-
Notifications
You must be signed in to change notification settings - Fork 3
/
112-TreeSumming.cpp
executable file
·110 lines (102 loc) · 1.6 KB
/
112-TreeSumming.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//
// 112 - Tree Summing.cpp
// Uva
//
// Created by Alexander Faxå on 2012-05-11.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <cstdlib>
using namespace std;
struct vertex
{
vertex* left, *right;
int number;
bool isLeaf;
};
vertex *root;
int destsum;
void readTree(vertex* v)
{
char c;
(*v).number = 0;
int sign = 1;
bool first = true;
while(true)
{
cin >> c;
if(isdigit(c))
{
if(first)
{
first = false;
(*v).isLeaf = false;
v->left = new vertex();
(*(v->left)).isLeaf = true;
v->right = new vertex();
(*(v->right)).isLeaf = true;
}
(*v).number = (*v).number*10+(int)(c-'0');
}
else if(c == '-')
sign *= -1;
else if(c == '(')
{
readTree(v->left);
do {
cin >> c;
} while (c != '(');
readTree(v->right);
do {
cin >> c;
} while (c != ')');
(*v).number *= sign;
break;
}
else if(c == ')')
{
break;
}
}
}
bool ok;
void calc(vertex* cur, int cursum)
{
cursum += (*cur).number;
if((*cur).isLeaf)
return;
if((*(cur->left)).isLeaf && (*(cur->right)).isLeaf)
{
if(cursum == destsum)
ok = true;
return;
}
if(!(*(cur->right)).isLeaf)
calc(cur->right, cursum);
if(!(*(cur->left)).isLeaf)
calc(cur->left, cursum);
}
int main()
{
while(cin >> destsum)
{
char c;
do {
cin >> c;
} while (c != '(');
root = new vertex();
(*root).isLeaf = true;
readTree(root);
ok = false;
calc(root, 0);
if(ok)
cout << "yes" << endl;
else
cout << "no" << endl;
}
return 0;
}