思路:
由p写出s,s里的括号进行配对,如果两个括号是配对的,那么括号里的括号应该都是配对的,既左括号数=右括号数
代码如下:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <vector>
using namespace std;
int find(char *temp,int xb)
{
int i;
int x;
int zuo, you;
int r;
r = 0;
for (i = xb-1; i >= 0; i--)
{
if (temp[i] == '(')
{
zuo = 0;
you = 0;
for (x = i + 1; x < xb; x++)
{
if (temp[x] == '(')
zuo++;
else
you++;
}
if (zuo == you)
{
r = i;
break;
}
}
}
return r;
}
int main()
{
int t;
int n;
int i;
int p[50];
int w[50];
int xb[50];
char s[50];
int max;
int x;
int z;
int r;
cin >> t;
while (t--)
{
memset(s, 0, sizeof(s));
cin >> n;
for (i = 0; i < n; i++)
{
cin >> p[i];
s[p[i] + i] = ')';
}
n *= 2;
x = 0;
for (i = 0; i <n; i++)
{
if (s[i] != ')')
{
s[i] = '(';
}
else
xb[x++] = i;
}
for (i = 0; i < x; i++)
{
r = 1;
z = find(s, xb[i]);
for (; z < xb[i]; z++)
{
if (s[z] == ')')
r++;
}
if (i)
printf(" %d", r);
else
printf("%d", r);
}
printf("\n");
}
system("pause");
return 0;
}