您的位置:首页 > 其它

PAT (Advanced Level) Practise 1130 Infix Expression (25)

2017-03-22 15:13 405 查看


1130. Infix Expression (25)

时间限制

400 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with parentheses reflecting the precedences of the operators.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N ( <= 20 ) which is the total number of nodes in the syntax tree. Then N lines follow, each gives the information of a node (the i-th line corresponds to the i-th
node) in the format:

data left_child right_child

where data is a string of no more than 10 characters, left_child and right_child are the indices of this node's left and right children, respectively. The nodes are indexed from 1 to N. The NULL link is represented
by -1. The figures 1 and 2 correspond to the samples 1 and 2, respectively.




Figure 1
Figure 2
Output Specification:

For each case, print in a line the infix expression, with parentheses reflecting the precedences of the operators. Note that there must be no extra parentheses for the final expression, as is shown by the samples. There must be no space between any symbols.
Sample Input 1:
8
* 8 7
a -1 -1
* 4 1
+ 2 5
b -1 -1
d -1 -1
- -1 6
c -1 -1

Sample Output 1:
(a+b)*(c*(-d))

Sample Input 2:
8
2.35 -1 -1
* 6 1
- -1 4
% 7 8
+ 2 3
a -1 -1
str -1 -1
871 -1 -1

Sample Output 2:

(a*2.35)+(-(str%871))

差不多是二叉树的中序遍历,直接建树遍历就好了。

#include<map>
#include<set>
#include<ctime>
#include<cmath>
#include<queue>
#include<string>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
#define ms(x,y) memset(x,y,sizeof(x))
#define rep(i,j,k) for(int i=j;i<=k;i++)
#define per(i,j,k) for(int i=j;i>=k;i--)
#define loop(i,j,k) for (int i=j;i!=-1;i=k[i])
#define inone(x) scanf("%d",&x)
#define intwo(x,y) scanf("%d%d",&x,&y)
#define inthr(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define infou(x,y,z,p) scanf("%d%d%d%d",&x,&y,&z,&p)
#define lson x<<1,l,mid
#define rson x<<1|1,mid+1,r
#define mp(i,j) make_pair(i,j)
#define ft first
#define sd second
typedef long long LL;
typedef pair<int, int> pii;
const int low(int x) { return x&-x; }
const int INF = 0x7FFFFFFF;
const int mod = 1e9 + 7;
const int N = 1e5 + 50;
const double eps = 1e-10;
int T, n;
int in
, ch
[2];
string s
;

void dfs(int x, int d)
{
if (x < 0) return;
int f = ch[x][0] < 0 && ch[x][1] < 0;
if (d && !f) putchar('(');
dfs(ch[x][0], d + 1);
cout << s[x];
dfs(ch[x][1], d + 1);
if (d && !f) putchar(')');
}

int main()
{
inone(n);
rep(i, 1, n)
{
cin >> s[i] >> ch[i][0] >> ch[i][1];
if (ch[i][0] >= 0) in[ch[i][0]]++;
if (ch[i][1] >= 0) in[ch[i][1]]++;
}
rep(i, 1, n) if (!in[i]) dfs(i, 0);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: