Arthur and Brackets
time limit per test
2 seconds
memory limit per test
128 megabytes
input
standard input
output
standard output
Notice that the memory limit is non-standard.
Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length 2n. Unlike Arthur, Sasha understood the topic very badly, and broke Arthur’s favorite correct bracket sequence just to spite him.
All Arthur remembers about his favorite sequence is for each opening parenthesis (‘(‘) the approximate distance to the corresponding closing one (‘)’). For the i-th opening bracket he remembers the segment [li, ri], containing the distance to the corresponding closing bracket.
Formally speaking, for the i-th opening bracket (in order from left to right) we know that the difference of its position and the position of the corresponding closing bracket belongs to the segment [li, ri].
Help Arthur restore his favorite correct bracket sequence!
Input
The first line contains integer n (1 ≤ n ≤ 600), the number of opening brackets in Arthur’s favorite correct bracket sequence.
Next n lines contain numbers li and ri (1 ≤ li ≤ ri < 2n), representing the segment where lies the distance from the i-th opening bracket and the corresponding closing one.
The descriptions of the segments are given in the order in which the opening brackets occur in Arthur’s favorite sequence if we list them from left to right.
Output
If it is possible to restore the correct bracket sequence by the given data, print any possible choice.
If Arthur got something wrong, and there are no sequences corresponding to the given information, print a single line “IMPOSSIBLE” (without the quotes).
Examples
Input
4
1 1
1 1
1 1
1 1
Output
()()()()
Input
3
5 5
3 3
1 1
Output
((()))
Input
3
5 5
3 3
2 2
Output
IMPOSSIBLE
Input
3
2 3
1 4
1 4
Output
(())()
每次用stl的题都看不出来,还是功力太浅
这种更后面出现结果的先满足后面出现的条件都用栈的吧
解析:cnt表示坐标,我们每次枚举到新的i时让当前坐标为‘(’,然后让i入栈,看是否满足条件就好了,具体看代码
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define inf 0x3f3f3f3f
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int N=610;
int arr[N];
int mi[N],mx[N];
int p[N];
int main()
{
int n;
cin>>n;
rep(i,0,n)
cin>>mi[i]>>mx[i];
string ans;
int cnt=0,flag=1;
stack<int>st;
for(int i=0;i<n&&flag;i++)
{
st.push(i);
p[i]=cnt;//记录当前i'('的下标
ans+='(';
cnt++;
while(!st.empty()&&flag&&cnt-p[st.top()]>=mi[st.top()])
{
if(cnt-p[st.top()]<=mx[st.top()])//不满足最大值的话,以后会越来越大,直接退出就好了
ans+=')',cnt++;
else
flag=0;
st.pop();
}
}
if(cnt!=2*n||!flag)//第一个条件也就是栈里还有东西
cout<<"IMPOSSIBLE";
else
//rep(i,0,cnt)
cout<<ans;
cout<<endl;
return 0;
}