cherry picking

【Title description】

There are n cherries in a row, the sweetness of the i-th cherry is v[i], you need to divide the n cherries into several groups, and the cherries in each group must be adjacent. The deliciousness of each group of cherries is (sum-T)^2, where sum is the sum of the sweetness of the group of cherries, and T is the coefficient given by the input.

The delicacy of a group of plans is the sum of the delicacy of each group.

Find the minimum deliciousness of the feasible solutions.

【Input format】

Input file cherry.in

The first line contains two positive integers n and T.

The second line contains n integers, the ith integer is the sweetness of the ith cherry, v[i].

【Output format】

Output file cherry.out

One non-negative integer per line, the minimum delicacy.

【Sample input】

5 5

3 5 2 1 6

【Example output】

【data range】

For 50% of the data, n<=10, T<=1000, v[i]<=10

For 70% of the data, n<=100

For all data, n<=10^3,T<=1000,v[i]<=10

Each group of cherries must be adjacent to minimize the sum of taste. It is easy to think that it is similar to the merging of stones, and it can be done by interval division. But take a look at the data 1000, the complexity of n 3 should be tle (it turns out that it will be T).

So how should we optimize it? We can consider, instead of using interval division, we enumerate how many cherries there are, and then enumerate the cherries and the last cherries to form a group.

For specific implementation, we need the entire prefix sum (for sweetness), we can use f[i] to represent the minimum sweetness of the first i cherries. Then, use j to enumerate the group with the i-th cherries. The beginning of the number of cherries, then the state transition equation comes out

f[i]=min(f[i],f[j]+(sum[i]-sum[j-1]-t)*(sum[i]-sum[j-1]-t));

code at the end

 

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 using namespace std;
 5 int n,a[1010],f[1010],t,sum[1010];
 6 int main()
 7 {
 8     scanf("%d%d",&n,&t);
 9     memset(f,0x3f,sizeof(f));
10     for(int i=1;i<=n;++i)
11     {
12         scanf("%d",&a[i]);
13         sum[i]=sum[i-1]+a[i];
14     }
15     
16     f[1]=(a[1]-t )*(a[1]-t);
17     f[0]=0;
18     for(int i=2;i<=n;++i)
19     {
20         for(int j=i-1;j>=0;--j)
21         {
22             f[i]=min(f[i],f[j]+(sum[i]-sum[j]-t)*(sum[i]-sum[j]-t));
23         }
24     }
25     printf("%d",f[n]);
26     return 0;
27 }

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324924484&siteId=291194637