https://www.luogu.org/problemnew/show/P188
从前往后的做法:
1 #include<iostream> 2 #include<cstdio> 3 #include <cctype> 4 #include<algorithm> 5 #include<cstring> 6 #include<cmath> 7 #include<string> 8 #include<cmath> 9 #include<set> 10 #include<vector> 11 #include<stack> 12 #include<queue> 13 #include<map> 14 using namespace std; 15 #define ll long long 16 #define mem(a,x) memset(a,x,sizeof(a)) 17 #define se second 18 #define fi first 19 const int INF= 0x3f3f3f3f; 20 const int N=1e4+5; 21 22 int n,a[505],sum[505],f1[505][505],f2[505][505]; 23 24 int main() 25 { 26 cin>>n; 27 for(int i=1;i<=n;i++){ 28 cin>>a[i]; 29 a[i+n]=a[i]; 30 } 31 sum[0]=0; 32 for(int i=1;i<=(n<<1);i++) sum[i]=sum[i-1]+a[i]; 33 34 mem(f2,0); 35 mem(f1,0); 36 for(int i=2;i<=(n<<1);i++) 37 { 38 for(int j=i-1;j>0;j--) 39 { 40 f1[i][j]=INF; 41 for(int k=i-1;k>=j;k--) 42 { 43 f1[i][j]=min(f1[i][j], f1[i][k+1]+f1[k][j]+sum[i]-sum[j-1] ); 44 f2[i][j]=max(f2[i][j], f2[i][k+1]+f2[k][j]+sum[i]-sum[j-1] ); 45 //cout<<f1[i][j]<<' '<<f2[i][j]<<endl; 46 } 47 } 48 } 49 int ans1=INF,ans2=0; 50 for(int i=1;i<=n;i++) 51 { 52 ans1=min(ans1,f1[i+n-1][i] ); 53 ans2=max(ans2,f2[i+n-1][i] ); 54 } 55 printf("%d %d",ans1,ans2); 56 }
从后往前的做法:
1 for(register int i=(n<<1)-1;i>0;--i) 2 { 3 for(register int j=i+1;j<i+n;++j) 4 { 5 dp1[i][j]=inf; 6 for(register int k=i;k<j;++k) 7 { 8 dp1[i][j]=min(dp1[i][j],dp1[i][k]+dp1[k+1][j]+sum[j]-sum[i-1]); 9 dp2[i][j]=max(dp2[i][j],dp2[i][k]+dp2[k+1][j]+sum[j]-sum[i-1]); 10 } 11 } 12 } 13 for(register int i=1;i<=n;++i) 14 { 15 min_ans=min(min_ans,dp1[i][i+n-1]); 16 max_ans=max(max_ans,dp2[i][i+n-1]); 17 } 18 printf("%d %d ",min_ans,max_ans); 19 return 0;