贪心题是很有趣的...

首先,本题为括号匹配问题,那么可以考虑进行栈模拟

然后,我们思考一下如何匹配:虽然题目中仅对右括号的位置提出了区域性要求,但可以发现,对能匹配上的栈顶括号立刻进行匹配一定是一种最优解!

为什么?

根据括号匹配原则,如果栈顶括号未被匹配,那么其他括号将无法被匹配,那么栈顶括号越长时间不被匹配,栈内括号失配的可能就越大。相反,如果我们对能匹配的栈顶括号立刻进行匹配,不会存在反例使得本能匹配上的其他括号未能被匹配。

所以这题的剩余部分就变成了一个模拟...

#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
int l[605],r[605];
int n;
int my_stack[605];
int posi[605];
int ttop=0;
int typ[1205];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d%d",&l[i],&r[i]);
}
int pos=2;
int cnt=1;
typ[1]=1;
my_stack[++ttop]=1;
posi[ttop]=1;
while(pos<=2*n)
{
int t=my_stack[ttop];
int p=posi[ttop];
if(p+l[t]<=pos&&p+r[t]>=pos)
{
typ[pos]=2;
ttop--;
pos++;
}else
{
my_stack[++ttop]=++cnt;
posi[ttop]=pos;
typ[pos]=1;
pos++;
}
}
if(ttop)
{
printf("IMPOSSIBLE\n");
return 0;
}else
{
for(int i=1;i<=2*n;i++)
{
if(typ[i]==1)
{
printf("(");
}else
{
printf(")");
}
}
printf("\n");
}
return 0;
}
04-26 23:46