【codeforces】3D

贪心+调整,先假设变为‘)’再用一个堆来调整,类似勇者斗恶龙

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
int i,n,m,t,mid;
long long ans;
int l[200000],r[200000],a[200000][2],b[200000],c[200000],w[200000],e;
char ch[200000];
int merge(int x,int y)
{
  if (!x) return y;
  if (!y) return x;
  if (w[x]>w[y]) e=x,x=y,y=e;
  r[x]=merge(r[x],y);
  e=l[x],l[x]=r[x],r[x]=e;
  return x;
}
int main()
{
  freopen("i.txt","r",stdin);
  freopen("o.txt","w",stdout);
  scanf("%s\n",ch+1);
  n=strlen(ch+1),m=0;
  for (i=1;i<=n;i++)
    if ('?'==ch[i]) c[++m]=i;
  for (i=1;i<=m;i++) scanf("%d%d\n",&a[c[i]][0],&a[c[i]][1]);
  mid=t=0;
  for (i=1;i<=n;i++) {
    if (ch[i]=='(') ++t,b[i]=0;
    else if (ch[i]=='?') {
      if (t) {
	w[i]=a[i][0]-a[i][1];
	b[i]=1,t--;
	mid=merge(mid,i);
      }
      else {
	if (mid && w[mid]+a[i][1]<a[i][0]) {
	  b[mid]=0;
	  mid=merge(l[mid],r[mid]);
	  b[i]=1,t=1;
	  w[i]=a[i][0]-a[i][1];
	  mid=merge(mid,i);
	}
	else b[i]=0,t=1;
      }
    }
    else {
      b[i]=1;
      if (t) t--;
      else {
	if (!mid) break;
	b[mid]=0;
	mid=merge(l[mid],r[mid]);
	t=1;
      }
    }
  }
  if (i<=n || t) {
    printf("-1\n");
    return 0;
  }
  ans=0;
  for (i=1;i<=n;i++) ans+=a[i][b[i]];
  printf("%I64d\n",ans);
  for (i=1;i<=n;i++) 
    if (!b[i]) printf("(");else printf(")");
  return 0;
}


你可能感兴趣的:(【codeforces】3D)