码迷,mamicode.com
首页 > 其他好文 > 详细

【BUAA 591】The Last Alpha Star

时间:2015-06-20 17:08:11      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:binarytree

【BUAA 591】The Last Alpha Star

二叉树 建树后DFS输出符合路径
最主要坑在建树。。。费了些神 还是不够

代码

#include

using namespace std;

typedef struct Node Node;
typedef struct Node *Nd;

typedef struct Node
{
    int data;
    Nd r,l;
}Node;

int d,tp,f;
int num[5555];

bool SetTree(Nd *t)
{
    (*t) = (Nd)malloc(sizeof(Node));
    char ch;
    int x = 0,f = 0;
    ch = getchar();
    while(ch == ‘\n‘ || ch == ‘\r‘) ch = getchar();
    while(ch >= ‘0‘ && ch <= ‘9‘)
    {
        f = 1;
        x = x*10+ch-‘0‘;
        ch = getchar();
    }
    if(f)
    {
        (*t)->data = x;
    }
    else (*t) = NULL;
   // cout<<tp<<" "<<x<<endl;
    if(ch == ‘(‘)
    {
        tp++;
        if(SetTree(&((*t)->l))) getchar();
        if(SetTree(&((*t)->r))) getchar();
        tp--;
        return 1;
    }
    else
    {
        if(f)
        {
            (*t)->l = NULL;
            (*t)->r = NULL;
        }
        return 0;
    }
}

void Dfs(int sum,Nd t)
{
    //cout<<sum<<endl;
    int i;
    if(t->l == NULL && t->r == NULL && sum == d)
    {
        f = 1;
        for(i = 0; i < tp;++i)
        {
            if(i) printf(" ");
            printf("%d",num[i]);
        }
        printf("\n");
    }else if(sum > d) return;

    if(t->l)
    {
        num[tp++] = t->l->data;
        Dfs(sum+num[tp-1],t->l);
        tp--;
    }
    if(t->r)
    {
        num[tp++] = t->r->data;
        Dfs(sum+num[tp-1],t->r);
        tp--;
    }
}

int main()
{
    //freopen("in.txt","r",stdin);
    int t,z = 0;
    scanf("%d",&t);
    char ch;
    while(t--)
    {
        d = 0;
        Nd tr;
        SetTree(&tr);
        ch = getchar();
        tp = 0;
        while(ch == ‘\n‘) ch = getchar();
        while(ch != ‘\n‘ && ch != ‘\r‘)
        {
            d = d*10+ch-‘0‘;
            ch = getchar();
        }
        tp = f = 0;
        printf("Case %d:\n",++z);
        num[tp++] = tr->data;
        Dfs(num[0],tr);
        if(!f) printf("I am so sorry!\n");
    }
    return 0;
}

【BUAA 591】The Last Alpha Star

标签:binarytree

原文地址:http://blog.csdn.net/challengerrumble/article/details/46574111

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!