天天看點

UVA 112 Tree Summing

~~題目連結~~

題目大意:用()表示空節點, (5)表示一個為5的節點, 5()() 表示葉子節點, 5(2)(6)表示目前節點為5, 左節點為2,右節點為6.現在給出一串字元串, 求是否有根節點到葉節點的值等于給定的值。

code:

#include <iostream>
#include <algorithm>
using namespace std;

typedef struct node
{
    int num;
    struct node *lf, *rt;
}Node;

int n = 0, ans = 0;

int trans(string &s, int &start)//轉換為數字
{
    int flag = 0, sum = 0;
    if(s[start] == '-') flag = 1, start++;
    else sum += s[start++]-'0';
    while(s[start] != '(' && s[start] != ')')
    {
        sum *= 10;
        sum += s[start++]-'0';
    }
    if(flag) sum = -sum;
    return sum;
}

int build(Node *r, string &s,int &cur, int sum)
{
    int cur_sum = 0;
    r->lf = new Node;
    r->rt = new Node;

    if(s[cur] == ')' && s[cur+1] == '(' && s[cur+2] == ')')//上一個節點為葉子節點
    {
        cur += 3;
        return 1;
    }
    else if(s[cur] != '(' && s[cur] != ')')
        r->num = trans(s, cur);

    cur_sum = sum+r->num;
    if(s[cur] == '(')//左子樹
       if(build(r->lf, s, ++cur, cur_sum))//為葉節點判斷
       {
           if(cur_sum == n)
               ans = 1;
       }

    if(s[cur] == '(')//右子樹
       if(build(r->rt, s, ++cur, cur_sum))
        if(cur_sum == n) ans = 1;
    if(s[cur] == ')') cur++;
    return 0;
}

int main()
{
    int i = 0, j = 0, num = 0, flag = 1;//flag判斷讀取樹沒
    string s, res;
    while(cin>>n)
    {
        num = ans = 0;
        Node *r = new Node;
        res = "";//為最終的字元串
        do
        {
            getline(cin, s);
            string::iterator it = remove(s.begin(),s.end(), ' ');
            s.erase(it, s.end());
            for(i = 0; i<s.size(); i++)
                if(s[i] == '(') num++, flag = 0;
                else if(s[i] == ')') num--;
            res += s;
        }
        while(num || flag);
        if(res[1] != ')')//讀出根節點的數
        {
            i = 1;
            r->num = trans(res, i);
            res.erase(res.end()-1);
            res.erase(res.begin(), res.begin()+i);
        }
        i = 0;
        build(r, res, i, 0);
        if(ans) cout<<"yes"<<endl;
        else cout<<"no"<<endl;
    }
    return 0;
}
           

繼續閱讀