CF 508E-Arthur and Brackets(思维+stack堆栈)

题意:http://codeforces.com/problemset/problem/508/E

就是告诉你每对括号的左右距离范围,让你构造这个括号。

思路:

看了题解才知道。

首先看到括号你得想到stack堆栈,想到的话很快就出结论了。

 1 struct node
 2 {
 3     int l,r;
 4 }a[N];
 5 bool in[N];
 6 stack<int>s;
 7 char ans[N];
 8 int cnt=0;
 9 
10 int main()
11 {
12     int n;
13     sc("%d",&n);
14     for(int i=1;i<=n;++i)sc("%d%d",&a[i].l,&a[i].r);
15     for(int i=1;i<=n;++i)
16     {
17         while(!s.empty())
18         {
19             int now=s.top();
20             if(a[now].r<0){pr("IMPOSSIBLE
");return 0;}
21             if(a[now].l<=0)
22             {
23                 ans[++cnt]=')';
24                 in[now]=0;
25                 s.pop();
26                 for(int j=1;j<=n;++j)
27                     if(in[j])a[j].l--,a[j].r--;
28             }
29             else
30                 break;
31         }
32         ans[++cnt]='(';
33         s.push(i);
34         in[i]=1;
35         for(int j=1;j<=n;++j)
36             if(in[j])a[j].l--,a[j].r--;
37     }
38     while(!s.empty())
39     {
40         int now=s.top();
41         if(a[now].r<0){pr("IMPOSSIBLE
");return 0;}
42         if(a[now].l<=0)
43         {
44             ans[++cnt]=')';
45             in[now]=0;
46             s.pop();
47             for(int j=1;j<=n;++j)
48                 if(in[j])a[j].l--,a[j].r--;
49         }
50         else
51             break;
52     }
53     if(!s.empty()){pr("IMPOSSIBLE
");return 0;}
54     else
55     {
56         for(int i=1;i<=cnt;++i)
57             pr("%c",ans[i]);
58     }
59     return 0;
60 }

为当前括号不会影响到下一个括号,所以赶紧结束肯定是最优的。

所以就模拟了。

原文地址:https://www.cnblogs.com/--HPY-7m/p/12656015.html