S-Trees(二叉树)

来源:互联网 发布:搜索电影免费网络观看 编辑:程序博客网 时间:2024/05/22 03:34

Question:题目详情(http://vjudge.net/contest/134361#problem/E)
题目大意:有一个n层的满二叉树,每个子节点都对应了一个确定的值(共2^n个),有m个访问值,每个访问值由n个0,1组成,0表示走左子节点,1表示走右子节点,这样每个访问值都对应了原二叉树的子节点的一个确定的值,最后输出m个访问值
解题思路:先用一个数组保存下2^n个节点的值,然后将输入的每个访问值,由二进制转化为10进制数,然后找到对应的保存节点数组的值,用另一个数组保存答案

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>using namespace std;const int maxn=500005;int a[maxn],ans[maxn],ncase;  //ans保存答案,a保存节点的值int main(){    int n,m;    while(scanf("%d",&n),n)    {        for(int i=1;i<=n;i++)        {            char c;            int k;            getchar();            scanf("%c%d",&c,&k);   //这里的输入个人理解没有太大的意义        }        for(int i=0;i<pow(2,n);i++)            scanf("%1d",&a[i]);  //保存各个节点的值        scanf("%d",&m);        for(int i=1;i<=m;i++)        {            int sum=0;            for(int j=1;j<=n;j++)            {                int tp;                scanf("%1d",&tp);                if(tp)                    sum+=pow(2,n-j);  //将输入的访问值变为十进制数            }            ans[i]=a[sum];  //最终答案保存在ans数组里        }        printf("S-Tree #%d:\n",++ncase);        for(int i=1;i<=m;i++)            printf("%d",ans[i]);        printf("\n\n");  //注意,这里输出之间隔了一行    }    return 0;}

体会:这道题没有太大的难度,只要想通了,自然迎刃而解了

0 0
原创粉丝点击