Codeforces 544E K Balanced Teams (DP)
题目:
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-1][j],dp[pos-1][j-1]+i-pos+1);
代码:
#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=5010;
int n,k;
int a[maxn],dp[maxn][maxn];
int main(){
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
sort(a+1,a+1+n);
int pos=1;
dp[0][0]=0;
for(int i=1;i<=n;i++){
while(a[i]-a[pos]>5 && pos<=n) pos++;
for(int j=1;j<=min(i,k);j++){
dp[i][j]=dp[i-1][j];
dp[i][j]=max(dp[i][j],dp[pos-1][j-1]+i-pos+1);
}
}
int ans=0;
for(int i=1;i<=k;i++){
ans=max(ans,dp[n][i]);
}
printf("%d\n",ans);
return 0;
}