Let S = s1 s2…s2n be a well-formed string of parentheses. S can be encoded in two different ways:
q By an integer sequence P = p1 p2…pn where pi is the number of left parentheses before the ith right parenthesis in S (P-sequence).
q By an integer sequence W = w1 w2…wn where for each right parenthesis, say a in S, we associate an integer which is the number of right parentheses counting from the matched left parenthesis of a up to a. (W-sequence).
Following is an example of the above encodings:
S (((()()()))) P-sequence 4 5 6666 W-sequence 1 1 1456
Write a program to convert P-sequence of a well-formed string to the W-sequence of the same string.
Input
The first line of the input contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case is an integer n (1 <= n <= 20), and the second line is the P-sequence of a well-formed string. It contains n positive integers, separated with blanks, representing the P-sequence.
Output
The output file consists of exactly t lines corresponding to test cases. For each test case, the output line should contain n integers describing the W-sequence of the string corresponding to its given P-sequence.
Sample Input
2 6 4 5 6 6 6 6 9 4 6 6 6 6 8 9 9 9
Sample Output
1 1 1 4 5 6
1 1 2 4 5 1 1 3 9
题意:
s是一组括弧。有两种编码方法。 方法一,可获得数列P。其中每个Pi是指在第i个右括弧左边的左括弧数目。(((()比如以上在第一个右括弧左边有4个左括弧。所以P1是4,p2是5... 方法二,可获得数列W。把这堆括弧左右一一对应起来。从第一个右括号数起,每个wi是指第i个右括号与对应的左括号之间的完整括号数,包括他本身
方法一:
#include<stdio.h>
#include<string.h>
int main()
{
int i,l,j,a[1000],b[1000],q=0;
char c[1000];
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));//初始化
int m,n,t;
scanf("%d",&m);
while(m--)
{
q=0;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
//将p数列转化为括号字符串,存在字符数组C中
for(i=0;i<a[0];i++)
c[i]='(';//c[a[0]]左边的都是“(”
c[a[0]]=')';
t=a[0]+1;//继续下去转化
for(i=1;i<n;i++)
{
int s=a[i]-a[i-1];
for(j=t;j<t+s;j++)
c[j]='(';
t=t+s;
c[t]=')';
t=t+1;
}
j=0;
int k=0,q;
for(i=0;i<t;i++)
{
if(c[i]==')')
{
k=0;
if(c[i-1]=='(')
{
c[i]='}';
c[i-1]='{';
k=1;
}//当左右括号相邻时,所包含的括号数是1,并将找过的括号用“{ ”,“}”标记
else
{
c[i]='}';
for(q=i-1;;q--)
{
if(c[q]=='{')
k=k+1;
else if(c[q]=='(')
{
k=k+1;
c[q]='{';
break;
}
else
continue;
}//从遇到')'的位置往后找,遇到标记过的,括号数加1,直到遇到')'为止
}
b[j++]=k;//将得到的括号数存入数组
}
}
for(i=0;i<j-1;i++)
printf("%d ",b[i]);
printf("%d\n",b[j-1]);
}
return 0;
}
方法二:
#include<stdio.h>
int main()
{
int count;
int n,j,i,a[1000],w[1000],p[1000];
scanf("%d",&count);
while(count--)
{
scanf("%d",&n);
for(i=1;i<=n;i++) scanf("%d",&p[i]);
a[0]=p[1];
for(i=1;i<n;i++) a[i]=p[i+1]-p[i];
for(i=1;i<=n;i++)
{
for(j=i-1;j>=0;j--)
{
if(a[j]>0)
{
a[j]--;
break;
}
}
w[i]=i-j;
}
for(int i=1;i<n;i++)printf("%d ",w[i]);
printf("%d\n",w[n]);
}
return 0;
}