pat甲级1130 Infix Expression(测试点4错了进来看)

19分代码 (如下)

 这个是因为运算符号只用了5种,但其实题目并没有告诉你运算符号有哪几个,所以这些运算符号更深的共同点是都是非叶子节点。

#include <bits/stdc++.h>
typedef long long ll ;
using namespace std ;
const int maxn = 3e1 + 10 ;
const int inf = 0x3f3f3f3f ;
int d[maxn] ;
struct node{
	string s ;
	int u , v ;
}l[maxn];
void dfs(int root , int h){
	if((h != 0) && (l[root].s == "%" || l[root].s == "*" || l[root].s == "-" || l[root].s == "+" || l[root].s == "/"))
		cout << "(" ;
	if(l[root].v != -1 && l[root].u == -1) {
		cout << l[root].s ;
		dfs(l[root].v , h+1) ;
	}else{
		if(l[root].u != -1)
			dfs(l[root].u , h+1) ;
		cout << l[root].s ;
		if(l[root].v != -1)
			dfs(l[root].v , h+1) ;
	}
	if((h != 0) && (l[root].s == "%" || l[root].s == "*" || l[root].s == "-" || l[root].s == "+" || l[root].s == "/"))
		cout << ")" ;
}
void deal(){
	int n ; cin >> n ;
	for(int i = 1 ; i <= n ; i++){
		cin >> l[i].s >> l[i].u >> l[i].v ;
		d[l[i].u]++ ;
		d[l[i].v]++ ;
	}
	int root = -1 ;
	for(int i = 1 ; i <= n ; i++){
		if(d[i] == 0) root = i ;
	}
	dfs(root , 0) ;
} 
int main(){
	deal() ;
    return 0 ;
}

AC代码

#include <bits/stdc++.h>
typedef long long ll ;
using namespace std ;
const int maxn = 3e1 + 10 ;
const int inf = 0x3f3f3f3f ;
int d[maxn] ;
struct node{
	string s ;
	int u , v ;
}l[maxn];
void dfs(int root , int h){
	if((h != 0) && !(l[root].v == -1 && l[root].u == -1))
		cout << "(" ;
	if(l[root].v != -1 && l[root].u == -1) {
		cout << l[root].s ;
		dfs(l[root].v , h+1) ;
	}else{
		if(l[root].u != -1)
			dfs(l[root].u , h+1) ;
		cout << l[root].s ;
		if(l[root].v != -1)
			dfs(l[root].v , h+1) ;
	}
	if((h != 0) && !(l[root].v == -1 && l[root].u == -1))
		cout << ")" ;
}
void deal(){
	int n ; cin >> n ;
	for(int i = 1 ; i <= n ; i++){
		cin >> l[i].s >> l[i].u >> l[i].v ;
		d[l[i].u]++ ;
		d[l[i].v]++ ;
	}
	int root = -1 ;
	for(int i = 1 ; i <= n ; i++){
		if(d[i] == 0) root = i ;
	}
	dfs(root , 0) ;
} 
int main(){
	deal() ;
    return 0 ;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值