Codeforces 3D Least Cost Bracket Sequence --- 贪心

来源:互联网 发布:知乎 恐惧 编辑:程序博客网 时间:2024/05/21 10:56
D. Least Cost Bracket Sequence
time limit per test
 1 second
memory limit per test
 64 megabytes
input
 standard input
output
 standard output

This is yet another problem on regular bracket sequences.

A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.

For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.

Input

The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.

Output

Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second.

Print -1, if there is no answer. If the answer is not unique, print any of them.

Sample test(s)
input
(??)1 22 8
output
4()()


这道题首先想到的是,先选择左右相差最大的?出来,决定它的结果。这个结果主要就是判断它能不能是最优的那个(也就是说它可能没得选,为了保证合法性)。但是这个判断过程是很慢的,只想到了O(n)的方法,加上?的数目(m吧),就是O(mn)。在第50组测试数据的时候就超时了。

上面的想法是优先考虑了最优性,然后保证合法性。另一种想法是优先考虑的合法性,先全部用)代替?,不合法时,再替换为(,这样在替换的时候由于可以使用堆(优先队列),是很快的,降到了O( nlog(m) ) ,这样就可以过了。

#include<cstdio>#include<iostream>#include<string>#include<vector>#include<cstdlib>#include<algorithm>#include<queue>using namespace std;class Cost{  public:    int l;    int r;    int id;    Cost(int id, int l, int r){ this->id = id; this->l=l; this->r=r; }    Cost(){ l=-1000; r=-1000; };    bool operator <(const Cost c) const{      return this->r - this->l < c.r-c.l;    }};string s;long long res_c=0;priority_queue<Cost> costs;int deal(){  int l,r,i;  int ln,rn;  Cost tmp;  res_c = 0;  for(i=0; i<s.size(); i++){    switch(s[i]){      case '(':        ln++;        break;      case ')':        ln--;        break;      case '?':        cin>>l>>r;        costs.push( Cost(i,l,r) );        s[i] = ')';        res_c += r;        ln--;        break;    }    if(ln<0){      if(costs.empty())        break;      else{        tmp = costs.top();        costs.pop();        s[tmp.id] = '(';        res_c = res_c + tmp.l - tmp.r;        ln += 2;      }    }  }  if(ln == 0){    cout<< res_c <<endl;    cout<< s << endl;  }else    cout<<"-1";  return 0;}int main(){  int n;#ifdef DEBUG  freopen("data","r",stdin);#endif  cin>>s;  deal();  return 0;}


0 0
原创粉丝点击