比赛 |
板子大赛 |
评测结果 |
AAAAAAAAAA |
题目名称 |
表达式树 |
最终得分 |
100 |
用户昵称 |
AeeE5x |
运行时间 |
0.030 s |
代码语言 |
C++ |
内存使用 |
3.52 MiB |
提交时间 |
2025-01-22 10:47:07 |
显示代码纯文本
#include<iostream>
using namespace std;
struct node{
int lch,rch,fa;
long long val;
}t[210];
int n;
int tp(char x){
if(x=='+') return 1;
if(x=='-') return 2;
if(x=='*') return 3;
if(x=='/') return 4;
}
long long dfs(int p){
if(p<=n) return t[p].val;
if(t[p].val==1) return dfs(t[p].lch)+dfs(t[p].rch);
if(t[p].val==2) return dfs(t[p].lch)-dfs(t[p].rch);
if(t[p].val==3) return dfs(t[p].lch)*dfs(t[p].rch);
if(t[p].val==4) return dfs(t[p].lch)/dfs(t[p].rch);
}
int main(){
freopen("expr_tree.in","r",stdin);
freopen("expr_tree.out","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;i++){
int x;scanf("%d",&x);
t[i].val=x;
}
for(int i=n+1;i<=n*2-1;i++){
char c;int lc,rc;scanf(" %c%d%d",&c,&lc,&rc);
t[i].lch=lc;
t[i].rch=rc;
t[i].val=tp(c);
t[lc].fa=t[rc].fa=i;
}
int root=1;
while(t[root].fa) root=t[root].fa;
printf("%lld",dfs(root));
return 0;
}