离线+分块
将n个数分成sqrt(n)块。
对所有询问进行排序,排序标准:
1. Q[i].left /block_size < Q[j].left / block_size (块号优先排序)
2. 如果1相同,则 Q[i].right < Q[j].right (按照查询的右边界排序)
问题求解:
从上一个查询后的结果推出当前查询的结果。(这个看程序中query的部分)
如果一个数已经出现了x次,那么需要累加(2*x+1)*a[i],因为(x+1)^2*a[i] = (x^2 +2*x + 1)*a[i],x^2*a[i]是出现x次的结果,(x+1)^2 * a[i]是出现x+1次的结果。
时间复杂度分析:
排完序后,对于相邻的两个查询,left值之间的差最大为sqrt(n),则相邻两个查询左端点移动的次数<=sqrt(n),总共有t个查询,则复杂度为O(t*sqrt(n))。
又对于相同块内的查询,right端点单调上升,每一块所有操作,右端点最多移动O(n)次,总块数位sqrt(n),则复杂度为O(sqrt(n)*n)。
right和left的复杂度是独立的,因此总的时间复杂度为O(t*sqrt(n) + n*sqrt(n))。
代码如下:
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #include <cstring> 5 #include <cmath> 6 using namespace std; 7 #define N 200100 8 typedef long long ll; 9 ll a[N], cnt[N*5], ans[N], res; 10 int L, R; 11 12 struct node { 13 int x, y, l, p; 14 } q[N]; 15 bool cmp(const node &x, const node &y) { 16 if (x.l == y.l) return x.y < y.y; 17 return x.l < y.l; 18 } 19 void query(int x, int y, int flag) { 20 if (flag) { 21 for (int i=x; i<L; i++) { 22 res += ((cnt[a[i]]<<1)+1)*a[i]; 23 cnt[a[i]]++; 24 } 25 for (int i=L; i<x; i++) { 26 cnt[a[i]]--; 27 res -= ((cnt[a[i]]<<1)+1)*a[i]; 28 } 29 for (int i=y+1; i<=R; i++) { 30 cnt[a[i]]--; 31 res -= ((cnt[a[i]]<<1)+1)*a[i]; 32 } 33 for (int i=R+1; i<=y; i++) { 34 res += ((cnt[a[i]]<<1)+1)*a[i]; 35 cnt[a[i]]++; 36 } 37 38 } else { 39 for (int i=x; i<=y; i++) { 40 res += ((cnt[a[i]]<<1)+1)*a[i]; 41 cnt[a[i]]++; 42 } 43 } 44 L = x, R = y; 45 } 46 int main() { 47 int n, t; 48 49 scanf("%d%d", &n, &t); 50 for (int i=1; i<=n; i++) scanf("%I64d", &a[i]); 51 int block_size = sqrt(n); 52 53 for (int i=0; i<t; i++) { 54 scanf("%d%d", &q[i].x, &q[i].y); 55 q[i].l = q[i].x / block_size; 56 q[i].p = i; 57 } 58 59 sort(q, q+t, cmp); 60 61 62 memset(cnt, 0, sizeof(cnt)); 63 64 res = 0; 65 for (int i=0; i<t; i++) { 66 query(q[i].x, q[i].y, i); 67 ans[q[i].p] = res; 68 } 69 70 for (int i=0; i<t; i++) printf("%I64d ", ans[i]); 71 72 return 0; 73 }