Codeforces 3D. Least Cost Bracket Sequence

来源:互联网 发布:淘宝哪家买家秀有福利 编辑:程序博客网 时间:2024/05/21 11:46

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()()

题意: 每一个问号表示可以用左括号‘(’或者右括号‘)’替代, 不同的地方、不同的替代方式花费不同, 求花费最少的替代方式能组成有效的括号序列

方法: 贪心的思想,用一个count记录括号匹配是否有效, 每次遇到 ‘(’count加1, 遇到‘)’减1, 每次遇到‘?’,都把‘?’替换为‘)’, 如果count小于1了, 说明到目前为止,‘)’的替换多了, 则从前面的替换中找出一个{替换‘)’花费  -  替换‘(’花费‘}最大的, 把它的’)‘改为’(‘,count += 2 

代码:

#include <stdio.h>#include <utility>#include <queue>using namespace std;const int MAXN = 50005;int main(){#ifdef _LOCAL    freopen("F://input.txt", "r", stdin);#endif  char str[MAXN];  scanf("%s", &str);  int count = 0;  long long totalCost = 0;  priority_queue<pair<int, int>> que;  for(int i = 0; str[i]; ++i)  {      if(str[i] == '(')          ++count;      else if(str[i] == ')')          --count;      else      {          int a, b;          scanf("%d%d", &a, &b);          str[i] = ')';// 选择右括号的原因是左边的括号不能增加          --count;          totalCost += b;          que.push(make_pair(b - a, i));      }      if(count < 0)      {          if(que.empty()) break;          count += 2;          totalCost -= que.top().first;          str[que.top().second] = '(';          que.pop();      }  }  if(count != 0)      printf("-1\n");  else      printf("%I64d\n%s", totalCost, str);  return 0;}




0 0
原创粉丝点击