cf3d
题目链接:http://www.codeforces.com/problemset/problem/3/D
思路:贪心+调整,?就改成')',如果加了')'后发现右括号比左括号多, 就将花费小的括号变成'(',(采用优先队列,默认排序是从大到小);
View Code
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<cstring> 5 using namespace std; 6 typedef long long ll; 7 #define MAXN 50005 8 9 10 int main(){ 11 char str[MAXN]; 12 while(~scanf("%s",str)){ 13 priority_queue<pair<int,int> >Q; 14 int len=strlen(str),x,y; 15 ll ans=0,count=0; 16 bool flag=true; 17 for(int i=0;i<len;i++){ 18 if(str[i]=='(')count++; 19 else if(str[i]==')')count--; 20 else { 21 scanf("%d%d",&x,&y); 22 str[i]=')'; 23 count--; 24 Q.push(make_pair(y-x,i)); 25 ans+=y; 26 } 27 pair<int,int>p; 28 if(count<0){ 29 if(Q.empty()){flag=false;continue;} 30 p=Q.top();Q.pop();//出对列的是最大元素,保证花费最小; 31 ans-=p.first; 32 str[p.second]='('; 33 count+=2; 34 } 35 } 36 (count==0&&flag)?printf("%I64d\n%s\n",ans,str):puts("-1"); 37 } 38 return 0; 39 }