Let S = s1 s2 ... s2n be a well-formed string of parentheses. S can be encoded in two different ways:
- 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).
- 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 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
这是一道模拟题,题意为输入的为一组数,每个位置的数表示当前右括号前左括号的个数:
如4 5 6 6 6 6 为(((()()())))
那么输出为当前的位置的右括号与左括号配对,需越过的左括号的个数(包括配对的左括号),可以看到:
第一个右括号,就与它前面第一个左括号配对,那么就输出1;以此类推。
我们可以非常轻易的发现规律:
如果我们计算出每个位置当前所拥有的括号数,即第1个位置有4个左括号,第二个位置有5-4=1个左括号,我们可以得到一组数:
4 1 1 0 0 0
那么,第1个右括号,用掉自身的一个左括号,变为3 1 1 0 0 0
第2个右括号,用掉自身的一个左括号,变为3 0 1 0 0 0
第3个右括号,用掉自身的一个左括号,变为3 0 0 0 0 0
第4个右括号,它自身位置没有右括号,向前搜索,找寻配对的左括号,需越过的左括号数:第2个位置,现在为0,越过左括号数为(1-0);第1个位置,现在为0,越过的左括号数为(1-0);第0个位置,现在为3,匹配左括号,左括号数减1,变为2,越过的左括号数为(4-2)。
那么越过的左括号数为:(1-0)+(1-0)+(4-2)=4
我们总结规律,第i个位置的右括号配对经过的左括号数:
当第i个位置有左括号时,为1,并且当前位置左括号数减1;
当第i个位置没有左括号时,j从i-1遍历至于0,左括号数=
if(j位置左括号数为0)
{
左括号数+=j位置原左括号数;
}
else
{
j位置原左括号数--;
左括号数+=j位置原左括号数-j位置当前左括号数;
}
代码如下:
#include<stdio.h>
#define MAXLEN 20
int testNum,n,num[MAXLEN],i,j,num1[MAXLEN],index1,num2[MAXLEN];
int main()
{
scanf("%d",&testNum);
while(testNum>0)
{
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&num[i]);
num1[i]=num[i];
//计算当前位置的左括号数,不算它前方位置包含的
if(i!=0)
{
num[i]=num1[i]-num1[i-1];
num2[i]=num[i];
//需要越过的左括号数
//如果立即有左括号配对,即自己本身有左括号,那么为1
//否则等于它前方的右括号数加1,即它本身的位置
if(num[i]!=0)
{
printf(" 1");
num[i]--;
}
else
{
index1=0;
for(j=i;j>=0;j--)
{
if(num[j]!=0)
{
num[j]--;
index1+=num2[j]-num[j];
break;
}
else
{
index1+=num2[j];
}
}
printf(" %d",index1);
}
}
else
{
printf("1");
num2[i]=num[i];
num[i]--;
}
}
printf("\n");
testNum--;
}
system("pause");
return 0;
}