hdu 1361

地址:http://acm.hdu.edu.cn/showproblem.php?pid=1361

题意:对于一个合法的括号序列S,可以计算出P和W的值。P的第i个值表示第i个右括号前面有多少个左括号,W的第i个值表示第i个右括号会和前面第几个左括号匹配。现在给出P的值,求W的值。

mark:因为数据很小,n的长度只有20,因此可以直接模拟,由P反求出S,然后由S直接求出P。

代码:

# include <stdio.h>
# include <string.h>


char str[50] ;
int p[50],w[50] ;
int n ;


void setstr()
{
int num, i, j, cnt ;
for(i=0;i<n;i++)
{
scanf ("%d", &num) ;
cnt = 0 ;
for(j=0;cnt<num;j++)
{
if (str[j]==')') continue ;
cnt++ ;
}
while (str[j]==')')j++ ;
str[j] = ')' ;
}
for(i = 0 ; i < 2*n ; i++) if (str[i]!=')') str[i] = '(' ;
str[2*n] = '\0' ;
}


void setw()
{

int i, j=0, flag = 0 ;
for (i = 0 ; i < 2*n ; i++)
{
if (str[i]=='('){ j=i; continue ;}
if (flag == 0) flag = 1 ;
else putchar(' ') ;
printf ("%d", (i-j)/2+1) ;
str[j] = '*' ;
while (j>=0 && str[j] != '(') j-- ;
}
printf ("\n") ;
}

int main ()
{
int t ;
scanf ("%d", &t) ;
while (t--)
{
scanf ("%d", &n) ;
memset (str, 0, sizeof(str)) ;
setstr() ;
setw() ;
}
return 0 ;
}



原文地址:https://www.cnblogs.com/lzsz1212/p/2353516.html