You Are the One
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 5204 Accepted Submission(s): 2499
Problem Description
The TV shows such as You Are the One has been very popular. In order to meet the need of boys who are still single, TJUT hold the show itself. The show is hold in the Small hall, so it attract a lot of boys and girls. Now there are n boys enrolling in. At the beginning, the n boys stand in a row and go to the stage one by one. However, the director suddenly knows that very boy has a value of diaosi D, if the boy is k-th one go to the stage, the unhappiness of him will be (k-1)*D, because he has to wait for (k-1) people. Luckily, there is a dark room in the Small hall, so the director can put the boy into the dark room temporarily and let the boys behind his go to stage before him. For the dark room is very narrow, the boy who first get into dark room has to leave last. The director wants to change the order of boys by the dark room, so the summary of unhappiness will be least. Can you help him?
Input
The first line contains a single integer T, the number of test cases. For each case, the first line is n (0 < n <= 100)
The next n line are n integer D1-Dn means the value of diaosi of boys (0 <= Di <= 100)
The next n line are n integer D1-Dn means the value of diaosi of boys (0 <= Di <= 100)
Output
For each test case, output the least summary of unhappiness .
Sample Input
2 512345554322
Sample Output
Case #1: 20Case #2: 24
题解:考虑区间[l,r],枚举该区间最后一个出场的值k,由栈操作的性质知,区间[l,k-1]的所有值一定先出场,接着是区间[k+1,r],K最后出场。
#include<bits/stdc++.h> using namespace std; #define ll long long #define rep(i,a,n) for(int i=(a);i<(n);++i) #define per(i,a,n) for(int i=(n-1);i>=(a);--i) #define INF 1e9 const int mod=1e9+7; #define N 1010 int a[N]; int dp[N][N]; int s[N]; int main(){ ios::sync_with_stdio(0); int n,T,cas=1; scanf("%d",&T); while(cas<=T){ scanf("%d",&n); s[0]=0; for(int i=0;i<n;++i){ scanf("%d",&a[i]); s[i+1]=s[i]+a[i]; } for(int i=0;i<n;++i) for(int j=0;j<n;++j) dp[i][j]=INF; for(int i=0;i<n;++i) dp[i][i]=0; for(int l=1;l<n;++l){ for(int i=0;i+l<n;++i){ int j=i+l; for(int k=i;k<=j;++k){ //枚举最后一个上场的下标K if(k==i){ dp[i][j]=min(dp[i][j],dp[k+1][j]+a[k]*l); } else if(k==j){ dp[i][j]=min(dp[i][j],dp[i][k-1]+a[k]*l); } else{ dp[i][j]=min(dp[i][j],dp[i][k-1]+dp[k+1][j]+(s[j+1]-s[k+1])*(k-i)+a[k]*l); //dp[i][j]=min(dp[i][j],dp[i][k-1]+dp[k+1][j]+(s[k]-s[i])*right+a[k]*(j-i)); 利用栈操作,序列123不能得到312 } } //cout<<"l="<<l<<' '<<i<<' '<<j<<' '<<dp[i][j]<<endl; } } printf("Case #%d: %d\n",cas++,dp[0][n-1]); } return 0; }