Twin Towers DP.
#include <cstdio>#include<cstring>#include<queue>#include<string>#include<algorithm>#include<map>#include<iostream>using namespacestd;Const intmaxn= -+ -;intT,n;intdp[maxn][2*MAXN];intA[MAXN],B[MAXN];voidinit () { for(intI=1; i<=n;i++) for(intj=0; j<= $; j + +) Dp[i][j]=0x7fffffff;}voidRead () {scanf ("%d",&N); for(intI=1; i<=n;i++) scanf ("%d%d",&a[i],&b[i]);}voidWork () {dp[1][a[1]+ -]=dp[1][0-b[1]+ -]=0; for(intI=2; i<=n;i++) { for(intj=0; j<= $; j + +) { if(dp[i-1][j]==0x7fffffff)Continue; inttmp=j- -; if(tmp>=0) {Dp[i][a[i]+ -]=min (dp[i][a[i]+ -],dp[i-1][j]+tmp); if(b[i]>=tmp) dp[i][tmp-b[i]+ -]=min (dp[i][tmp-b[i]+ -],dp[i-1][j]+tmp); Else if(b[i]<tmp) dp[i][tmp-b[i]+ -]=min (dp[i][tmp-b[i]+ -],dp[i-1][j]+B[i]); } Else if(tmp<0) {tmp=-tmp; if(dp[i-1][j]+tmp<dp[i][0-b[i]+ -]) dp[i][0-b[i]+ -]=min (dp[i][0-b[i]+ -],dp[i-1][j]+tmp); if(a[i]<=tmp) dp[i][a[i]-tmp+ -]=min (dp[i][a[i]-tmp+ -],dp[i-1][j]+A[i]); Else if(a[i]>tmp) dp[i][a[i]-tmp+ -]=min (dp[i][a[i]-tmp+ -],dp[i-1][j]+tmp); } } } intans=0x7fffffff; for(intj=0; j<= $; j + +) { if(dp[n][j]==0x7fffffff)Continue; Ans=min (Ans,dp[n][j]+abs (J- -)); } printf ("%d\n", ans);}intMain () {scanf ("%d",&T); while(t--) {read (); Init (); Work (); } return 0;}
ZOJ 3331 Process the Tasks