Codeforces 902 C.Hashing Trees 树的同构

来源:互联网 发布:如何看待网络用语 编辑:程序博客网 时间:2024/05/21 11:32

题意

给定树高h(2–1e5),然后h+1个数(2e5)(总和<2e5)表示每层的节点数.
问这样的表示是否存在多个非同构树.
如果不存在,输出perfect.
否则输出ambiguous,然后输出两个满足条件的父节点表示形式的树.

解法

第一层(根节点)一定只有一个点.
由样例得,如果连续两层都有大于一个点,那么为ambiguous.
没有其他ambiguous的情况.
主算法很清晰,本题难度主要在代码细节部分.

输出树时,默认情况让所有下一层的节点的父节点都为上一层最后一个.
而在ambiguous的位置,让下一层的节点的父节点分别指向上一层的倒数第二个和最后一个.

注意

这种思路简单,但是代码难度大的题
1.明确变量名字,包括循环的索引变量.
2.对于数组的遍历,一定要清楚从0还是从1开始,一共遍历多少个
3.对于循环中的选择结构,尽量提前跳出,减少缩进层数.

代码

/* LittleFall : Hello! */#include <bits/stdc++.h>using namespace std;int save[200016];int main(void){    int h;    scanf("%d", &h);    for(int i = 0; i <= h; i++)        scanf("%d", &save[i]);    int position = 0;    for(int h_index = 1; h_index <= h; h_index++)    {        if(save[h_index] > 1 && save[h_index - 1] > 1)        {            position = h_index;            break;        }    }    if(position == 0)    {        printf("perfect\n");        return 0;    }    printf("ambiguous\n");    int item = 0;    for(int h_index = 0; h_index <= h; h_index++)    {        if(h_index==position)        {            for(int item_index = 0; item_index < save[h_index]-1; item_index++)                printf("%d ",item-1 );            printf("%d ",item );        }        else            for(int item_index = 0; item_index < save[h_index]; item_index++)                printf("%d ", item );        item += save[h_index];    }    printf("\n");    item = 0;    for(int h_index = 0; h_index <= h; h_index++)    {        for(int item_index = 0; item_index < save[h_index]; item_index++)            printf("%d ", item );        item += save[h_index];    }    printf("\n");    return 0;}

AC时间:5分钟

原创粉丝点击