您的位置:首页 > 其它

POJ 1068 Parencodings 模拟 栈操作

2013-09-01 11:35 417 查看
Parencodings

TimeLimit:1000MSMemoryLimit:10000K
TotalSubmissions:17398Accepted:10478
Description
LetS=s1s2...s2nbeawell-formedstringofparentheses.Scanbeencodedintwodifferentways:

qByanintegersequenceP=p1p2...pnwherepiisthenumberofleftparenthesesbeforetheithrightparenthesisinS(P-sequence).

qByanintegersequenceW=w1w2...wnwhereforeachrightparenthesis,sayainS,weassociateanintegerwhichisthenumberofrightparenthesescountingfromthematchedleftparenthesisofauptoa.(W-sequence).

Followingisanexampleoftheaboveencodings:

S		(((()()())))

P-sequence	456666

W-sequence	111456


WriteaprogramtoconvertP-sequenceofawell-formedstringtotheW-sequenceofthesamestring.

Input
Thefirstlineoftheinputcontainsasingleintegert(1<=t<=10),thenumberoftestcases,followedbytheinputdataforeachtestcase.Thefirstlineofeachtestcaseisanintegern(1<=n<=20),andthesecondline
istheP-sequenceofawell-formedstring.Itcontainsnpositiveintegers,separatedwithblanks,representingtheP-sequence.
Output
Theoutputfileconsistsofexactlytlinescorrespondingtotestcases.Foreachtestcase,theoutputlineshouldcontainnintegersdescribingtheW-sequenceofthestringcorrespondingtoitsgivenP-sequence.
SampleInput
2
6
456666
9
466668999

SampleOutput
111456
112451139


这道题的确英语有丝绕,看的纠结,但是大体意思就是有一串括号,序列P代表每一个右括号左面有多少个左括号,序列序列W代表每一个右括号左面第几个左括号是与之配对的左括号,然后给定P序列求W序列,这道题其实看到括号配对就要想到栈操作,先根据P序列还原原来的括号序列,主页君用了一个标记方法方便后面操作,还原后,正数代表左括号,负数代表右括号,数字代表其是第几个数,之后,就是栈操作,对每个数字判断,如果是正数,即左括号,则入栈,如果是负数,即右括号,此时将负数的变成相反的正数减去栈顶的数字除以2即为中间有多少对括号配对,也代表中间相隔多少个左括号,再+1就是右括号配对左括号是第几个左括号,将此序列再存入一个数组,待所有括号处理结束后,输出此数组即可AC。。。其实题目还是挺简单的。


下面是AC代码:


#include<cstdio>
#include<iostream>
#include<stack>
usingnamespacestd;
inta[25],b[25],c[100];
intmain()
{
inti,j,t,n,p,num;
stack<int>st;
scanf("%d",&t);
while(t--)
{
num=0;
cin>>n;
a[0]=0;
p=0;
for(i=1;i<=n;i++)
{
cin>>a[i];
for(j=p;j<p+a[i]-a[i-1];j++)
c[j]=j+1;
c[p+a[i]-a[i-1]]=-(p+a[i]-a[i-1]+1);
p=p+a[i]-a[i-1]+1;
}
j=0;
for(i=0;i<p;i++)
{
if(c[i]>0)
st.push(c[i]);
else
{
num=st.top();
st.pop();
num=(-c[i]-num)/2+1;
b[j]=num;
j++;
}
}
for(i=0;i<j-1;i++)
printf("%d",b[i]);
printf("%d\n",b[j-1]);
}
return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: