题目:
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 totalnumber 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.
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.
Print one integer — the maximum possible total number of students in no more than kk (and at least one) non-empty balanced teams.
5 2
1 2 15 15 15
5
6 1
36 4 1 25 9 16
2
4 4
1 10 100 1000
4
题意:
有n个学生 要求组成k个小组 每个小组中两两差值不得超过5 可以有学生不被编入组中 求最多可以有多少个学生被编入组中 思路:
采取线性dp的思路
将每个学生的值a[i]从小到大排序
排序后 每个小组必定可以视为一段连续区域 则将pos设为一段连续区间的左端点
dp[i][j]表示到第i个学生为止 前面分为j组的最多学生数
状态转移方程为
dp[i][j]=max(dp[i-][j],dp[pos-][j-]+i-pos+);
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm> using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int maxn=;
int n,k;
int a[maxn],dp[maxn][maxn]; int main(){
scanf("%d%d",&n,&k);
for(int i=;i<=n;i++){
scanf("%d",&a[i]);
}
sort(a+,a++n);
int pos=;
dp[][]=;
for(int i=;i<=n;i++){
while(a[i]-a[pos]> && pos<=n) pos++;
for(int j=;j<=min(i,k);j++){
dp[i][j]=dp[i-][j];
dp[i][j]=max(dp[i][j],dp[pos-][j-]+i-pos+);
}
}
int ans=;
for(int i=;i<=k;i++){
ans=max(ans,dp[n][i]);
}
printf("%d\n",ans);
return ;
}