POJ-1068 Parencodings---模拟括号的配对

题目链接:

https://vjudge.net/problem/POJ-1068

题目大意:

给出一种括号序列的表示形式名叫P序列,规则是统计出每个右括号之前的左括号个数作为序列每项的值。然后要求你根据这个求括号列的W序列值,W序列的规则是统计每一个右括号和与其匹配的左括号之间所有匹配后的括号个数。

思路:

先模拟出括号序列,然后根据每个右括号向前入栈,记录中间的括号数目

 #include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#define MEM(s, b) memset(a, b, sizeof(a));
using namespace std;
typedef long long ll;
int T, n, a[], b[], ans[];
int main()
{ cin >> T;
while(T--)
{
cin >> n;
string s;
MEM(a, );
MEM(b, );
MEM(ans, );
for(int i = ; i <= n; i++)cin >> a[i];
for(int i = ; i <= n; i++)
{
for(int j = ; j <= a[i] - a[i - ]; j++)s += '(';
s += ')';
}
// cout<<s<<endl;
int tot = ;
for(int i = ; i < s.size(); i++)
{
if(s[i] == ')')b[tot++] = i;
}
for(int i = ; i < tot; i++)
{
stack<char>q;
int cnt = ;
for(int j = b[i]; j >= ; j--)
{
if(s[j] == ')')q.push(s[j]);
else
{
q.pop();
cnt++;
if(q.empty())break;
}
}
ans[i] = cnt;
}
cout<<ans[];
for(int i = ; i < tot; i++)cout<<" "<<ans[i];
cout<<endl;
}
return ;
}
上一篇:Python-字符串开头或结尾匹配


下一篇:IOS绘制渐变背景色折线图的一种尝试