洛谷地址:https://www.luogu.com.cn/problem/CF508E
题意:
给出n对L,R
第i个左括号,与它匹配的右括号与左括号的距离范围为:[L,R]
求是否有序列满足,否则:IMPOSSIBLE
解析:
看了不少题解,勉强搞懂。
对于括号匹配问题,应该优先想到栈。因为括号的匹配符合先进后出,所以用stack来进行模拟。
栈顶的括号进行优先匹配,
如果它的左括号位置+L>cnt,位置留下,供下一个左括号使用。
左括号位置+R<cnt,已经没有多余位置匹配右括号了,这个时候一定不满足条件。
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
typedef long long ll;
const int maxn=605;
int l[maxn],r[maxn];
char ch[3*maxn];
int pos[maxn];
int main()
{
int n;
scanf("%d",&n);
memset(pos,0,sizeof(pos));
stack<int>s;
int cnt=0,ok=0;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&l[i],&r[i]);
pos[i]=cnt;
ch[cnt++]='(';
s.push(i);
while(!s.empty())
{
int u=s.top();
if(l[u]+pos[u]>cnt) break;
if(r[u]+pos[u]<cnt)
{
ok=1;break;
}
ch[cnt++]=')';
s.pop();
}
}
if(!ok&&s.empty())
printf("%s\n",ch);
else
printf("IMPOSSIBLE\n");
}