Problem Description
Mery has a beautiful necklace. The necklace is made up of N magic balls. Each ball has a beautiful value. The balls with the same beautiful value look the same, so if two or more balls have the same beautiful value, we just count it once. We define the beautiful value of some interval [x,y] as F(x,y). F(x,y) is calculated as the sum of the beautiful value from the xth ball to the yth ball and the same value is ONLY COUNTED ONCE. For example, if the necklace is 1 1 1 2 3 1, we have F(1,3)=1, F(2,4)=3, F(2,6)=6.
Now Mery thinks the necklace is too long. She plans to take some continuous part of the necklace to build a new one. She wants to know each of the beautiful value of M continuous parts of the necklace. She will give you M intervals [L,R] (1<=L<=R<=N) and you must tell her F(L,R) of them.
Now Mery thinks the necklace is too long. She plans to take some continuous part of the necklace to build a new one. She wants to know each of the beautiful value of M continuous parts of the necklace. She will give you M intervals [L,R] (1<=L<=R<=N) and you must tell her F(L,R) of them.
Input
The first line is T(T<=10), representing the number of test cases. For each case, the first line is a number N,1 <=N <=50000, indicating the number of the magic balls. The second line contains N non-negative integer numbers not greater 1000000, representing the beautiful value of the N balls. The third line has a number M, 1 <=M <=200000, meaning the nunber of the queries. Each of the next M lines contains L and R, the query.
Output
For each query, output a line contains an integer number, representing the result of the query.
Sample Input
2 6 1 2 3 4 3 5 3 1 2 3 5 2 6 6 1 1 1 2 3 5 3 1 1 2 4 3 5
Sample Output
3 7 14 1 3 6
题目大概+思路:
求不重合数的问题,不过不需要离散化,数据小。
要把区间存起来,按照右端点排序。进行预处理。
然后从第一个数开始循环,把数放到树状数组里,如果数组中存在了,就再减去。每到一个右端点,就把和存到ans里。最后输出。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int n;
int b[50010];
long long c[50010];
long long ans[200010];
int vis[1099999];
struct poin
{
int l,r,id;
}a[200010];
bool cmp(const poin a,const poin b)
{
return a.r<b.r;
}
int lowbit(int x)
{
return x&(-x);
}
int add(int x,int v)
{
while(x<=50001)
{
c[x]+=v;
x=x+lowbit(x);
}
}
long long sum(int x)
{
long long su=0;
while(x>0)
{
su+=c[x];
x-=lowbit(x);
}
return su;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{ memset(c,0,sizeof(c));
memset(vis,0,sizeof(vis));
memset(ans,0,sizeof(ans));
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&b[i]);
}
int m=0;
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
int q,w;
scanf("%d%d",&q,&w);
a[i].l=q;a[i].r=w;a[i].id=i;
}
sort(a+1,a+m+1,cmp);
int j=1;
for(int i=1;i<=m;i++)
{
for(;j<=a[i].r;j++)
{
if(vis[b[j]])add(vis[b[j]],-b[j]);
vis[b[j]]=j;
add(j,b[j]);
}
ans[a[i].id]=sum(a[i].r)-sum(a[i].l-1);
}
for(int i=1;i<=m;i++)
{
printf("%I64d\n",ans[i]);
}
}
return 0;
}