R1_B_Teamwork

题面

For his favorite holiday, Farmer John wants to send presents to his friends. Since he isn’t very good at wrapping presents, he wants to enlist the help of his cows. As you might expect, cows are not much better at wrapping presents themselves, a lesson Farmer John is about to learn the hard way.

Farmer John’s NN cows (1≤N≤104) are all standing in a row, conveniently numbered 1…Nin order. Cow ii has skill level sisi at wrapping presents. These skill levels might vary quite a bit, so FJ decides to combine his cows into teams. A team can consist of any consecutive set of up to KK cows (1≤K≤103), and no cow can be part of more than one team. Since cows learn from each-other, the skill level of each cow on a team can be replaced by the skill level of the most-skilled cow on that team.

Please help FJ determine the highest possible sum of skill levels he can achieve by optimally forming teams.

Input

The first line of input contains NN and KK. The next NN lines contain the skill levels of the NN cows in the order in which they are standing. Each skill level is a positive integer at most 105.

Output

Please print the highest possible sum of skill levels FJ can achieve by grouping appropriate consecutive sets of cows into teams.

input

7 3
1
15
7
9
2
5
10

output

84

Note

In this example, the optimal solution is to group the first three cows and the last three cows, leaving the middle cow on a team by itself (remember that it is fine to have teams of size less than KK). This effectively boosts the skill levels of the 7 cows to 15, 15, 15, 9, 10, 10, 10, which sums to 84.

题目大意

给定一个长度为N的序列,划分成几个部分,每个部分的长度不超过K,而这一部分的值为这一部分中最大的数乘以这一部分的长度。问题是怎么划分使得这几个部分的和最大。

题目分析

一开始想的是贪心,然后发现好像不行……

这道题用的是DP。我们定义 d p [ i ] dp[i] 为前 i i 个数已经划分成几个部分,而且这几个部分的和已经最大了。那么根据题意,我们就有如下的式子:
d p [ i + j ] = m a x ( d p [ i ] + j × m a x ) dp[i + j] = max(dp[i]+j \times max)
这就是状态转移方程,其中 1 j K 1 \le j \le K m a x max a r r [ i + 1 ] , a r r [ i + 2 ] , a r r [ i + 3 ] a r r [ i + j ] arr[i+1],arr[i+2],arr[i+3]\cdots arr[i+j] 中,最大的那一个。显然,前0个的值是零。也就是 d p [ 0 ] = 0 dp[0] = 0 ,这样就要可以递推下去了。 d p [ n ] dp[n] 就是答案。

代码

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 1e5 + 7;
typedef long long ll;
ll arr[maxn], dp[maxn];
int n, m;
int main(int argc, char const *argv[]) {
  scanf("%d%d", &n, &m);
  for(int i = 0; i < n; i++)
    scanf("%lld", &arr[i]);
  dp[0] = 0;
  for(int i = 0; i < n; i++){
    ll mx = arr[i];
    for(int j = 1; j <= m; j++){
      if(i + j > n)
        continue;
      dp[i + j] = max(dp[i] + mx * j, dp[i + j]);
      mx = max(mx, arr[i + j]);
    }
  }
  printf("%lld\n", dp[n]);

  return 0;
}

猜你喜欢

转载自blog.csdn.net/IT_w_TI/article/details/87830646
今日推荐