標籤:freopen out har def 預先處理 print algo seq style
首先容易想到二維方程dp(i,j),表示第i個左括弧去匹配到第j個右括弧時產生的最大值,但如果如此表示的話,首先需要枚舉(i,j)以及一個k即dp(i-1,k)。
考慮變化dp(i,j)的表示方法,可選擇將其表示為第i個左括弧至少匹配到第j個右括弧時所產生的最大值。如此表示的話,則轉移方程為
dp(i,j) = max(dp(i,j+1),dp(i+1,j) + a(i,j))此時不再需要枚舉k了,其中a(i,j)表示由第i個左括弧匹配到第j個右括弧時得到的值。另外注意左括弧不去匹配右括弧時的情況,
這個情況需要另行添加。
#include<cstdio>#include<cstdlib>#include<iostream>#include<string>#include<set>#include<algorithm>#include<vector>#include<queue>#include<list>#include<cmath>#include<cstring>#include<map>#include<stack>using namespace std;#define INF 0x3f3f3f3f#define maxn 200005#define ull unsigned long long#define ll long long#define hashmod 99999839#define mod 7#define repe(x,y,i) for(int i=(x);i<=(y);++i)#define repne(x,y,i) for(int i=(x);i<(y);++i)#define MAX(x,y) (x) < (y) ? (y) : (x);char s[1005];int p0[1005],p1[1005];ll v[1005];ll a[1005][1005];ll dp[1005][1005];//第i個0至少匹配到第j個1產生的最大值int main(){ // freopen("a.in","r",stdin); // freopen("b.out","w",stdout); int T,n; cin >> T; while(T--){ scanf("%d",&n); scanf("%s",s); int st = 0,en = n - 1,len0,len1; for(int i = 0;i < n;++i) scanf("%lld",&v[i]); for(;s[st] != ‘(‘;++st); for(;s[en] != ‘)‘;--en); len0 = len1 = 1;//存在不進行匹配的情況放到0 for(int i = st;i <= en;++i){ if(s[i] == ‘(‘) p0[len0++] = i; else p1[len1++] = i; } memset(a,0,sizeof(a)); for(int i = 1;i < len0;++i){//預先處理首碼和 int l = p0[i]; for(int j = 1;j < len1;++j){ if(l < p1[j]) a[i][j] = a[i][j-1] + v[l] * v[p1[j]]; } } memset(dp,0,sizeof(dp)); dp[len0-1][len1 - 1] = a[len0-1][len1-1]; ll ans = 0; for(int i = len1 - 2;i >= 0;--i) dp[len0 - 1][i] = max(a[len0-1][i],dp[len0-1][i+1]); for(int i = len0 - 2;i >= 0;--i){ dp[i][len1 - 1] = dp[i+1][len1 - 1] + a[i][len1 - 1]; for(int j = len1 - 2;j >= 0;--j){ dp[i][j] = max(dp[i][j+1],dp[i+1][j]+a[i][j]); if(i == 0) ans = max(dp[i][j],ans); } } printf("%lld\n",ans); } return 0;}
zoj4027 Sequence Swapping