Codeforces 3D Least Cost Bracket Sequence(贪心)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Miracle_ma/article/details/52807640

?
?()
dp(n2

?)
(+1,)1
0
)0
0?(
0


代码:

#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#pragma comment(linker,"/STACK:102400000,102400000")

using namespace std;
#define   MAX           50005
#define   MAXN          1000005
#define   maxnode       105
#define   sigma_size    30
#define   lson          l,m,rt<<1
#define   rson          m+1,r,rt<<1|1
#define   lrt           rt<<1
#define   rrt           rt<<1|1
#define   middle        int m=(r+l)>>1
#define   LL            long long
#define   ull           unsigned long long
#define   mem(x,v)      memset(x,v,sizeof(x))
#define   lowbit(x)     (x&-x)
#define   pii           pair<int,int>
#define   bits(a)       __builtin_popcount(a)
#define   mk            make_pair
#define   limit         10000

//const int    prime = 999983;
const int    INF   = 0x3f3f3f3f;
const LL     INFF  = 0x3f3f;
const double pi    = acos(-1.0);
const double inf   = 1e18;
const double eps   = 1e-8;
const LL     mod   = 1e9+7;
const ull    mx    = 133333331;

/*****************************************************/
inline void RI(int &x) {
      char c;
      while((c=getchar())<'0' || c>'9');
      x=c-'0';
      while((c=getchar())>='0' && c<='9') x=(x<<3)+(x<<1)+c-'0';
 }
/*****************************************************/

char s[MAX];

int main(){
    //freopen("in.txt","r",stdin);
    while(~scanf("%s",s)){
        int len=strlen(s);
        priority_queue<pii> q;
        int cnt=0;
        LL ans=0;
        int flag=0;
        for(int i=0;i<len;i++){
            if(s[i]=='(') cnt--;
            else if(s[i]==')') cnt++;
            else{
                cnt++;
                int a,b;
                scanf("%d%d",&a,&b);
                ans+=b;
                q.push(mk(b-a,-i));
                s[i]=')';
            }
            if(cnt>0){
                if(!q.empty()){
                    pii p=q.top();
                    q.pop();
                    ans-=p.first;
                    s[-p.second]='(';
                    cnt-=2;
                }
                else flag=1;
            }
        }
        if(flag||cnt) printf("-1\n");
        else{
            cout<<ans<<endl;
            printf("%s\n",s);
        }
    }
    return 0;
}
阅读更多

没有更多推荐了,返回首页