Parencodings
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 17398 | Accepted: 10478 |
Description
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:
Write a program to convert P-sequence of a well-formed string to the W-sequence of the same string.
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
这道题的确英语有丝绕,看的纠结,但是大体意思就是有一串括号,序列P代表每一个右括号左面有多少个左括号,序列序列W代表每一个右括号左面第几个左括号是与之配对的左括号,然后给定P序列求W序列,这道题其实看到括号配对就要想到栈操作,先根据P序列还原原来的括号序列,主页君用了一个标记方法方便后面操作,还原后,正数代表左括号,负数代表右括号,数字代表其是第几个数,之后,就是栈操作,对每个数字判断,如果是正数,即左括号,则入栈,如果是负数,即右括号,此时将负数的变成相反的正数减去栈顶的数字除以2即为中间有多少对括号配对,也代表中间相隔多少个左括号,再+1就是右括号配对左括号是第几个左括号,将此序列再存入一个数组,待所有括号处理结束后,输出此数组即可AC。。。其实题目还是挺简单的。
下面是AC代码:
#include<cstdio> #include<iostream> #include<stack> using namespace std; int a[25],b[25],c[100]; int main() { int i,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]); } return 0; }