题意就是给一个只包含有"(" ")" "?"的字符串,对于第i个?,我们可以把他变成"(" 或者")" ,代价分别是a[i] , b[i],问说把所有的问号替换以后,使得这个字符串是一个合法的括号匹配的最小代价是多少,如果无解输出-1
这道题一到手马上想到一O(n²)的dp,因为n是5e4,而且cf上的机子跑的很快(薅资本主义的羊毛),加一点优化好像还可以。
把"("替换成1,把")"替换成-1,dp[i][j] 代表前i个字符串的前缀和为j的时候的最小代价,dp[i][j] = min(dp[i -1 ][j - 1 ]+ a[i] ,dp[ i - 1][ j +1 ] + b[i ]) ;用滚动数组代替二维数组即可,跑了几组数据发现可以求最小代价,然而题目还要求输出路径,请教了很多dalao之后发现dp滚动数组好像不容易打印路径!!所以这个dp并没有什么卵用。
然后看q神的题解,先把所有的问号换成右括号,然后从左到右,同样记左括号为1,右括号为-1,那么如果到某一个位置中,前缀和sum<0,那么在这个前缀中必须有一个右括号替换成左括号,我们把那个(a[i] - b[i ])最小的拿出来替换,这里可以用堆优化降到O(n log n)。这样就可以了,注意最后前缀和sum必须=0 ,否则是无解的。
#pragma GCC optimize ("03")
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<set>
#include<map>
#include<time.h>
#include<cstdio>
#include<vector>
#include<stack>
#include<queue>
#include<iostream>
using namespace std;
#define LONG long long
const int INF=0x3f3f3f3f;
const int MOD=1e9+7;
const double PI=acos(-1.0);
#define clrI(x) memset(x,-1,sizeof(x))
#define clr0(x) memset(x,0,sizeof x)
#define clr1(x) memset(x,INF,sizeof x)
#define clr2(x) memset(x,-INF,sizeof x)
#define EPS 1e-10
char str[60000];
struct Node
{
LONG a, b ;
LONG cost ;
int p ;
bool operator < (const Node &x) const
{
if(cost == x.cost )return p<x.p ;
else return cost > x.cost ;
}
}node[60000];
int main()
{
scanf("%s",str);
int len = strlen(str);
int m = 0;
LONG ans = 0 ;
for(int i = 0 ; i < len ;++i)
{
if(str[i] == '?')
{
++ m ;
scanf("%lld%lld",&node[i].a,&node[i].b);
ans += node[i].b ;
}
node[i].cost = node[i].a - node[i].b ;
node[i].p = i;
}
priority_queue <Node > que ;
while(!que.empty()) que.pop();
int sum = 0 ;
int judge = 1 ;
for(int i = 0 ; i< len ;++ i)
{
if(str[i] == '?' )
{
que.push(node[i]) ;
str[i] = ')';
sum ++ ;
}
else if(str[i] == '(')
sum --;
else if(str[i] == ')')
sum ++ ;
if( sum > 0)
{
if(que.empty())
{
judge = 0 ;
break ;
}
Node tmp = que.top() ;
que.pop() ;
str[tmp.p] = '(';
ans += tmp.cost ;
sum -= 2 ;
}
// printf("%s\n",str);
}
if(!judge || sum != 0 )
{
cout<<-1<<endl;
return 0;
}
cout<<ans<<endl;
printf("%s\n",str);
}