《ACM国际大学生程序设计竞赛题解I》——6.8
Posted 黑大帅之家
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《ACM国际大学生程序设计竞赛题解I》——6.8相关的知识,希望对你有一定的参考价值。
Poj1068:
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:
Following is an example of the above encodings:
S (((()()()))) P-sequence 4 5 6666 W-sequence 1 1 1456Write 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
题目大意:这里有三个数组S、P、W,S是长度为2n是符合数学规律的括号字符串,P、W是依据S生成的长度为n的整数列。
P:{p1,p2,p3…}第i个右括号左边的左括号数目,记为pi.
W:{w1,w2,w3…}第i个右括号与其匹配的左括号,截取的那个区间段左括号的数目。
现在给出P序列,求出对应的W序列。
数理分析:很容易想到,首先我们应该根据P得到S,然后根据S和W的定义得到W。因此整个模拟流程分为如下的两个步骤:
(一)P -> S:
遍历整数列P,其含义是第i个右括号左边有的左括号数目,我们先将n个右括号画出,则第i个右括号和第i-1个右括号中间隔了P[i] – P[i-1]个左括号,按照这个规律,我们遍历P[i],先生成P[i]-P[i-1]个左括号(P[0] = 0),然后生成一个右括号,便可构造出S。
(二)S –> W:
我们遍历S,设置数组left[i]记录第i个左括号在字符串数组S中的下标,则我们在遍历过程中一遇到右括号,就应该和left数组的尾部元素匹配,然后将left数组的尾部元素删除。(其实模拟了一个栈过程),此时我们知道尾部元素在S中的下标和右括号在S中的下标,不难得出这之间有多少个左括号。
简单的参考代码如下:
#include<cstdio> #include<cstring> using namespace std; const int maxn = 50; int main() { char s[maxn]; int p[maxn]; int w[maxn]; int t,index; scanf("%d",&t); while(t--) { int n; scanf("%d",&n); for(int i = 1;i <= n;i++) scanf("%d",&p[i]); index = 0; p[0] = 0; for(int i = 1;i <= n;i++) { int temp = p[i] - p[i-1]; while(temp--) { s[index++] = ‘(‘; } s[index++] = ‘)‘; } //得到s序列 n *= 2;//得到w序列 index = 1; int left[maxn]; bool left2[ maxn]; memset(left2 ,false , sizeof(left2)); for(int i = 0;i < n;i++) { if(s[i] == ‘(‘) left[index++] = i; else { if(i == n-1) {printf("%d\n" ,(i-left[--index]+1)/2);} else {printf("%d ",(i-left[--index]+1)/2);} } } } }
以上是关于《ACM国际大学生程序设计竞赛题解I》——6.8的主要内容,如果未能解决你的问题,请参考以下文章