问题 K: Together
时间限制: 1 Sec 内存限制: 128 MB
提交: 379 解决: 203
[提交] [状态] [讨论版] [命题人:admin]
题目描述
You are given an integer sequence of length N, a1,a2,…,aN.
For each 1≤i≤N, you have three choices: add 1 to ai, subtract 1 from ai or do nothing.
After these operations, you select an integer X and count the number of i such that ai=X.
Maximize this count by making optimal choices.
Constraints
1≤N≤105
0≤ai<105(1≤i≤N)
ai is an integer.
输入
The input is given from Standard Input in the following format:
N
a1 a2 .. aN
输出
Print the maximum possible number of i such that ai=X.
样例输入
7 3 1 4 1 5 9 2
样例输出
4
提示
For example, turn the sequence into 2,2,3,2,6,9,2 and select X=2 to obtain 4, the maximum possible count.
【题目大意】:
每一个数字都有三种操作 --- +1;-1;不变。每个数只能操作一次,找出操作后X出现的次数。
思路:
用cnt数组存每个数的出现次数(包括未出现的数字,未出现的数字的cnt就是0)
用b数组去重
如果数组只存在一种数字,答案就是 n;
如果不止一种数字,从a[0]开始,三个三个一组出现的次数的和,取最大值。
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int a[N];
int cnt[N];
int b[N];
bool cmp(int a,int b)
{
return a < b;
}
int main()
{
int n;
while(cin >> n)
{
memset(cnt,0,sizeof(cnt));
int j = 0;
for(int i=0; i<n; i++)
{
cin >> a[i];
cnt[a[i]] ++;
if(cnt[a[i]] == 1)
b[j++] = a[i];
}
if(j == 1)
{
cout << n << endl;
continue;
}
sort(a,a+n,cmp);
sort(b,b+j,cmp);
int maxx = 0;
int sum = 0;
for(int i=a[0]; i<a[n-1]; i++)
{
sum += cnt[i] + cnt[i+1] + cnt[i+2];
if(maxx < sum)
maxx = sum;
sum = 0;
}
cout << maxx << endl;
}
return 0;
}
欢迎指正与交流