1066 - Buy Candy
Time Limit:1s Memory Limit:1024MByte
Submissions:185Solved:39
DESCRIPTION
PigVan ( Mr.Van's pet ) encounter a hard problem in his school. There are n groups children sit in a line. However, all groups dislike each other. Each group have a value which means how others dislike him. And PigVan wants to make all of them become one group. He can only merge two adjacent group into one. And if he wants to merge two groups of children, he needs to buy f(s) candies to them. ( s is the sum of their dislike value and f is a polynomial function of s ).
He wonder the minimal cost he will spend on candies.
INPUT
The first line is a single integer T, indicating the number of test cases.
For each test case:
In the first line, there are an integer n (1≤n≤1000)n (1≤n≤1000)
In the second line, there are nn integers. The ii thth integer ss ii (1 ≤ ss ii ≤ 40), indicating the dislike value of the ii thth child.
In the third line, there are an integer m (1≤m≤4)m (1≤m≤4)In the next line, there are m+1m+1 integers a 0 , a 1 ,..., a m.
The polynomial function f(x) = a 0 + a 1x + a 2x 2 +...+ a mx m (1≤(1≤a i ≤5)≤5)
For each test case:
In the first line, there are an integer n (1≤n≤1000)n (1≤n≤1000)
In the second line, there are nn integers. The ii thth integer ss ii (1 ≤ ss ii ≤ 40), indicating the dislike value of the ii thth child.
In the third line, there are an integer m (1≤m≤4)m (1≤m≤4)In the next line, there are m+1m+1 integers a 0 , a 1 ,..., a m.
The polynomial function f(x) = a 0 + a 1x + a 2x 2 +...+ a mx m (1≤(1≤a i ≤5)≤5)
OUTPUT
For each test case, output an integer indicating the answer.
SAMPLE INPUT
153 1 8 9 922 1 2
SAMPLE OUTPUT
2840
SOLUTION
#include <stdio.h>
#include <string.h>
#include <vector>
#define LL long long
using namespace std;
const int maxn = 1005;
const long long inf = 1LL << 62;
LL dp[maxn][maxn];
int p[maxn][maxn];
LL a[1005] = { 0 };
LL b[55];
int n, m;
LL jici(LL x, int y)
{
LL ret = 1;
for (int i = 1; i <= y; i++)
ret *= x;
return ret;
}
LL fun(LL x)
{
LL ret = 0;
for (int i = 0; i <= m; i++)
ret += jici(x, i)*b[i];
return ret;
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%lld", &a[i]);
a[i] += a[i - 1];
dp[i][i] = 0;
p[i][i] = i;
}
scanf("%d", &m);
for (int i = 0; i <= m; i++)
scanf("%lld", &b[i]);
LL sum = 0;
for (int len = 1; len <= n - 1; len++)
{
for (int i = 1; i + len <= n; i++)
{
int j = i + len;
LL F = fun(a[j] - a[i-1]);
dp[i][j] = inf;
for (int k = p[i][j - 1]; k <= p[i + 1][j]; k++)
{
if (dp[i][j] > dp[i][k] + dp[k + 1][j]+F)
{
dp[i][j] = dp[i][k] + dp[k + 1][j] + F;
p[i][j] = k;
}
}
}
}
printf("%lld\n", dp[1][n]);
}
return 0;
}