主要考察对vector的使用
题意概括:给你一段序列,要求你将l到r区间内的数全部加K,这个l和r可以由你任意取。最后求所有可能的方案中众数的最大个数。
我们可以理解为x和x+k只能选择其中之一。当然必须选连续的一段。
然后我们可以知道最后的众数一定是序列a的其中一个,枚举这个数字,然后用vector v[x]储存可以变成x的所有数,也就是x和x-k,然后这个最大众数可以用类似前缀和的方式快速计算出。(就是遍历然后求左边的最大值,详情见代码)
综合复杂度不超过2*n
由于x和x+k只能选择一个,当k≠0时上述算法显然是满足的。但k=0时就同时统计了x和x+k,所以这种情况下的答案要除以二
#include <bits/stdc++.h>
using namespace std;
#define go(i, a, b) for (int i = a; i <= b; ++i)
const int N = 1e6 + 10, B = 1e6;
int n, k, vis[2 * N];
vector<int> v[2 * N];
vector<int> app;
void read(int &x) {
int f = 1;
char c;
c = getchar();
x = 0;
while (!isdigit(c)) {
if (c == '-') f = -1;
c = getchar();
}
while (isdigit(c)) {
x = x * 10 + c - '0';
c = getchar();
}
x *= f;
}
signed main() {
// freopen("input.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
cin >> n >> k;
int x;
app.reserve(2 * n);
go(i, 1, n) {
read(x);
x += B;
if (!vis[x]) {
app.push_back(x);
vis[x] = 1;
}
v[x].push_back(x);
if (x + k >= 0 && x + k <= 2 * B) {
v[x + k].push_back(x);
}
}
int ans = 0;
for (auto num : app) {
if (!v[num].size()) continue;
// cout << num << endl;
int addk = 0, nok = 0, mx = 0;
int all = 0;
for (auto x : v[num]) all += x == num;
ans = max(ans, all);
for (auto x : v[num]) {
addk += x != num;
nok += x == num;
ans = max(ans, all - nok + addk + mx);
mx = max(mx, nok - addk);
}
}
if (k == 0)
cout << ans / 2 << endl;
else
cout << ans << endl;
return 0;
}