luogu P4887 莫队二次离线
珂朵莉给了你一个序列$a$,每次查询给一个区间$[l,r]$
查询$l≤i<j≤r$,且$ai⊕aj$的二进制表示下有$k$个$1$的二元组$(i,j)$的个数。$⊕$是指按位异或。
直接暴力莫队的话复杂度是$O(n\sqrt{m}\binom{14}{7})$, 有一种做法是莫队二次离线
考虑莫队的过程, 假设当前维护的区间为$[ql,qr]$
若右端点移动到$r$, 那么答案的增量为
$\sum\limits_{k=qr+1}^r f(k,[ql,k-1])=\sum\limits_{k=qr+1}^r f(k,[1,k-1])-\sum\limits_{k=qr+1}^rf(k,[1,ql-1])$
$f(k,[1,k-1])$可以预处理出来, $f(k,[1,ql-1])$可以离线以后扫描线.
总的复杂度就是$O(n\sqrt{m}+n\binom{14}{7})$
#include <iostream> #include <sstream> #include <algorithm> #include <cstdio> #include <cmath> #include <set> #include <map> #include <queue> #include <string> #include <cstring> #include <bitset> #include <functional> #include <random> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl '\n' #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<',';hr;}) using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;} //head const int N = 1e5+10; const int M = 1<<14; int n, m, k, sqn, cnt; int a[N], blo[N], f[N]; struct _ { int l,r,id; ll ans; bool operator < (const _ & rhs) const { return blo[l]^blo[rhs.l]?l<rhs.l:blo[l]&1?r<rhs.r:r>rhs.r; } } q[N]; vector<_> g[N]; ll ans[N]; int vis[N],pre[N]; int main() { scanf("%d%d%d", &n, &m, &k); sqn = pow(n,0.55); REP(i,1,n) scanf("%d",a+i),blo[i]=i/sqn; REP(i,1,m) { scanf("%d%d",&q[i].l,&q[i].r); q[i].id = i; } if (k>14) { REP(i,1,m) puts("0"); return 0; } REP(i,0,M-1) if (__builtin_popcount(i)==k) f[++cnt] = i; REP(i,1,n) { REP(j,1,cnt) pre[i]+=vis[f[j]^a[i]]; ++vis[a[i]]; } sort(q+1,q+1+m); int ql=1, qr=0; REP(i,1,m) { int l = q[i].l, r = q[i].r; if (ql<l) g[qr].pb({ql,l-1,-i}); while (ql<l) q[i].ans+=pre[ql++]; if (ql>l) g[qr].pb({l,ql-1,i}); while (ql>l) q[i].ans-=pre[--ql]; if (qr<r) g[ql-1].pb({qr+1,r,-i}); while (qr<r) q[i].ans+=pre[++qr]; if (qr>r) g[ql-1].pb({r+1,qr,i}); while (qr>r) q[i].ans-=pre[qr--]; } REP(i,0,M-1) vis[i] = 0; REP(i,1,n) { REP(j,1,cnt) ++vis[a[i]^f[j]]; for (auto &t:g[i]) { REP(j,t.l,t.r) { int ret = vis[a[j]]; if (j<=i&&!k) --ret; if (t.id<0) q[-t.id].ans-=ret; else q[t.id].ans+=ret; } } } REP(i,1,m) q[i].ans+=q[i-1].ans; REP(i,1,m) ans[q[i].id] = q[i].ans; REP(i,1,m) printf("%lld\n",ans[i]); }