Codeforces div3 Balanced Team (贪心+寻找最长子序列)

You are a coach at your local university. There are
n
n
students under your supervision, the programming skill of the
i
i
-th student is
a
i
ai
.
You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maximum number of students. But you also know that a team should be balanced. It means that the programming skill of each pair of students in a created team should differ by no more than
5
5
.
Your task is to report the maximum possible number of students in a balanced team.
Input
The first line of the input contains one integer
n
n
(
1≤n≤2⋅
10
5
1≤n≤2⋅105
) — the number of students.
The second line of the input contains
n
n
integers
a
1
,
a
2
,…,
a
n
a1,a2,…,an
(
1≤
a
i

10
9
1≤ai≤109
), where
a
i
ai
is a programming skill of the
i
i
-th student.
Output
Print one integer — the maximum possible number of students in a balanced team.
Examples
Input
Copy
6
1 10 17 12 15 2
Output
Copy
3
Input
Copy
10
1337 1337 1337 1337 1337 1337 1337 1337 1337 1337
Output
Copy
10
Input
Copy
6
1 1000 10000 10 100 1000000000
Output
Copy
1
Note
In the first example you can create a team with skills
[12,17,15]
[12,17,15]
.
In the second example you can take all students in a team because their programming skills are equal.
In the third example you can create a team consisting of a single student (and you cannot create a team consisting of at least two students).
问题链接: http://codeforces.com/contest/1133/problem/C
问题简述: 给定n个成员数据,求最多能组的成员数(两两数据之差不能超过5)
问题分析: 先排序,再贪心,具体可看代码及以下注释
AC通过的C++语言程序如下:


#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<string>
#include<bitset>
#include<utility>
#include<functional>
#include<iomanip>
#include<sstream>
#include<ctime>
using namespace std;

const int N=200005;

int main()
{
	int n,ans=0;
	cin>>n;
	int cnt[N];//存储所有队员
	for(int i=0;i<n;i++)
		cin>>cnt[i];
	sort(cnt,cnt+n);//由小到大排序
	int lef=0,rig=1;//左边界&&右边界
	while(lef<n-1&&rig<n)//左边界小于n-1且右边界小于n
    {
        if(cnt[rig]-cnt[rig-1]>5)//当右边界界限范围超过5,直接左边界右移
        {
            ans=max(ans,rig-1-lef);//寻找最长子序列
            lef=rig;
            rig++;
        }
        else if(cnt[rig]-cnt[lef]>5)//如果右边界减左边界大于5,左边界右移并且重新找到最大值
        {
            ans=max(ans,rig-1-lef);
            lef++;
            if(lef==rig) rig++;//如果左右相等,则右边界移动
        }
        else
            rig++;//其余情况右边界移动
    }
    ans=max(ans,rig-1-lef);//再找一次最大
	cout<<ans+1;//记得加一后输出
	return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值