Codeforces Round #544(Div. 3)--Balanced Team(map的简单运用)

Balanced Team

time limit per test 2 seconds
memory limit per test 256 megabytes

题目链接https://codeforces.com/contest/1133/problem/C

You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is 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.

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 (1≤n≤2⋅10^5) — the number of students.The second line of the input contains n integers a1,a2,…,an
(1≤ai≤10^9), where ai is a programming skill of the i-th student.

Output
Print one integer — the maximum possible number of students in a balanced team.

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


题目大意:给你一个数组让你找到一个最大的集合,该集合内所有数相差不超过5.
问该集合最多有几个数。

这题比较简单,暴力一遍,每次寻找比该数小5之内的数或寻找比该数大5之内的数。
但怎么存数是个问题,只不过我们这题只需要向前找5和向后找5,是有一个确定范围的,所以只要有个映射判断这5个数有多少个就行了。。

#include <cstdio>
#include <map>
#define max(a,b) (a>b)?a:b
using namespace std;
map<int,int>q;           //将整数映射到整数上
int a[200050];
int main() {
	int n,ans=0;
	scanf ("%d",&n);
	for (int i=1; i<=n; i++) {
		scanf ("%d",&a[i]);
		q[a[i]]++;         //该值的个数
	}
	for (int i=1; i<=n; i++) {
		int sum=0;
		for (int j=a[i]-5; j<=a[i]; j++) {    //寻找不小于a[i]之差为5的个数
			if (j>0)
				sum+=q[j];
		}
		ans=max(ans,sum);      //更新ans
		sum=0;
		for (int j=a[i]; j<=a[i]+5; j++) {   //寻找不大于a[i]之差为5的个数
			if (j>0)
				sum+=q[j];
		}
		ans=max(ans,sum);
	}
	printf ("%d\n",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43906000/article/details/88359991