题解:有模板。。先根据括号建树,然后用深搜存每条路径的和,最后循环对比,注意负数情况。
#include <stdio.h>
#include <string.h>
const int N = 10010;
struct Node {
int val;
Node* left;
Node* right;
Node () {
val = 0;
left = right = NULL;
}
};
int k, sum[N];
void init() {
k = 0;
memset(sum, 0, sizeof(sum));
}
Node* build() {
int flag = 0, flag1 = 0;
Node* node = new Node;
char c;
while (scanf("%c", &c)) {
if (c >= '0' && c <= '9')
node -> val = node -> val * 10 + c - '0';
else if (c == '(' && flag == 0) {
node -> left = build();
flag++;
}
else if (c == '(' && flag == 1)
node -> right = build();
else if (c == '-')
flag1 = 1;
else if (c == ')')
break;
}
if (flag1)
node -> val *= -1;
if (flag == 0 && node -> val == 0)
return NULL;
else
return node;
}
void dfs(Node* node, int s) {
if (node == NULL)
return;
s += node -> val;
if (node -> left == NULL && node -> right == NULL)
sum[k++] = s;
else {
if (node -> left != NULL)
dfs(node -> left, s);
if (node -> right != NULL)
dfs(node -> right, s);
}
}
void Delete(Node* node) {
if (node == NULL)
return;
if (node -> left != NULL)
Delete(node -> left);
if (node -> right != NULL)
Delete(node -> right);
delete node;
}
int main() {
int n;
char c;
Node* root;
while (scanf("%d", &n) != EOF) {
init();
while (scanf("%c", &c)) {
if (c == '(') {
root = build();
break;
}
}
dfs(root, 0);
int i;
for (i = 0; i < k; i++)
if (sum[i] == n)
break;
if (i == k)
printf("no\n");
else
printf("yes\n");
Delete(root);
}
return 0;
}