Zuosige always has bad luck. Recently, he is in hospital because of
pneumonia. While he is taking his injection, he feels extremely bored. However,
clever Zuosige comes up with a new game.
Zuosige knows there is a typical problem called Merging Stones. In the
problem, you have N heaps of stones and you are going to merging them into one
heap. The only restriction is that you can only merging adjacent heaps and the
cost of a merging operation is the total number of stones in the two heaps
merged. Finally, you are asked to answer the minimum cost to accomplish the
merging.
However, Zuosige think this problem is too simple, so he changes it. In his
problem, the cost of a merging is a polynomial function of the total number of
stones in those two heaps and you are asked to answer the minimum
cost.
The first line contains one integer T, indicating the number of test
cases.
In one test case, there are several lines.
In the first line, there
are an integer N (1<=N<=1000).
In the second line, there are N
integers. The i-th integer si (1<=si<=40) indicating
the number of stones in the i-th heap.
In the third line, there are an
integer m (1<=m<=4).
In the forth line, there are m+1 integers
a0, … , am. The polynomial function is P(x)=
(a0+a1*x+a2*x2+…+am*xm).
(1<=ai<=5)
For each test case, output an integer indicating the answer.
1 #include<iostream>
2 #include<cstdio>
3 #include<algorithm>
4 #include<cstring>
5
6 using namespace std;
7
8 #define ll long long
9
10 //const long long MAX=0xfffffffffffffff;
11
12 ll num[1010],nmul[40050]; //nmul:储存预处理的结果
13 ll dp[1010][1010],mm[10];
14 ll snum[1010]; //记录各数字的和
15 int kk[1010][1010]; //记录上一层次的断点
16
17 ll Pow(ll a,int k)
18 {
19 ll s=1;
20 for(int i=1; i<=k; i++)
21 s*=a;
22 return s;
23 }
24
25 void Mul(int n,int m)
26 {
27 for(int i=0;i<=snum[n-1];i++)
28 {
29 nmul[i]=0;
30 for(int j=0;j<=m;j++)
31 nmul[i]+=mm[j]*Pow(i,j);
32 }
33 }
34
35 int main()
36 {
37 int t,n,m;
38 /*for(int i=0; i<=40005; i++)
39 {
40 for(int j=0; j<=4; j++)
41 dd[i][j]=Pow(i,j);
42 }*/
43 scanf("%d",&t);
44 while(t--)
45 {
46 //snum[0]=0;
47 //memset(dp,0,sizeof(dp));
48 scanf("%d",&n);
49 for(int i=0; i<n; i++)
50 {
51 scanf("%lld",&num[i]);
52 if(i==0)
53 snum[i]=num[i];
54 else
55 snum[i]=snum[i-1]+num[i];
56 }
57 scanf("%d",&m);
58 for(int i=0; i<=m; i++)
59 scanf("%lld",&mm[i]);
60 Mul(n,m);
61 for(int i=0; i<n; i++)
62 dp[i][i]=0,kk[i][i]=i;
63 for(int l=2; l<=n; l++)
64 {
65 for(int s=0; s<n-l+1; s++)
66 {
67 int e=s+l-1;
68 ll ss=1e63; //一定要定义成最大值
69 for(int k=kk[s][e-1]; k<=kk[s+1][e]; k++) //从两个断点之间找
70 {
71 if(ss>dp[s][k]+dp[k+1][e])
72 {
73 ss=dp[s][k]+dp[k+1][e];
74 kk[s][e]=k;
75 }
76 //ss=dp[s][k]+dp[k+1][e]>ss?ss:dp[s][k]+dp[k+1][e];
77 }
78 /*ll sum=0,sss=0;
79 for(int k=s; k<=e; k++)
80 sum+=num[k];
81 for(int k=0; k<=m; k++)
82 sss+=mm[k]*Pow(sum,k);*/
83 dp[s][e]=ss+nmul[snum[e]-snum[s-1]];;
84 //printf("s=%d,e=%d,dp=%lld\n",s,e,dp[s][e]);
85 }
86 }
87 printf("%lld\n",dp[0][n-1]);
88 }
89 return 0;
90 }