题目链接:http://codeforces.com/problemset/problem/190/C
题目大意:输入中只会出现pair和int的字符串,要求按照给出pair和int的顺序,添加'<' , '>' , ','这三个符号,使得给出的串成为一个合法的类型.
题目思路:
(1)添加'<':很容易知道,当出现一个pair,后面必然要有一个'<';
(2)添加'>':当一个pair结束,后面就要添加一个'>'.
(3)添加',':当一个pair的前面一个类型结束,就要添加一个','.
符号匹配可以用栈.
枚举每个单词时检查栈顶的值,
如果栈顶的值是一个pair,那直接添加一个"int"或"pair<"就好了;
如果是半个pair,那就添加",int"或",pair<";
如果是一个结束的pair,那就添加">"(ps:这一步只可能在添加int时出现,因为一个pair的结束必然是添加int后)
代码:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define ull unsigned __int64
#define ll __int64
//#define ull unsigned long long
//#define ll long long
#define son1 New(p.xl,xm,p.yl,ym),(rt<<2)-2
#define son2 New(p.xl,xm,min(ym+1,p.yr),p.yr),(rt<<2)-1
#define son3 New(min(xm+1,p.xr),p.xr,p.yl,ym),rt<<2
#define son4 New(min(xm+1,p.xr),p.xr,min(ym+1,p.yr),p.yr),rt<<2|1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define middle (l+r)>>1
#define MOD 1000000007
#define esp (1e-8)
const int INF=0x3F3F3F3F;
const double DINF=10000.00;
//const double pi=acos(-1.0);
const int N=100010;
int n,m,tot;
char ch,word[N];
string str;
int pcnt,icnt;
template<class type>
class Stack{
private:
int size;
type elem[N];
public:
void clear(){size=0;}
void push(type a){elem[++size]=a;}
void pop(){size--;}
type top(){return elem[size];}
bool empty(){return size? false:true;}
};
Stack<int>s;
int main(){
//freopen("1.in","r",stdin);
//freopen("1.out","w",stdout);
int i=0,j=0,k;
//int T,cas=0;scanf("%d",&T);for(cas=1;cas<=T;cas++){
while(~scanf("%d",&m)){
getchar();
i=pcnt=icnt=0,s.clear(),str.clear();
while(ch=getchar()){
if(isalpha(ch)) word[i]=ch;
else if(ch==' '){
if(word[i]=='r') pcnt++;
else icnt++;
i++;
}
else{
if(word[i]=='r') pcnt++;
else icnt++;
i++;
if(pcnt+1!=icnt) puts("Error occurred");
else{
n=i;
if(n==1) puts("int");
else{
for(i=0;i<n;i++){
if(word[i]=='r'){
if(!s.empty()){
if(s.top()==2) s.pop(),s.push(1);
else s.pop(),s.push(0),str+=',';
}
str+="pair<",s.push(2);
}
else{
if(s.empty()) break;
else if(s.top()==2) s.pop(),s.push(1),str+="int";
else if(s.top()==1){
s.pop(),s.push(0),str+=",int";
if(!s.empty()){
if(s.top()==2) break;
else if(s.top()==0){
do{
s.pop(),str+=">";
}while(!s.empty() && !s.top());
}
}
}
}
if(s.empty()) break;
}
if(i!=n-1) puts("Error occurred");
else cout<<str<<endl;
}
}
break;
}
}
}
return 0;
}