POJ1068-Parencodings

转载请注明出处:優YoU http://user.qzone.qq.com/289065406/blog/1299127551

模拟的题型,基本难度不大,关键读懂题意:

对于给出的原括号串,存在两种数字密码串:

1.p序列:当出现匹配括号对时,从该括号对的右括号开始往左数,直到最前面的左括号数,就是pi的值。

2.w序列:当出现匹配括号对时,包含在该括号对中的所有右括号数(包括该括号对,就是wi的值。

题目的要求:对给出的p数字串,求出对应的s串。

串长限制均为20

 

提示:在处理括号序列时可以使用一个小技巧,把括号序列转化为01序列,左0右1,处理时比较方便

 

 1 //Memory  Time 
2 //256K 0MS
3
4 #include<iostream>
5 using namespace std;
6
7 int main(void)
8 {
9 int p[21]={0}; //使 p[0]=0
10 int w[20];
11 int str[40]; //括号串,左0右1
12 int n;
13
14 int cases;
15 cin>>cases;
16 while(cases--)
17 {
18 memset(str,0,sizeof(str)); //str串初始化为全0
19
20 cin>>n;
21
22 int i,j,k;
23
24 /*Input P-sequence*/
25
26 for(i=1;i<=n;i++)
27 cin>>p[i];
28
29 /*Convert the P-sequence to the string of parenthesese*/
30
31 for(j=0,i=1;i<=n;i++) //把P数列转化为01串,左括为0,右括为1
32 for(k=0;;k++)
33 if(k<p[i]-p[i-1]) //以每个右括为终点,把括号串分成多个01子串(子串左边全是0,右边只有唯一的1.每个子串至少含一个1)
34 j++; //k为各个子串的指针,j为str串的指针
35 else if(k==p[i]-p[i-1])
36 {
37 str[j++]=1;
38 break;
39 }
40
41 const int length=j; //str串长
42
43 /*Convert the string of parenthesese to the W-sequence*/
44
45 int count;
46 for(i=0;i<length;i++) //str串向W数列转换
47 if(str[i]==1) //在str中遇到1(右括)就回溯,找出离其最近的0(左括)
48 {
49 count=2; //计数器初始化为2是因为当前正在寻找的配对的01将置换为两个'F'
50 for(j=i-1;;j--)
51 {
52 if(str[j]==0)
53 {
54 str[i]=str[j]='F'; //01配对后就都置为'F'
55 break;
56 }
57 else
58 count++; //在回溯找0的过程中,每遇到一个F,计数器就+1
59 }
60 cout<<count/2<<' '; //计数器的个数就是当前 括号对 所包含的 括号对 (包括当前括号对)数量的两倍
61 }
62 cout<<endl;
63 }
64 return 0;
65 }

posted on 2011-07-29 19:38  小優YoU  阅读(962)  评论(0编辑  收藏  举报

导航