#include<bits/stdc++.h>
using namespace std;
using i64 = long long;
const int N = 1e6 + 5;
int cnt[N], a[N];
struct query {
int l, r, id;
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
int M = sqrt(n);
for (int i = 1; i <= n; i ++)
cin >> a[i];
int m;
cin >> m;
vector<query> q(m);
for (int i = 0; i < m; i ++) {
int l, r;
cin >> l >> r;
q[i] = {l, r, i};
}
//按分块大小排序,在同一个块的按块的奇偶性将右端点正序或逆序排序
sort(q.begin(), q.end(), [&M](query x, query y) {
return (((x.l / M) ^ (y.l / M)) ? x.l < y.l : ((x.l / M) & 1) ? x.r<y.r: x.r>y.r);
});
int l = 1, r = 0, now = 0;
vector<int> ans(m);
for (int i = 0; i < m; i ++) {
auto [ql, qr, id] = q[i];
//易错点
while (l < ql) now -= !--cnt[a[l++]];
while (l > ql) now += !cnt[a[--l]]++;
while (r < qr) now += !cnt[a[++r]]++;
while (r > qr) now -= !--cnt[a[r--]];
ans[id] = now;
}
for (int i = 0; i < m; i ++)
cout << ans[i] << "\n";
return 0;
}
标签:cnt,int,cin,++,--,now,莫队,模板
From: https://www.cnblogs.com/Kescholar/p/18306761