Input
第1行:3个数N,K,Q,中间用空格分隔,N为数组A的长度,K为差距,Q为查询的数量。(2 <= N <= 50000, 0 <= K <= 10^9, 1 <= Q <= 50000)第2至N + 1行:每行1个数,对应数组中的数(1 <= A[i] <= 10^9)第N + 2至N + M + 1行:每行2个数l, r中间用空格分隔(0 <= l <= r < N)
Output
输出共Q行,对于Q条查询的结果。
Input示例
5 2 3134300 11 30 4
Output示例
136
题解: 莫队加树状数组乱搞
AC代码:
#include <bits/stdc++.h> #include <stdio.h> #include <algorithm> using namespace std; typedef long long ll; const int N = 5e5 + 5; typedef pair<int,int> P; P tmp[N]; int tid[N]; template<class T> void read(T & x) { char ch = getchar(); bool sign = false; x = 0; while (ch < '0' || ch > '9') { if (ch == '-') sign = true; ch = getchar(); } while ('0' <= ch && ch <= '9') { x = 10 * x + ch - '0'; ch = getchar(); } if (sign) x = -x; } template<class T> void print(T x) { if (x > 9) print(x / 10); putchar('0' + (x % 10)); } template<class T> void println(T x) { print(x); puts(""); } template<class T> inline T sqr(T a) { return a * a; } int c[N],a[N],b[N],n,unit,k,q; ll ans[N]; int find(int x) { int l = 0,r = n - 1; int ans = 0; while(l <= r) { int mid = l + r >> 1; if(a[mid] < x) l = mid + 1; else if(a[mid] == x) { return mid; } else r = mid - 1; } return l; } inline int ID(int x,int v) { int id = find(x); if(v) id++; else if(id < n && a[id] == x) id++; return id; } void add(int x,int d) { while(x <= n) { c[x] += d; x += x & -x; } } int que(int l,int r) { int s = 0; while(r > 0) { s += c[r]; r -= r & -r; } l--; while(l > 0) { s -= c[l]; l -= l & -l; } return s; } struct node { int l,r,id; void read(int i) { id = i; scanf("%d %d",&l,&r); } bool operator < (const node &a) const { if((l + 1) / unit != (a.l + 1) / unit) return (l + 1) / unit < (a.l + 1) / unit; return (r + 1) < a.r + 1; } }p[N]; void work() { ll temp = 0; int L = 1,R = 0; for(int i = 0; i < q; i++) { int l = p[i].l,r = p[i].r; while(R < r) { R++; temp += que(tmp[R].first,tmp[R].second); add(tid[R],1); } while(R > r) { add(tid[R],-1); temp -= que(tmp[R].first,tmp[R].second); R--; } while(L > l) { L--; temp += que(tmp[L].first,tmp[L].second); add(tid[L],1); } while(L < l) { add(tid[L],-1); temp -= que(tmp[L].first,tmp[L].second); L++; } ans[p[i].id] = temp; } } int main() { int NB; //freopen("in.txt","r",stdin); read(n),read(k),read(q); NB = n; for(int i = 0; i < n; i++) { read(a[i]); b[i] = a[i]; } sort(a,a + n); unit = (int) sqrt(n + 0.5); n = unique(a,a + n) - a; for(int i = 0; i < NB; i++) { tmp[i].first = ID(b[i] - k,1); tmp[i].second = ID(b[i] + k,0); tid[i] = ID(b[i],1); } for(int i = 0; i < q; i++) p[i].read(i); sort(p,p + q); work(); for(int i = 0; i < q; i++) { println(ans[i]); } return 0; }