cf1203E E. Boxers

该博客探讨了一个竞赛问题:如何从n个拳击手中选择体重各不相同的最大团队。每个拳击手的体重可以在比赛前改变不超过1单位。通过贪心算法,可以找到最优解决方案。例如,在给定的输入情况下,可以通过调整拳击手的体重来创建一个包含4或5个不同体重的团队。博客内容包括问题描述、示例解释以及实现贪心策略的详细步骤和代码分析。
摘要由CSDN通过智能技术生成

E. Boxers
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
There are n boxers, the weight of the i-th boxer is ai. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.

It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers’ weights in the team are different (i.e. unique).

Write a program that for given current values ​ai will find the maximum possible number of boxers in a team.

It is possible that after some change the weight of some boxer is 150001 (but no more).

Input
The first line contains an integer n (1≤n≤150000) — the number of boxers. The next line contains n integers a1,a2,…,an, where ai (1≤ai≤150000) is the weight of the i-th boxer.

Output
Print a single integer — the maximum possible number of people in a team.

Examples
input

4
3 2 4 1
output
4
input
6
1 1 1 4 4 4
output
5
Note
In the first example, boxers should not change their weights — you can just make a team out of all of them.

In the second example, one boxer with a weight of 1 can be increased by one (get the weight of 2), one boxer with a weight of 4 can be reduced by one, and the other can be increased by one (resulting the boxers with a weight of 3 and 5, respectively). Thus, you can get a team consisting of boxers with weights of 5,4,3,2,1.
题意: 给出n个元素,可以对每个元素进行加一或减一或不变,问最后最多有多少个不同的元素,元素变化后的范围为1-n+1.
思路: 先对数组元素进行排序,对于1元素进行特判,因为0元素无效,先判断1本身是否出现,若没则标记1,否则标记为2,对于其他元素,利用贪心思路,先向左边扩展,再考虑元素本身,最后考虑向右扩展,详情看代码和注释。

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 50002;
int a[N], book[N];
int main() {
	int n;
	scanf("%d", &n);
	memset(book, 0 , sizeof(book));
	for (int i = 1; i<= n; i++) {
		scanf("%d", &a[i]);
	}
	sort(a + 1, a + n + 1);
	for (int i = 1; i <= n; i++) {
		if (a[i] - 1 == 0) { // 对1进行特判 
			if (book[a[i]] == 0) book[a[i]]++; // 如果当前1元素未标记,则标记1 
			else book[a[i] + 1]++; // 否则标记为2 
		}
		else {
			// 对于其他元素利用贪心思路,若左边的元素未标记先向左边扩展,其次再是本身元素,最后才是右边扩展 
			if (book[a[i] - 1] == 0) book[a[i] - 1]++;
			else {
				if (book[a[i]] == 0) book[a[i]]++;
				else book[a[i] + 1]++;
			} 
		}
	}
	int ans = 0;
	for (int i = 1; i < N; i++) if (book[i]) ans++;
	printf("%d\n", ans);
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值