这题WA死了,5Y。。。
开始没想到还有负数的可能,送了2个WA,一次是犯2忘关调试了,还有一次是 0 () 这组数据没处理
好久没写模拟了,太没状态了,哎,还好把代码给压缩到了100以内
附上AC代码~
#include <stdio.h>
#include <string.h>
struct Node
{
int l, r, v;
};
Node node[101000];
int num, sum;
char str[2048],stack[101000];
bool flag;
void build(int l, int r, int &fa)
{
if ( r-l == 1 )
{
fa = 0;
return;
}
int t = sum++, j;
fa = t;
int len = 0, temp = 0, fh = 1, left = l;
if ( stack[l+1] == '-' )
{
fh=-1;
left++;
}
for ( int i = left+1 ; i < r && ('0' <= stack[i] && stack[i] <= '9' ) ; i++, len++ )
temp=temp*10+stack[i]-'0';
node[t].v=temp*fh;
for ( int i = left+2+len , k = 1 ; i < r && k ; i++ )
{
if (stack[i]==')')
k--;
else if (stack[i]=='(')
k++;
if (!k)
j = i;
}
build(left+len+1, j, node[t].l);
build(j+1, r-1, node[t].r);
}
void dfs(int p, int n)
{
node[p].v+=n;
if (node[p].l)
dfs(node[p].l, node[p].v);
if (node[p].r)
dfs(node[p].r, node[p].v);
if (!node[p].l&&!node[p].r)
if (node[p].v==num)
flag = 1;
}
int main()
{
while ( EOF != scanf("%d", &num) )
{
memset(stack, 0, sizeof(stack));
memset(node, 0, sizeof(node));
int top = 0, k = 0;
for ( int i = 0 ; top == 0 || k ; i = 0)
{
gets(str);
for ( int len = strlen(str) ; i < len ; i++ )
{
while ( ' ' == str[i] ) i++;
if ( '(' == str[i] )
{
k++;
stack[top++]=str[i];
}
else if( ')' == str[i] )
{
k--;
stack[top++]=str[i];
}
else if (('0' <= str[i] && str[i] <= '9') || ( '-' == str[i] ))
stack[top++]=str[i];
}
}
sum = 1;
flag = 0;
build(0, top-1, node[0].r);
if ( top == 2 )
puts("no");
else
{
dfs(1, 0);
flag ? puts("yes"): puts("no");
}
}
return 0;
}