Turing Tree
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8457 Accepted Submission(s): 3111
Problem Description
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:
- Line 1: N (1 ≤ N ≤ 30,000).
- Line 2: N integers A1, A2, …, AN (0 ≤ Ai ≤ 1,000,000,000).
- Line 3: Q (1 ≤ Q ≤ 100,000), the number of Queries.
- Next Q lines: each line contains 2 integers i, j representing a Query (1 ≤ i ≤ j ≤ N).
Ouput
For each Query, print the sum of distinct values of the specified subsequence in one line.
Sample Input
2
3
1 1 4
2
1 2
2 3
5
1 1 2 1 3
3
1 5
2 4
3 5
Sample Output
1
5
6
3
6
求区间不同数字的和;
先将数据离散化,离线操作就是要先将问题储存起来,根据一定的顺序解答来降低复杂度;
这题就将问题储存起来后按右边界排序,之后从左到右逐个点的建立线段树,同时标记一下这个值是否出现过和位置,如果之前出现过,就把之前出现的点清零再在当前点插值,同时看当前的点有没有刚刚排好序的问题的右边界,如果遇到了,就对这个问题求和,因为之前的数已经去过重并且都是最靠右的,所以对这个区间求和的答案是正确的;然后继续更新下一个节点…
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn=30010;
ll num[maxn<<2];
void update(int pos,int val,int le,int ri,int node){
if(le==ri){
num[node]=val;
return ;
}
int t=(le+ri)>>1;
if(pos<=t) update(pos,val,le,t,node<<1);
else update(pos,val,t+1,ri,node<<1|1);
num[node]=num[node<<1]+num[node<<1|1];
}
ll query(int l,int r,int le,int ri,int node){
if(l<=le&&ri<=r) return num[node];
int t=(le+ri)>>1;
ll ans=0;
if(l<=t) ans+=query(l,r,le,t,node<<1);
if(r>t) ans+=query(l,r,t+1,ri,node<<1|1);
return ans;
}
struct edge{
int num2,num1,pos;
}B[maxn*4];
bool cmp(edge a,edge b){
return a.num2<b.num2;
}
int vis[maxn],pre[maxn],A[maxn];
ll ans[maxn*4];
int main()
{
int T,n,m,a,b;
map<int,int> ma;
scanf("%d",&T);
while(T--){
ma.clear();
int no=0;
scanf("%d",&n);
memset(vis,0,sizeof(vis));
memset(ans,0,sizeof(ans));
memset(pre,-1,sizeof(pre));
memset(num,0,sizeof(num));
for(int i=0;i<n;i++)
{
scanf("%d",&A[i]);
if(!ma[A[i]])ma[A[i]]=no++;
}
cin>>m;
for(int i=0;i<m;i++)
scanf("%d%d",&B[i].num1,&B[i].num2),B[i].pos=i;
sort(B,B+m,cmp);对问题排序
for(int i=0,j=0;i<n;i++)
{
if(vis[ma[A[i]]])//左面出现过
{
update(pre[ma[A[i]]],0,1,n,1);
update(i+1,A[i],1,n,1);//i+1就是线段树中的位置
pre[ma[A[i]]]=i+1;
}else
{
vis[ma[A[i]]]=1;
update(i+1,A[i],1,n,1);
pre[ma[A[i]]]=i+1;
}
for(;j<m;j++)//对j个询问作答
{
if(i+1!=B[j].num2)break;
ans[B[j].pos]=query(B[j].num1,B[j].num2,1,n,1);
}
}
for(int i=0;i<m;i++) printf("%I64d\n",ans[i]);
}
}