codeforces 508E Arthur and Brackets (stack)

E. Arthur and Brackets
time limit per test
2 seconds
memory limit per test
128 megabytes

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 length2n. 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 numbersli andri (1 ≤ li ≤ ri < 2n), representing the segment where lies the distance from thei-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).

Sample test(s)
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
(())()


题目大意:给出n组区间,每组区间为第i个括号的左右半边的下标值的相差范围,问存不存在这样的满足限制的括号序列,存在则输出,不存在输出IMPOSSIBLE

题目分析:本题可用dfs搜出来,但分析后存在更简单的方法,即选择栈来操作序列,理由是类似((())),(()()())这种类型的括号序列,我们可以很清楚的发现它们满足后进先出的特点,即遇到相匹配的则出栈,在对栈操作过程中我们总是选择栈顶的“(”来和“)”匹配,因为要满足题意我们可以根据所给区间的范围来选择合适的进出栈顺序,选择方式如下:

先将"("进栈,记录栈中"("的个数

1.当前字符串长+1大于等于当前栈内元素个数+当前区间左端点值,相等时就是遇到一组匹配的"()"

2.若1且当前字符串长+1小于等于当前栈内元素个数+当前区间右端点值,

3.若2则栈顶“(”出栈,若不满足2则直接输出IMPOSSIBLE退出,因为此时找不到与之匹配的")",相当于无解

条件2很好理解因为给了一个区间,设"("的下标为l,与之匹配的")"下标为r,则有l = stack.size(),r∈[l+l0,l+r0]

最后若栈内还有元素则表示存在找不到匹配的"(",则输出IMPOSSIBLE


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值