CodeForces - 1077F1 Pictures with Kittens (easy version) (动态规划)

The only difference between easy and hard versions is the constraints.
Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of nn consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the ii-th picture has beauty aiai.
Vova wants to repost exactly xx pictures in such a way that:

each segment of the news feed of at least kk consecutive pictures has at least one picture reposted by Vova;
the sum of beauty values of reposted pictures is maximum possible.

For example, if k=1k=1 then Vova has to repost all the pictures in the news feed. If k=2k=2 then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.
Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.

题意:给你一个长度为N的序列,问从中取X个值的最大和,要求在原序列中每K个连续的序列里必须最少要有一个值被选择.
思路:1.求长度为N的序列里面去X个值的最大和,我们很快就可以想到用DP的思想。
2.每K个连续序列里必须要有一个值被选择,就代表我们选择的两个相邻的值的位置相隔不能超过K(否则他们两个之间就有一定有连续为K的序列中不含有被选择的值).
3.结合上述1.2的思路,我们可以尝试用DP求最大和,同时用所选择的两个相邻值之间相隔不超过K的条件来维护每次DP更新值的范围.
我用dp [i] [j] 来表示取第i个值时已经取了j个值的最大和。
动态转移方程为
dp [i] [j] = max ( dp [q] [j-1] (i-k<=q<i ) ) + a[i]

AC代码如下:

long long a[210];
long long dp[210][210]={0};
int main() {
	int n,k,x;
	cin>>n>>k>>x;
	for(int i=0;i<n;i++) {
 		cin>>a[i];
  	if(i<k) dp[i][1]=a[i];
 	}
 	for(int i=0;i<n;i++) {
  		for(int l=1;l<=x;l++) {
   			if(dp[i][l]==0) continue;
   			for(int j=i+1;j<=i+k&&j<n;j++) {
    				dp[j][l+1] = max(dp[j][l+1],dp[i][l]+a[j]);
   			}
  		}
 	}
 	long long ans = -1;
 	for(int i=n-k;i<n;i++) {
  		if(dp[i][x]==0) continue;
  	ans = max(ans,dp[i][x]);
 	}
 	cout<<ans<<endl; 
 	return 0; 
}

不懂的可以在评论区留言;
加油

猜你喜欢

转载自blog.csdn.net/qq_43305984/article/details/88533813