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;
}