codeforces 508E E. Arthur and Brackets(栈模拟+贪心+构造)

来源:互联网 发布:mac qq怎么发文件夹 编辑:程序博客网 时间:2024/05/22 05:14

题目链接:

codeforces 508E


题目大意:

给出一些括号,这个括号左括号的先后顺序确定,左右括号的距离的范围确定,构造一种合法的方案。


题目分析:

  • 首先对于括号的问题很容易想到栈,那么我们对于每个左括号采取的决策是栈顶的左括号能够匹配就立即匹配,因为如果栈顶的括号不匹配,其他的括号没办法匹配,栈顶括号匹配的越晚,已经构造的序列就越长,那么越有可能超过下面的左括号的右边界,所以能够匹配栈顶左括号就立即匹配的方案是保证有解的最优的方案。 
#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>#include <stack>#define MAX 607using namespace std;int l[MAX],r[MAX],n,pos[MAX];char ans[MAX<<1];stack<int> s;int main ( ){    while ( ~scanf ( "%d" , &n ))    {        while ( !s.empty()) s.pop();        int cnt = 0,i;        bool flag = true;        for ( i = 0 ; i < n ; i++ )        {            scanf ( "%d%d" , &l[i] , &r[i] );            s.push ( i );            pos[i] = cnt;            ans[cnt++] = '(';            while ( !s.empty() )            {                int x = s.top();                if ( pos[x]+l[x] > cnt ) break;                if ( pos[x]+r[x] < cnt )                {                    flag = false;                    break;                }                ans[cnt++] = ')';                s.pop();            }        }        ans[cnt] = 0;        if ( flag && s.empty()) printf ( "%s\n" , ans );        else puts ( "IMPOSSIBLE");    }}


阅读全文
0 0
原创粉丝点击