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.
mr 9/3
如何消去之前重复的数字?只要记录下每个数字的前继即可。
代码
#include<iostream>
#include<cstdio>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<map>
using namespace std;
map<long long, long long> last;
long long n,q,T;
long long a[300010],tree[300010],ans[300010];
struct node
{
long long l,r,num;
}s[300010];
bool cp(node x,node y)
{
return x.r < y.r;
}
void update(long long x, long long num)
{
while(x <= n)
{
tree[x] += num;
x += x & -x;
}
}
long long add(int x)
{
long long sum = 0;
while(x > 0)
{
sum += tree[x];
x -= x & -x;
}
return sum;
}
int main()
{
freopen("turingtree.in","r",stdin);
freopen("turingtree.out","w",stdout);
scanf("%d",&T);
while(T--)
{
memset(ans,0,sizeof(ans));
memset(a,0,sizeof(a));
memset(tree,0,sizeof(tree));
last.clear();
scanf("%d",&n);
for(int i = 1; i <= n; i++)
scanf("%d",&a[i]);
scanf("%d",&q);
for(int i=1;i<=q;i++)
{
int x,y;
scanf("%d%d",&x,&y);
s[i].l = x;
s[i].r = y;
s[i].num = i;
}
sort(s+1,s+q+1,cp);
int left = 1;
for(int k = 1; k <= q; k++)
{
for(int i = left; i <= s[k].r; i++)
{
update(i, a[i]);
if(last[a[i]] > 0)
update(last[a[i]], -a[i]);
last[a[i]] = i;
}
left = s[k].r + 1;
ans[s[k].num] = add(s[k].r) -
add(s[k].l - 1);
}
for(int i=1;i<=q;i++)
{
printf("%lld\n",ans[i]);
}
}
fclose(stdin);
fclose(stdout);
return 0;
}