原題:
Parencodings
Time Limit: 1 Second Memory Limit: 32768 KB
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
Source:
Asia 2001, Tehran (Iran)
雖然是一道簡單題,但是由於是英文的,我做的時候理解起來還是花了那麼一段時間,現在分析一下,主要是理解一下題目,讓我自己以後看的時候不要摸不到頭腦就可以了。
題意是這樣的,現在有一系列的(),要對這些左右圓括弧進行編碼。現在有兩種編碼形式,第一種:從給定的S(左右圓括弧串)中,從左往右說,找到一個右括弧,記錄在這個右括弧之前出現的左括弧的數量,即P編碼。第二種,還是從給定串的左邊開始往右數,找到右括弧,然後從這個位置往左數,記錄與之匹配的第一個左括弧是出現的第幾個左括弧,即W編碼。例如:
S (((()()())))
P-sequence 4 5 6666
W-sequence 1 1 1456
然後,題目給出了已知S串的P編碼形式,求其W編碼串。雖然根據P編碼形式可以反向求得原S串,但是這卻不是最佳解法。其實我們是可以根據P串直接求W串的。
好啦,題意理解清楚了,就可以給出解題代碼了。
1: #include<iostream>
2: #include<vector>
3: using namespace std;
4:
5: int main(void)
6: { 7: int times;
8: while(cin>>times)
9: { 10: for(int items;times && cin>>items;times--)
11: { 12: vector<int> leftParenthsis(items,0);
13: int preNumber = 0;
14: for(int numbers,i = 0;i < items && cin>>numbers; i++)
15: { 16: leftParenthsis[i] = numbers - preNumber;
17: preNumber = numbers;
18: cout<<(i ? " ":"");
19: if(leftParenthsis[i])
20: { 21: cout<<1;
22: leftParenthsis[i]--;
23: }
24: else
25: { 26: for(int j = i; j >= 0;j--)
27: { 28: if(leftParenthsis[j])
29: { 30: cout<<i - j + 1;
31: leftParenthsis[j]--;
32: break;
33: }
34: }
35: }
36: }
37: cout<<endl;
38: }
39: }
40: return 0;
41: }