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

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; 
}

更新

第二次遇到了这个题 ,突然想到了不同做法 , 我们 可以用记忆化搜索的 方法去做 , 看了一下 时间和 内存 和上面方法差不多 (内存多了 0.2MB) 。
具体看代码


const long long inf = 1e18;
int n,k,x;
int a[220];
long long dp[220][220];
int vis[220][220];

long long dfs(int nums,int now) {
    if(now == x ) { // 找到了第 x 个数
        vis[nums][now] = 1;
        if(nums + k-1 >=n) return dp[nums][now] = a[nums]; // 判断是否能覆盖剩余的所有数
        else return dp[nums][now] = -1;
    }
    if(nums == 0) {
        long long res = -1;
        for(int i= 1;i<min(n+1,1+k);i++) {
            res = max(res,dfs(i,now+1));
        }
        return res;
    }
    if(vis[nums][now] == 1) return dp[nums][now];
    dp[nums][now] = inf;
    long long res = -1;
    for(int i = nums+1 ;i <min(n+1,nums + k+1);i++) { // 和上述思路其实是相同的 即在 接下来的k 个数中选择一个数 .
        res = max(res,dfs(i,now+1));
    }
    dp[nums][now] = (res== -1? -1: res + a[nums]);
    vis[nums][now] = 1;
    return dp[nums][now];
}

int main() {
    cin>>n>>k>>x;
    for(int i=1;i<=n;i++) cin>>a[i];
    cout<<dfs(0,0)<<endl;
    return 0;
}

你可能感兴趣的:(DP)