話說這道題代碼那個醜陋啊,,寫出來我自己都不想再看第二遍啊。。。看了看聰神的代碼,還消耗我3個NYOJ币啊,,更扯得是,聰神的代碼我看不懂啊,,,,卧槽。。。這道題不再多說了,資料結構上有詳細的介紹,主要就是輸入的時候巧妙利用sscanf()函數就可以了。。題目:
郁悶的C小加(一)
時間限制:1000 ms | 記憶體限制:65535 KB
難度:3
- 描述
-
我們熟悉的表達式如a+b、a+b*(c+d)等都屬于中綴表達式。中綴表達式就是(對于雙目運算符來說)操作符在兩個操作數中間:num1 operand num2。同理,字尾表達式就是操作符在兩個操作數之後:num1
num2 operand。ACM隊的“C小加”正在郁悶怎樣把一個中綴表達式轉換為字尾表達式,現在請你設計一個程式,幫助C小加把中綴表達式轉換成字尾表達式。為簡化問題,操作數均為個位數,操作符隻有+-*/ 和小括号。
- 輸入
-
第一行輸入T,表示有T組測試資料(T<10)。
每組測試資料隻有一行,是一個長度不超過1000的字元串,表示這個表達式。這個表達式裡隻包含+-*/與小括号這幾種符号。其中小括号可以嵌套使用。資料保證輸入的操作數中不會出現負數。并且輸入資料不會出現不比對現象。
- 輸出
- 每組輸出都單獨成行,輸出轉換的字尾表達式。
- 樣例輸入
-
21+2(1+2)*3+4*5
- 樣例輸出
-
12+12+3*45*+
ac代碼:
#include <iostream>
#include <cstdio>
#include <string.h>
#include <string>
#include <stack>
using namespace std;
struct oper{
char op;
int level;
}p;
int fun(char cc){
if(cc=='+'||cc=='-')
return 1;
else if(cc=='*'||cc=='/')
return 2;
else if(cc=='(')
return 3;
else if(cc==')')
return 0;
}
int main(){
int numcase;
scanf("%d",&numcase);
while(numcase--){
string str;
cin>>str;
int len=str.size(),pos=0,ll=0,num=0;
char ch;
stack<oper> ss;
p.op=' ';p.level=0;ss.push(p);
while(pos<len){
if(str[pos]<='9'&&str[pos]>='0'){
sscanf(&str[pos],"%d%n",&num,&ll);
printf("%d",num);
pos+=ll;
}
else{
sscanf(&str[pos],"%c%n",&ch,&ll);
pos+=ll;p.op=ch;p.level=fun(ch);
if(p.op==')'){
while(ss.top().op!='('){
printf("%c",ss.top().op);
ss.pop();
}
ss.pop();
}
else if(p.level>ss.top().level||ss.top().op=='(')
ss.push(p);
else{
while(p.level<=ss.top().level&&ss.top().op!='('){
printf("%c",ss.top().op);
ss.pop();
}
ss.push(p);
}
}
}
while(!ss.empty()){
printf("%c",ss.top().op);
ss.pop();
}
printf("\n");
}
return 0;
}