题解:P8349 [SDOI/SXOI2022] 整数序列
感觉显式的根号分治还是太不优美了。
Solution
设
设
对于一个只包含在
因此,把
考虑怎么把这些点抠出来。从左往右枚举
只会有
一次询问复杂度为
Code
很短。
#include <bits/stdc++.h>
#define REP(i, l, r) for (int i = (l); i <= (r); ++ i)
#define DEP(i, r, l) for (int i = (r); i >= (l); -- i)
#define fi first
#define se second
#define pb emplace_back
#define mems(x, v) memset((x), (v), sizeof(x))
#define SZ(x) (int)(x).size()
#define ALL(x) (x).begin(), (x).end()
#define ppc(x) __builtin_popcount(x)
using namespace std;
namespace Milkcat {
typedef long long LL;
typedef pair<LL, LL> pii;
typedef vector<int>::iterator IT;
const int N = 3e5 + 5;
LL n, q, x, y, a[N], c[N], b[N * 2];
vector<int> s[N]; map<int, LL> mp[N];
int main() {
cin >> n >> q;
REP(i, 1, n) cin >> c[i], s[c[i]].pb(i);
REP(i, 1, n) cin >> a[i];
REP(te, 1, q) {
cin >> x >> y;
if (SZ(s[x]) > SZ(s[y])) swap(x, y);
if (mp[x].count(y)) { cout << mp[x][y] << '\n'; continue; }
vector<int> B; vector<IT> A{s[y].begin()};
for (int i : s[x])
A.pb(lower_bound(ALL(s[y]), i)), B.pb(i);
A.pb(s[y].end());
int t = 0;
REP(i, 1, SZ(A) - 2) {
auto it = A[i];
for (t ++; ~t && it != A[i + 1]; )
B.pb(*it ++), t --;
t = max(t, 0);
}
t = 0;
DEP(i, SZ(A) - 2, 1) {
auto it = A[i];
for (t ++; ~t && it != A[i - 1]; )
B.pb(*-- it), t --;
t = max(t, 0);
}
sort(ALL(B)), B.erase(unique(ALL(B)), B.end());
LL rs = -1e18, sm = 0, d = SZ(B); t = d;
REP(i, 0, d * 2) b[i] = (i == d ? 0 : 1e18);
for (int i : B) {
t += (c[i] == x ? 1 : -1), sm += a[i];
rs = max(rs, sm - b[t]), b[t] = min(b[t], sm);
}
cout << (mp[x][y] = rs) << '\n';
}
return 0;
}
}
int main() {
cin.tie(0)->sync_with_stdio(0);
int T = 1;
while (T --) Milkcat::main();
return 0;
}