Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2083 Accepted Submission(s): 747
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N=51000; const int M=210000; struct node{ int l,r; int id; }q[M]; int n,m,val[N],pre[N],loc[1100000]; long long arr[N],res[M]; int lowbit(int x){ return x&(-x); } void update(int i,int x){ while(i<=n){ arr[i]+=x; i+=lowbit(i); } } long long Sum(int i){ long long ans=0; while(i>0){ ans+=arr[i]; i-=lowbit(i); } return ans; } bool cmp(node a,node b){ return a.r<b.r; } int main(){ //freopen("input.txt","r",stdin); int t; scanf("%d",&t); while(t--){ memset(arr,0,sizeof(arr)); memset(loc,-1,sizeof(loc)); scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&val[i]); pre[i]=loc[val[i]]; loc[val[i]]=i; update(i,val[i]); } scanf("%d",&m); for(int i=1;i<=m;i++){ scanf("%d%d",&q[i].l,&q[i].r); q[i].id=i; } sort(q+1,q+1+m,cmp); int r=0; for(int i=1;i<=m;i++){ for(int j=r+1;j<=q[i].r;j++) if(pre[j]!=-1) update(pre[j],-val[j]); r=q[i].r; res[q[i].id]=Sum(q[i].r)-Sum(q[i].l-1); } for(int i=1;i<=m;i++) printf("%I64d\n",res[i]); } return 0; }
线段树:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<map> using namespace std; const int N=51000; //#define L(rt) (rt<<1) //#define R(rt) (rt<<1|1) #define lson l,mid,rt<<1 #define rson mid+1,r,rt<<1|1 struct Tree{ int l,r; int id; }q[N<<2]; map<int,int> mp; int n,m,a[N]; long long sum[N<<2],res[N<<2]; void PushUp(int rt){ sum[rt]=sum[rt<<1]+sum[rt<<1|1]; } void update(int id,int val,int l,int r,int rt){ if(l==r){ sum[rt]+=val; return ; } int mid=(l+r)>>1; if(id<=mid) update(id,val,lson); else update(id,val,rson); PushUp(rt); } long long query(int L,int R,int l,int r,int rt){ if(L<=l && R>=r) return sum[rt]; int mid=(l+r)>>1; long long ans=0; if(L<=mid) ans+=query(L,R,lson); if(R>mid) ans+=query(L,R,rson); return ans; } int cmp(Tree a,Tree b){ return a.r<b.r; } int main(){ //freopen("input.txt","r",stdin); int t; scanf("%d",&t); while(t--){ scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); scanf("%d",&m); for(int i=1;i<=m;i++){ scanf("%d%d",&q[i].l,&q[i].r); q[i].id=i; } sort(q+1,q+1+m,cmp); mp.clear(); memset(sum,0,sizeof(sum)); int r=0; for(int i=1;i<=m;i++){ for(int j=r+1;j<=q[i].r;j++){ if(mp[a[j]]) update(mp[a[j]],-a[j],1,n,1); update(j,a[j],1,n,1); mp[a[j]]=j; r=q[i].r; } res[q[i].id]=query(q[i].l,q[i].r,1,n,1); } for(int i=1;i<=m;i++) printf("%I64d\n",res[i]); } return 0; }