POJ1068 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).
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
 
分析:
对于给出的序列,明显是一定不会下降的,
用ans[]来记录答案
当A[i]>A[j]时其对应的ans[i]=1;
注意到A[i]-ans[i]其实就是当前右括号对应的左括号的前面有多少个左括号
很明显对每个A[i]-ans[i]都是唯一的,用它来作为匹配过的左括号的编号,这个编号从0开始
所以当A[i]==A[i-1]时 令k=ans[i-1]+1;
不断增加k直到A[i]-k的值没有在前面出现过时,ans[i]=k;
 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 int f[100], g[100], ans[100];
 5 int t, n, k, sum;
 6 int main() {
 7     cin >> t;
 8     while (t--) {
 9         cin >> n;
10         memset (g, 0, sizeof g);//数组g用来记录使用过的左括号
11         for (int i = 1; i <= n; i++) {
12             cin >> f[i];
13             if (f[i] > f[i - 1]) {//比前面的数大
14                 ans[i] = 1;//ans[i]赋值为一
15                 g[f[i] - ans[i]] = 1;//标记使用过的左括号
16             }
17             else {
18                 int k = ans[i - 1] + 1;
19                 while (g[f[i] - k]) k++;//找到没有使用过的左括号
20                 g[f[i] - k] = 1;
21                 ans[i] = k;
22             }
23         }
24         cout << ans[1];
25         for (int i = 2; i <= n; i++)
26             cout << ' ' << ans[i];
27         cout << endl;
28     }
29     return 0;
30 }
View Code

 

 
http://www.cnblogs.com/keam37/ keam所有 转载请注明出处
posted @ 2014-05-24 00:45  keambar  阅读(161)  评论(0)    收藏  举报