锻炼思维题

E. Boxers

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

题目大意

给出一组数据,每个数可以加一或者减一,求不同数的个数最多可以为多少个?

思路

用推排序的思想,记录下每一个数据对应出现次数,然后遍历整个数组。
对每个位置,我们都要考虑上一个位置,当前位置,和下一个位置,这是可以相互补充的。
具体实现也很简单,判断上一个位置是否有数出现,有则ans+1;若没有,则判断当前数是否有数出现,有则ans+1,对应位置-1(为上一个位置补充);若没有,则判断下一个位置是否有数出现,有则ans+1,对应位置-1(为上一个位置补充);

AC代码

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=2e5;
int a[maxn],vis[maxn];
int main(){
    int n,ans=0,maxk=-2e6;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        int k;
        scanf("%d",&k);
        maxk=max(maxk,k);
        a[k]++;
    }
    for(int i=1;i<=maxk+1;i++){
        if(a[i-1]) ans++;
        else if(a[i]) ans++,a[i]--;
        else if(a[i+1]) ans++,a[i+1]--; 
    }
    printf("%d\n",ans);
    return 0;
}