比赛 |
板子大赛 |
评测结果 |
AAAAAAAAAA |
题目名称 |
表达式树 |
最终得分 |
100 |
用户昵称 |
喵喵喵 |
运行时间 |
0.030 s |
代码语言 |
C++ |
内存使用 |
3.33 MiB |
提交时间 |
2025-01-22 11:01:24 |
显示代码纯文本
#include <bits/stdc++.h>
using namespace std;
const int N = 52;
struct bt
{
int parent;
int l;
int r;
char data = ' ';
int number;
};
bt bt[2*N-1];
char ch[10000];
int ind = 0;
void trans(int root)
{
if(bt[root].l)
{
trans(bt[root].l);
}
if(bt[root].r)
{
trans(bt[root].r);
}
if(bt[root].data == ' ')
{
stack<int> pri;
while(bt[root].number != 0)
{
pri.push(bt[root].number % 10);
bt[root].number /= 10;
}
while(!pri.empty())
{
ch[ind] = pri.top() + '0';
ind = ind+1;
pri.pop();
}
ch[ind] = '#';
ind = ind+1;
}
else
{
ch[ind] = bt[root].data;
ind++;
}
}
void cal(int len)
{
int arr[55], num = 0,top = 0;
for (int i = 0; i < len; i++)
if (ch[i] >= '0' && ch[i] <= '9')
num = num * 10 + (ch[i] - '0');
else if (ch[i] == '#')
arr[++top] = num, num = 0;
else if (ch[i] == '+')
arr[--top] += arr[top + 1];
else if (ch[i] == '-')
arr[--top] -= arr[top + 1];
else if (ch[i] == '*')
arr[--top] *= arr[top + 1];
else if (ch[i] == '/')
arr[--top] /= arr[top + 1];
cout << arr[top] << endl;
}
int main()
{
freopen("expr_tree.in","r",stdin);
freopen("expr_tree.out","w",stdout);
int n;
cin >> n;
for(int i = 1;i <= n;i++)
{
int a;
cin >> a;
bt[i].number = a;
}
for(int i = n + 1;i <= 2*n-1;i++)
{
char op;
cin >> op;
int a,b;
cin >> a >> b;
bt[i].data = op;
bt[i].l = a;
bt[a].parent = i;
bt[i].r = b;
bt[b].parent = i;
}
int root = 0;
for(int i = 1;i <= 2*n-1;i++)
{
if(bt[i].parent == 0)
{
root = i;
}
}
trans(root);
cal(ind);
}