codeforce 1077 F1 and F2 - DP
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
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
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.
The first line of the input contains three integers n,kn,k and xx (1≤k,x≤n≤2001≤k,x≤n≤200) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost.
The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the beauty of the ii-th picture.
OutputPrint -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement.
Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
Examples : input5 2 3 5 1 3 10 1output
18input
6 1 5 10 30 30 70 10 10output
-1input
4 3 1 1 100 1 1output 100
題目的大意:給定n個長度的序列,選出x個元素。要求:在任意長度為k的區間內至少有1個元素被選中。
主要思路:利用dp的方法解決。
轉移方程:dp[i][j]=max(dp[i][j],dp[s][j?1]+a[i]) s為區間[i?k,i)。
easy version 代碼如下:
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll; //防止int上溢
const int MAXN = 200;
ll dp[MAXN + 5][MAXN + 5];
ll store[MAXN + 5];
int n = 0, k = 0, x = 0;
int main()
{
while (cin >> n >> k >> x) {
for (int i = 1; i <= n; ++i) {
cin >> store[i];
}
if (k*(x+1) <= n) { //查看是否有解
printf("-1\n");
continue;
}
int mi = 0, l = 0;
for (int i = 1; i <= x; ++i) {
l = min(n+1, i*k+1); //選擇i個最長能到l-1個元素
for (int j = 1; j < l; ++j) {
mi = max(j - k, 0); //上一個狀態轉移的範圍
for (int s = mi; s < j; ++s) {
dp[i][j] = max(dp[i