time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are a coach at your local university. There are nn students under your supervision, the programming skill of the ii-th student is aiai.
You have to form kk teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than kk (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 55. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter).
It is possible that some students not be included in any team at all.
Your task is to report the maximum possible total number of students in no more than kk (and at least one) non-empty balanced teams.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains two integers nn and kk (1≤k≤n≤50001≤k≤n≤5000) — the number of students and the maximum number of teams, correspondingly.
The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is a programming skill of the ii-th student.
Output
Print one integer — the maximum possible total number of students in no more than kk (and at least one) non-empty balanced teams.
Examples
input
Copy
5 2 1 2 15 15 15
output
Copy
5
input
Copy
6 1 36 4 1 25 9 16
output
Copy
2
input
Copy
4 4 1 10 100 1000
output
Copy
4
假设表示当前将第i个人作为新的队伍的第一个人,且此时有j个非空队伍的状态对应的最大在队伍里的队员
数量
转移方向:
1.跳过第i个,直接转移到dp[i+1][j]
2,第i个单独形成一个新的队列 这个地方需要贪心地想一下,一旦形成了一个新的队列,题目的要求又没有
规定必须要k个非空,所以一旦形成一个新的队伍,就尽可能多得往这个队里插入队员是最好的
记录表示一旦选第i个选手作为这个队中能力最低的,这个队最多可以由多少人 dp[i][j]+cnt[i]
可以转移到dp[i+cnt[i]][j+1]
最后的答案就是max ( dp[i][j] )
#include<bits/stdc++.h>
using namespace std;
int dp[5010][5010],cnt[5010],a[5010];
int main()
{
int n,m;
scanf("%d %d",&n,&m);
for (int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
for (int i=0;i<n;i++)
cnt[i] = upper_bound(a,a+n,a[i]+5)-a-i;
int ans = -1;
for (int i=0;i<n;i++)
{
for (int j=0;j<=m;j++)
{
dp[i+1][j] = max(dp[i][j],dp[i+1][j]);
ans = max(ans,dp[i+1][j]);
if (j+1<=m)
{
dp[i+cnt[i]][j+1] = max(dp[i+cnt[i]][j+1],dp[i][j]+cnt[i]);
ans = max(dp[i+cnt[i]][j+1],ans);
}
}
}
printf("%d\n",ans);
return 0;
}