题解:P14558 [ROI 2013 Day2] 大规模预测
给定一个长度为
n ,值域为[1,k] 的序列a ,求出有多少个a 的子区间存在绝对众数。
注意到绝对众数,每个区间只会存在一个绝对众数,那么不妨把每一个 存在绝对众数的 区间的贡献放在其绝对众数处计算!不妨钦定它为
现在对一个
到这一步,其实对一个
我们考察哪些位置可能被一个和
考虑如何求出所有
那么有可能成为一个
直接把这些位置拿出来直接求逆序对就可以通过了,时间复杂度
如何做到线性?注意到对于一个合法的连续段,其内的所有
如果不写线性代码可以短很多,下面给出一份严格线性的实现:
const int N = 1.5e6 + 5;
int n, k, p[N], len, a[N], c[N];
vector<int> b1, b2, b;
vector<int> pos[N];
int t1[N], t2[N];
void solve() {
cin >> n >> k;
rep(i, 1, n) { int x; cin >> x; pos[x].pb(i); a[i] = x; }
LL ans = 0;
rep(v, 1, k) {
if (!SZ(pos[v])) continue;
len = SZ(pos[v]); p[len + 1] = n + 1;
rep(i, 1, len) p[i] = pos[v][i - 1];
b.clear(), b1.clear(), b2.clear();
int now = 0;
rep(i, 1, len) {
int x = p[i] + 1;
b1.pb(p[i]);
now += 1;
while (x < p[i + 1] && now >= 0)
b1.pb(x), ++x, --now;
tomax(now, 0);
}
now = 0;
per(i, len, 1) {
int x = p[i] - 1;
b2.pb(p[i]);
now += 1;
while (x > p[i - 1] && now >= 0)
b2.pb(x), --x, --now;
tomax(now, 0);
}
reverse(all(b2));
int i = 0, j = 0;
while (i < SZ(b1) && j < SZ(b2)) {
if (b1[i] < b2[j]) {
if (b.empty() || b1[i] != b[SZ(b) - 1])
b.pb(b1[i]);
++i;
}
else {
if (b.empty() || b2[j] != b[SZ(b) - 1])
b.pb(b2[j]);
++j;
}
}
while (i < SZ(b1)) {
if (b.empty() || b1[i] != b[SZ(b) - 1])
b.pb(b1[i]);
++i;
}
while (j < SZ(b2)) {
if (b.empty() || b2[j] != b[SZ(b) - 1])
b.pb(b2[j]);
++j;
}
j = 0;
for (auto x: b) {
while (j < len && p[j + 1] <= x) ++j;
t1[x] = j - (x - j) + n;
t2[x] = t1[x] - (a[x] == v? 1: -1);
}
int lst = 0, nowv = 1, w = 0;
for (auto x: b) {
if (x ^ (lst + 1))
nowv = t1[x], w = 0;
lst = x;
++c[t2[x]], w += (t2[x] < nowv);
while (nowv < t1[x]) w += c[nowv++];
while (nowv > t1[x]) w -= c[--nowv];
ans += w;
}
for (auto x: b)
c[t2[x]] = 0;
}
cout << ans << '\n';
}