#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct Node;
typedef struct Node *position;
typedef struct Node *tree;
typedef struct collection *queue;
struct Node
{
int x;
position left, next;
};
struct collection
{
int size;
tree array[200];
};
queue merge(queue h1, queue h2);
tree combine(tree t1, tree t2);
void printTree(tree T, int k);
int main()
{
char y;
int x = 0;
queue H0, H; //用来存储新元素的一个二项队列,且永远只有一个元素
H0 = malloc(sizeof(struct collection));
H0->size = 1;
H = malloc(sizeof(struct collection));
H->size = 0;
do
{
y = getchar();
if (y != ',')
{
x = x * 10 + y - '0';
}
else
{
tree T = malloc(sizeof(struct Node));
T->left = T->next = NULL;
T->x = x;
H0->array[0] = T;
H = merge(H, H0);
H0->array[0] = NULL;
x = 0;
}
} while (y != '\n');
int k;
scanf("%d", &k);
printTree(H->array[k], k);
return 0;
}
queue merge(queue h1, queue h2)
{
tree t1, t2, carry = NULL;
int i, j;
h1->size = h1->size + h2->size;
for (i = 0, j = 1; j <= h1->size; j = j * 2, i++)
{
t1 = h1->array[i];
t2 = h2->array[i];
int judge = !!t1 + 2 * !!t2 + 4 * !!carry;
if (judge == 2)
{
h1->array[i] = t2;
h2->array[i] = NULL;
}
else if (judge == 4)
{
h1->array[i] = carry;
carry = NULL;
}
else if (judge == 3)
{
carry = combine(t1, t2);
h1->array[i] = h2->array[i] = NULL;
}
else if (judge == 5)
{
carry = combine(t1, carry);
h1->array[i] = NULL;
}
else if (judge == 6)
{
carry = combine(t2, carry);
h2->array[i] = NULL;
}
else if (judge == 7)
{
h1->array[i] = carry;
carry = combine(t1, t2);
h2->array[i] = NULL;
}
}
return h1;
}
void printTree(tree T, int k)
{
int num = pow(2, k);
position p = T;
if (T == NULL)
{
printf("0,");
}
else
{
for (int i = 1; i <= num; i++)
{
printf("%d,", p->x);
if (p->next == NULL)
{
p = p->left;
}
else
{
p = p->next;
}
}
}
}
tree combine(tree t1, tree t2)
{
if (t2->x < t1->x)
{
return combine(t2, t1);
}
position p = t1->left;
if (p == NULL)
{
t1->left = t2;
}
else
{
while (p->next != NULL)
{
p = p->next;
}
p->next = t2;
}
return t1;
}
Note:
打印的方法比较流氓,仅限于过oj
通用方法还是要用队列