【codeforces 508E】Artur and Brackets

【题目链接】:http://codeforces.com/problemset/problem/508/E

【题意】

让你构造一个括号字符串;
使得每个从左往右数第i个左括号在这个括号序列中与之匹配的右括号的位置与这个左括号的位置的差的在[li..ri]这个区间内;

【题解】

遇到左括号就加入栈内;
然后每次都尝试给栈顶的元素匹配;
能匹配就直接匹配;
不然可能到了后面就不能匹配了(太右);
就按照这个贪心策略搞就能过.

【Number Of WA

0

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)
#define Open() freopen("W:\\rush.txt","r",stdin)
#define Close() ios::sync_with_stdio(0),cin.tie(0)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 2000;
const int K = 110;

int n,l[N],r[N],cnt,pos[N];
char s[N];
stack <int> sta;

void wujie()
{
    cout <<"IMPOSSIBLE"<<endl;
    exit(0);
}

int main()
{
    //Open();
    Close();//scanf,puts,printf not use
    //init??????
    cin >> n;
    rep1(i,1,n)
        cin >> l[i] >> r[i];
    rep1(i,1,n)
    {
        sta.push(i);
        s[++cnt] = '(';
        pos[i] = cnt;
        while (sta.size())
        {
            int x = sta.top();
            int idx = pos[x];
            if (idx+l[x]>cnt+1) break;
            if (idx+r[x]<cnt+1) wujie();
            sta.pop();
            s[++cnt] = ')';
        }
    }
    if (!sta.empty()) wujie();
    for (int i = 1;i <= 2*n;i++)
        cout << s[i];
    return 0;
}

posted @ 2017-10-04 18:44  AWCXV  阅读(93)  评论(0编辑  收藏  举报