HDU_3874
这个题目和HDU_3333几乎一模一样,具体的思路可以参考我的HDU_3333的题解:http://www.cnblogs.com/staginner/archive/2012/04/13/2445104.html。
#include<stdio.h> #include<string.h> #include<stdlib.h> #define MAXD 50010 #define MAXQ 200010 long long int sum[4 * MAXD]; int N, Q, a[MAXD], tx[MAXD], X, r[MAXQ], where[MAXD]; struct Question { int x, y; long long int ans; }question[MAXQ]; int cmpint(const void *_p, const void *_q) { int *p = (int *)_p, *q = (int *)_q; return *p - *q; } int cmpq(const void *_p, const void *_q) { int *p = (int *)_p, *q = (int *)_q; return question[*p].y < question[*q].y ? -1 : 1; } void init() { int i, j, k; scanf("%d", &N); for(i = 1; i <= N; i ++) { scanf("%d", &a[i]); tx[i] = a[i]; } qsort(tx + 1, N, sizeof(tx[0]), cmpint); X = 0; for(i = 1; i <= N; i ++) if(i == 1 || tx[i] != tx[i - 1]) { where[X] = -1; tx[X ++] = tx[i]; } scanf("%d", &Q); for(i = 0; i < Q; i ++) { scanf("%d%d", &question[i].x, &question[i].y); r[i] = i; } qsort(r, Q, sizeof(r[0]), cmpq); } void build(int cur, int x, int y) { int mid = (x + y) >> 1, ls = cur << 1, rs = (cur << 1) | 1; sum[cur] = 0; if(x == y) return ; build(ls, x, mid); build(rs, mid + 1, y); } int BS(int x) { int min = 0, max = X, mid; for(;;) { mid = (min + max) >> 1; if(mid == min) break; if(tx[mid] <= x) min = mid; else max = mid; } return mid; } void update(int cur) { sum[cur] = sum[cur << 1] + sum[(cur << 1) | 1]; } void refresh(int cur, int x, int y, int k, int c) { int mid = (x + y) >> 1, ls = cur << 1, rs = (cur << 1) | 1; if(x == y) { sum[cur] = c ? a[x] : 0; return ; } if(k <= mid) refresh(ls, x, mid, k, c); else refresh(rs, mid + 1, y, k, c); update(cur); } long long int query(int cur, int x, int y, int s, int t) { int mid = (x + y) >> 1, ls = cur << 1, rs = (cur << 1) | 1; if(x >= s && y <= t) return sum[cur]; if(mid >= t) return query(ls, x, mid, s, t); else if(mid + 1 <= s) return query(rs, mid + 1, y, s, t); else return query(ls, x, mid, s, t) + query(rs, mid + 1, y, s, t); } void solve() { int i, j, k; build(1, 1, N); for(i = 1, j = 0; i <= N; i ++) { k = BS(a[i]); if(where[k] != -1) refresh(1, 1, N, where[k], 0); where[k] = i; refresh(1, 1, N, i, 1); while(j < Q && question[r[j]].y == i) { question[r[j]].ans = query(1, 1, N, question[r[j]].x, question[r[j]].y); ++ j; } } for(i = 0; i < Q; i ++) printf("%I64d\n", question[i].ans); } int main() { int t; scanf("%d", &t); while(t --) { init(); solve(); } return 0; }