🏯 🏯 🏯
求[l, r]区间内不重复的数的和。N个数,M次询问
(1)考虑维护出一个无重复元素的前缀,例如现在枚举到以 i 结尾的前缀,那么所有以 i 结尾的区间均可以直接查询出。
(2)维护前缀的过程中,我们记录下每个数字最后出现的位置,并将之前出现过的贡献清零(因为该元素越靠右的位置越有可能对之后的答案有贡献)
int n,w[MAXN];
ll c[MAXN],ans[MAXN];
void update(int x,int v){ while (x <= n) {c[x]+=v; x += (x & (-x)); }}
ll que(int x){ll sum = 0; while (x) { sum += c[x]; x -= (x & (-x)); }return sum;}
struct IN
{
int l,r,id;
}op[MAXN];
signed main()
{
fast;
int T;cin>>T;
while(T--)
{
cin>>n;
rep(i,n+1) c[i]=0;
rpp(i,n)
{
cin>>w[i];
update(i,w[i]);
}
int m;cin>>m;
rpp(i,m)
{
cin>>op[i].l>>op[i].r;
op[i].id=i;
}
sort(op+1,op+1+m,[](IN a,IN b){return a.r<b.r;});
map<int,int>mp;
int tag=1;//当前处理到哪个区间
rpp(i,n)
{
if(tag>m) break;
if(mp[w[i]]) update(mp[w[i]],-w[i]);
mp[w[i]]=i;
while(tag<=m&&i==op[tag].r)
{
ans[op[tag].id]=que(op[tag].r)-que(op[tag].l-1);
++tag;
}
}
rpp(i,m) cout<<ans[i]<<endl;
}
return 0;
}