题目链接:https://codeforces.com/contest/1203/problem/E
思路:一开始想的是记录数字出现次数,看每个数字的三种变化能否产生新数,但是这样容易多算或者少算答案。 可以使用贪心的思想,将数组以非增排序,然后从最大的数开始取三种变化,设置一个数组当前最大值,如果最大值比新数大,就更新最大值,并让答案加1
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
int a[maxn];
int f[5] = {1,0,-1};
int main() {
int n;
ios::sync_with_stdio(0);
cin >> n;
int ans = 0;
for(int i = 0 ; i < n; i++) {
cin >> a[i];
}
sort(a,a+n);
int cnt = a[n-1] + 2;
for(int i = n-1 ; i >= 0; i--) {
int t = -1;
for(int j = 0; j < 3; j++) {
int tmp = a[i] + f[j];
if(tmp > 0 && tmp < cnt) {
t = tmp;
cnt = t;
break;
}
}
if(t == -1)continue;
ans++;
}
cout << ans << "\n";
return 0;
}