■ ヒープ(平成14年午後1問5)
#include <stdio.h>
#include <time.h>
/* 平成14年午後1問5 */
#define N 255
struct QUE {
unsigned pri;
long time;
unsigned id;
} Q[N];
unsigned n = 0;
void put(unsigned priority, unsigned id)
{
struct QUE t;
unsigned r;
n++;
Q[n].pri = priority;
Q[n].id = id;
Q[n].time = time(NULL);
r = n;
while (r != 1 && Q[r/2].pri > Q[r].pri) {
t = Q[r];
Q[r] = Q[r/2];
Q[r/2] = t;
r /= 2;
}
}
unsigned get()
{
struct QUE t;
unsigned id, r;
id = Q[1].id;
Q[1] = Q[n];
n--;
r = 1;
while (n >= 2*r) {
if (Q[r].pri < Q[r*2].pri && Q[r].pri < Q[r*2+1].pri) break;
if (n < 2*r+1 || Q[r*2].pri < Q[r*2+1].pri) {
t = Q[r];
Q[r] = Q[r*2];
Q[r*2] = t;
r *= 2;
} else if (Q[r*2].pri > Q[r*2+1].pri) {
t = Q[r];
Q[r] = Q[r*2+1];
Q[r*2+1] = t;
r = r*2+1;
}
}
return id;
}
void print_que()
{
unsigned i;
for (i = 1; i <= n; i++)
printf("%2u ", Q[i].pri);
putchar('\n');
}
int main()
{
put(2, 1);
put(5, 2);
put(11, 3);
put(8, 4);
put(13, 5);
put(15, 6);
put(12, 7);
put(9, 8);
put(10, 9);
printf("初期値 :");
print_que();
get();
printf("getのあと:");
print_que();
put(6, 10);
printf("putのあと:");
print_que();
return 0;
}