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) OutputFor each test case, output the least summary of unhappiness .
Sample Input
2 512345554322
Sample Output
Case #1: 20Case #2: 24 题目大意: n个人,每个的都有一个值d,定义不开心值为(k-1)*d,k代表第k个出场,根据入栈出栈的不同情况, 最后会有很多种出场顺序,求最小的总不开心值。 可得情况数是个卡特兰数,第100项很大,而且不好枚举。 dp[i][j]可通过枚举中间点得到。有两种状态:(pre为前缀和,sum[i][j]代表出场顺序为j~i的总不开心值) 1.dp[i][k]+dp[k+1][j]+(pre[j]-pre[k])*(k-i+1) 2.dp[k+1][j]+sum[i][k]+(pre[k]-pre[i-1])*(j-k)
#include#include #include using namespace std;const int INF=0x3f3f3f3f;int a[105],pre[105],dp[105][105],sum[105][105];int n;int main(){ int T,o=0; cin>>T; while(T--) { memset(pre,0,sizeof pre); memset(sum,0,sizeof sum); memset(dp,INF,sizeof dp); cin>>n; for(int i=1;i<=n;i++)///预处理前缀和 cin>>a[i],pre[i]=pre[i-1]+a[i],dp[i][i]=0; for(int j=1;j<=n;j++)///预处理倒着的不开心值 for(int i=j-1;i>0;i--) sum[i][j]=sum[i+1][j]+a[i]*(j-i); for(int j=1;j<=n;j++) for(int i=j-1;i>0;i--) for(int k=i;k