题意:有T(1<=T<=10)组测试数据,每组数据有N(1<=N<=30000)个数。接下来有Q个查询,表示查询区间[l,r]之间的数的和,但是出现多次的值,只能加进和里一次。
可以用离线的方法,方法如我之前关于Codeforces Round #136 (Div. 2) D. Little Elephant and Array的解题报告里介绍的两种方法没有什么太大的区别。
另外hdu 3874 Necklace只是变化了数据范围,其他的都一样。
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <map> #include <algorithm> using namespace std; #define LL(x) (x<<1) #define RR(x) (x<<1|1) #define MID(a,b) (a+((b-a)>>1)) const int N=50005; typedef long long LL; struct Query { int st,ed,ind; Query(){} Query(int a,int b,int c){st=a;ed=b;ind=c;} bool operator<(const Query&b)const { return ed<b.ed; } }; struct node { int lft,rht; LL sum; int mid(){return MID(lft,rht);} }; int y[N],n,m,sca; LL res[200005]; bool flag[N]; int st[N],ed[N]; vector<Query> q; map<int,int> H; struct Segtree { node tree[N*4]; void down(int ind) { if(tree[ind].sum) { tree[LL(ind)].sum+=tree[ind].sum; tree[RR(ind)].sum+=tree[ind].sum; tree[ind].sum=0; } } void build(int lft,int rht,int ind) { tree[ind].lft=lft; tree[ind].rht=rht; tree[ind].sum=0; if(lft!=rht) { int mid=tree[ind].mid(); build(lft,mid,LL(ind)); build(mid+1,rht,RR(ind)); } } void updata(int st,int ed,int ind,int valu) { int lft=tree[ind].lft,rht=tree[ind].rht; if(st<=lft&&rht<=ed) tree[ind].sum+=valu; else { down(ind); int mid=tree[ind].mid(); if(st<=mid) updata(st,ed,LL(ind),valu); if(ed> mid) updata(st,ed,RR(ind),valu); } } LL query(int pos,int ind) { if(tree[ind].lft==tree[ind].rht) return tree[ind].sum; else { down(ind); int mid=tree[ind].mid(); if(pos<=mid) return query(pos,LL(ind)); else return query(pos,RR(ind)); } } }seg; int main() { int t; scanf("%d",&t); while(t--) { sca=0; q.clear(); H.clear(); memset(flag,0,sizeof(flag)); scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&y[i]); if(H.find(y[i])==H.end()) H.insert(make_pair(y[i],sca++)); } seg.build(1,n,1); scanf("%d",&m); for(int i=0;i<m;i++) { int a,b; scanf("%d%d",&a,&b); q.push_back(Query(a,b,i)); } sort(q.begin(),q.end()); int ind=0; for(int i=1;i<=n;i++) { int valu=H[y[i]]; if(flag[valu]==0) { seg.updata(1,i,1,y[i]); st[valu]=1; ed[valu]=i; flag[valu]=1; } else { st[valu]=ed[valu]+1; ed[valu]=i; seg.updata(st[valu],ed[valu],1,y[i]); } while(q[ind].ed==i&&ind<m) { res[q[ind].ind]=seg.query(q[ind].st,1); ind++; } } for(int i=0;i<m;i++) printf("%I64d\n",res[i]); } return 0; }