题目链接
After inventing Turing Tree, 3xian always felt boring when solving problems about intervals, because Turing Tree could easily have the solution. As well, wily 3xian made lots of new problems about intervals. So, today, this sick thing happens again…
Now given a sequence of N numbers A1, A2, …, AN and a number of Queries(i, j) (1≤i≤j≤N). For each Query(i, j), you are to caculate the sum of distinct values in the subsequence Ai, Ai+1, …, Aj.
Input
The first line is an integer T (1 ≤ T ≤ 10), indecating the number of testcases below.
For each case, the input format will be like this:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define ll long long
#define lowbit(x) (x&(-x))
#define MT(a,b) memset(a,b,sizeof(a))
const int maxn=1E6+5;
const int ONF=-0x3f3f3f3f;
const int INF=0x3f3f3f3f;
int num[maxn];
ll tree[maxn];
ll ans[maxn];
map<int,int>vis;
struct node
{
int first,second,i;
}p[maxn];
bool cmp(node a,node b)
{
return a.second<b.second;
}
void change(int l,int r,int ql,int qr,int val,int root)
{
if (l==ql&&r==qr){
tree[root]=val;
return;
}
int mid=(l+r)>>1;
if (qr<=mid) change(l,mid,ql,qr,val,root<<1);
else if (ql>mid) change(mid+1,r,ql,qr,val,root<<1|1);
else{
change(l,mid,ql,mid,val,root<<1);
change(mid+1,r,mid+1,qr,val,root<<1|1);
}
tree[root]=tree[root<<1]+tree[root<<1|1];
}
ll query(int l,int r,int ql,int qr,int root)
{
if (l==ql&&r==qr){
return tree[root];
}
int mid=(l+r)>>1;
if (qr<=mid) return query(l,mid,ql,qr,root<<1);
else if (ql>mid) return query(mid+1,r,ql,qr,root<<1|1);
else return query(l,mid,ql,mid,root<<1)+query(mid+1,r,mid+1,qr,root<<1|1);
}
int main ()
{
int t,n,m;
scanf ("%d",&t);while (t--) {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &num[i]);
}
scanf("%d", &m);
for (int i = 1; i <= m; i++) {
scanf("%d%d", &p[i].first, &p[i].second);
p[i].i=i;
}
sort(p + 1, p + 1 + m, cmp);
vis.clear();
MT(tree,0);
MT(ans,0);
int tot=1;
for (int i=1;i<=n;i++){
int tmp=vis[num[i]];
if (tmp==0){
change(1,n,i,i,num[i],1);
} else if (tmp!=0){
change(1,n,tmp,tmp,0,1);
change(1,n,i,i,num[i],1);
}
vis[num[i]]=i;
while (p[tot].second<=i&&tot<=m){
ans[p[tot].i]=query(1,n,p[tot].first,p[tot].second,1);
tot++;
}
}
for (int i=1;i<=m;i++){
printf("%lld\n",ans[i]);
}
}
return 0;
}