POJ_1068_Parencodings(构造法)

/*
题意:有一组格式匹配的字符串括号,即每个左括号都有右括号相匹配;
他有两种描述形式,
P:每一给右括号的左边有多少左括号;
w:每一个右括号的左边有多少成对的括号;
输入p;
输出w;
解题思路,先由给出的p求出括号字符串用栈存储;
然后遍历栈,遇到')',从当前位置往前找,设置w=1,
代表右括号的数目,count=0,代表匹配括号的数目;
那么在找的过程中

遇到')'说明有成对的括号,w+1,coung+1;
遇到'(',那么右括号w-1;
当w=0时就代表已经找完了。
*/

 1 # include <stdio.h>
 2 struct node
 3 {
 4     char ch[1000];
 5     int top;
 6 }p; 
 7 int main()
 8 {
 9     int i,j,count,n,a[50],k,w,leag;
10     scanf("%d",&k);
11     while(k--)
12     {
13         leag=0;
14         scanf("%d",&n);
15         a[0]=0;
16         p.top=0;
17         for(i=1;i<=n;i++)
18         {
19             scanf("%d",&a[i]);
20         }
21         for(i=1;i<=n;i++)
22         {
23             for(j=0;j<a[i]-a[i-1];j++)
24             {
25                 p.ch[p.top++]='(';
26             }
27             p.ch[p.top++]=')';
28         }
29         p.ch[p.top]='\0';
30         for(i=0;i<p.top;i++)
31         {
32             if(p.ch[i]==')')
33             {
34                 w=1;count=0;
35                 for(j=i-1;j>=0;j--)
36                 {
37                     if(p.ch[j]==')')
38                     {
39                         w++;
40                         count++;
41                     }
42                     else 
43                         w--;
44                     if(w==0)break;    
45                 }
46                 if(leag)
47                     printf(" ");
48                 leag++;
49                 printf("%d",count+1);
50             }
51         }
52         printf("\n");
53     }
54     return 0;
55 }
View Code

 

posted on 2013-08-09 16:31  随风浪子的博客  阅读(122)  评论(0编辑  收藏  举报

导航