每一个栈顶的左括号优先匹配最近的右括号 范围判断一下就行了
#include<bits/stdc++.h>
using namespace std;
const int N=605;
int l[N],r[N],n,pos[N];
char ans[N<<1];
int main(){
stack<int> q;
int cnt=0;
scanf("%d",&n);
int fl=0;
for(int i=1;i<=n;i++){
scanf("%d%d",&l[i],&r[i]);
pos[i]=cnt;
ans[++cnt]='(';
q.push(i);
while(q.size()){
int tp=q.top();
// cout<<tp<<endl;
if(pos[tp]+r[tp]<cnt){
fl=1;return cout<<"IMPOSSIBLE"<<endl,0;
}
if(pos[tp]+l[tp]>cnt) break;
q.pop();
ans[++cnt]=')';
}
}
if(q.size()) return cout<<"IMPOSSIBLE"<<endl,0;
for(int i=1;i<=2*n;i++) cout<<ans[i];
cout<<endl;
}