模拟 | POJ1068.Parencodings
Link:Parencodings
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).
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
Source
Tehran 2001
题意
有一个合法的由括号组成的字符串S
P序列p1 p2 p3…pn表 示S中第i个右括号的左边 左括号的数量
W序列w1 w2 w3 … wn,对于S中第i个右括号,从与之相匹配的左括号起,到当前右括号所包含的右括号的数量(包括当前右括号),要求根据给出的P序列求出W序列。
思路
依据P序列还原字符串。用-1表示左括号,1表示右括号。得到S相应的原始序列。
根据此原始序列,对于每一个右括号,找到与之相匹配的左括号,并将这对括号都置为0(将-1和1置为0)。所以回溯的过程只会遇到0和-1并且遇到-1终止回溯,遇到0计数自增。这个右括号的W值为计数值的一半。
由于右括号自己也计入W值,所以计数值初始值为2
POJ在输出一组数字时,并不会要求最后一个数字之后无空格并且在输出每组数据之后,应该自己增加换行,否则,会出现Presentation Error
代码
#include <iostream>
#include <cstring>
using namespace std;
int cursor;
int S[41];
void toS( int n )
{
while( n-- )
S[cursor++] = -1;
S[cursor++] = 1;
}
int main()
{
int cases;
int n;
cin >> cases;
while( cases-- )
{
//初始化
memset( S, 0, 41 );
cursor = 0;
cin >> n;
int now, last = 0;
//输入P序列并且生成原始S序列
for( int i = 0; i < n; i++ )
{
cin >> now;
toS( now - last );
last = now;
}
cursor = 0;
int count0 = 0;
bool first = true;
for( int i = 0, j; i < 2*n; i++ )
{
//遇到右括号开始回溯
if( S[i] == 1 )
{
j = i;
count0 =2;
while( j-- )
{
//回溯遇到相匹配的左括号
if( S[j] == -1 )
{
S[j] = 0;
S[i] = 0;
break;
}
else
count0++;
}
cout << count0/2 << " ";
}
}
cout << endl;
}
return 0;
}