I - Parencodings
题目描述:
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.
题目大意:
这道题讲的是给出一串括号,然后有2种编码方式,分别为W与P,假设括号为(((()()()))),如果按照P编码来输出,就从第一个右括号他的左边有多少个括号就输出,接着按照第二个右括号的左边有多少个括号输出,则有4 5 6666。如果按照W编码来输出,就从 第一个右括号与他最近的左括号结合,输出2者的距离,但不能重复结合,一旦这个左括号与右括号结合,后面的右括号就不能与其在结合,就有 1 1 1 4 5 6.。
题目要求给出P编码的输出,然后叫你转换为W编码输出。
思路分析:
可以先将P编码打出括号字符串,然后在转换为W,则就相当于先进栈后出栈,并给特定的右括号做标记,就可以了。
代码块:
#include<stdio.h>
int lemon()
{
char str[2000];//记录字符串
int L[2000]={0};//判断左括号是否被标记了
int L1[2000];//记录W编码方式的结果。
int b,c,num=0,d,e,h=0;
scanf("%d",&b);
for(c=0;c<b;c++)//将P编码方式转为字符串
{
scanf("%d",&d);
for(e=0;e<d-num;e++)
{
str[h++]='(';
}
num=d;
str[h++]=')';
}
num=0;
for(c=0;c<h;c++)//由字符串转化为W编码方式
{
int num1=1;//左右括号之间的距离
if(str[c]==')')
{
for(e=c-1;e>=0;e--)
{
if(str[e]=='(' && L[e]==0)//当左括号被人结合后,L[e]就会被标记相当于
{ //相当于给左括号下标做标记。
L[e]=1;
L1[num++]=num1;//如果结合成功就将其2括号之间的距离记录下来。
break;
}
else if(L[e]==1 && str[e]=='(')
{
num1++;//计算右括号与左括号之间的距离
}
}
}
}
for(c=0;c<num;c++)//输出W编码方式
{
if(c!=num-1)
printf("%d ",L1[c]);
else
printf("%d\n",L1[c]);
}
}
int main()
{
int b,c,d;
scanf("%d",&b);
for(c=0;c<b;c++)
{
lemon();
}
}