CodeForces Round #288 Div.2. E-Arthur and Brackets——dp/greedy

CodeForces Round #288 Div.2


有一些配好对的括号,现在已知第i对括号,左右括号的距离在[Li, Ri]区间中。按照左括号出现的顺序编号。输出原括号序列。


greedy:只有前一个括号匹配完,后一个括号才能匹配。所以前一个括号今早的匹配,后一个括号才有更多的机会匹配


如果当前左括号在p位置,则右括号所在的区间为[L[i]+p,R[i]+p],用一个栈存储每个右括号的区间,用一个迭代器一直往后走,如果当前位置在栈顶区间内,则在当前位置放置右括号,出栈


#include<bits/stdc++.h>
const int maxn=601;
using namespace std;
int main(){
    int n;
    int L[maxn],R[maxn];
    cin>>n;
    for(int i=0;i<n;++i){
        scanf("%d%d",&L[i],&R[i]);
    }
    stack<pair<int,int> > s;
    char str[maxn];
    int p=0;
    for(int i=0;i<n;++i){
        s.push(make_pair(L[i]+p,R[i]+p));
        str[p++]='(';
        while(!s.empty()&&s.top().first<=p&&s.top().second>=p){
            str[p++]=')';
            s.pop();
        }
        if(!s.empty()&&p>s.top().second){puts("IMPOSSIBLE");return 0;}
    }
    if(!s.empty()){puts("IMPOSSIBLE");return 0;}
    str[p]='\0';
    puts(str);
    return 0;
}


你可能感兴趣的:(CodeForces Round #288 Div.2. E-Arthur and Brackets——dp/greedy)