题目:
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).
Output
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
大意:查询静态区间 i - j 内不同数之和。
先讲离线
这题算出值后统一输出,将m个查询及其下标保存,按查询的右端点排序。树范围0到n-1。之前没出现过的,当前第 i 位加a[ i ]。出现过的,之前出现的位置 变为0,当前第 i 位加a[ i ]。每次算出的查询数再按照原来顺序输出。
就是简单的单点修改+数据离散化
#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=3e4+7;
const int mod=1e9+7;
#define ls i<<1
#define rs i<<1|1
#define lson ls,l,mid
#define rson rs,mid+1,r
#define ln (mid-l+1)
#define rn (r-mid)
int read(){
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+ch-'0';
ch=getchar();
}
return x*f;
}
struct choice{
int x,y,id;
}sz[maxn<<2];
int T,n,m,a[maxn],b[maxn],cnt,k,pos;
ll num[maxn<<2],sum[maxn<<2];
int f[maxn];
bool cmp(choice p,choice q){ return p.y<q.y; }
void pushup(int i){ num[i]=num[ls]+num[rs]; }
void update(int i,int l,int r,int x,int c){
if(l==r){
num[i]=c;
return;
}
int mid=l+r>>1;
if(x<=mid) update(lson,x,c);
else update(rson,x,c);
pushup(i);
}
ll query(int i,int l,int r,int x,int y){
if(x<=l&&r<=y) return num[i];
int mid=l+r>>1;
ll ans=0;
if(x<=mid) ans+=query(lson,x,y);
if(y>mid) ans+=query(rson,x,y);
return ans;
}
int main(){
T=read();
while(T--){
n=read(); pos=cnt=0;
memset(f,-1,sizeof(f)); memset(num,0,sizeof(num));
for(int i=0;i<n;i++) b[i]=a[i]=read();
sort(b,b+n); k=unique(b,b+n)-b;
m=read();
for(int i=0;i<m;i++){
sz[i].x=read()-1; sz[i].y=read()-1;
sz[i].id=i;
}
sort(sz,sz+m,cmp);
for(int i=0;i<m;i++){
while(pos<=sz[i].y&&pos<n){
int id=lower_bound(b,b+k,a[pos])-b;
if(f[id]!=-1) update(1,0,n-1,f[id],0);
f[id]=pos;
update(1,0,n-1,pos,a[pos]);
pos++;
}
sum[sz[i].id]=query(1,0,n-1,sz[i].x,sz[i].y);
}
for(int i=0;i<m;i++) printf("%lld\n",sum[i]);
}
}
/*
2
3
1 1 4
2
1 2
2 3
5
1 1 2 1 3
3
1 5
2 4
3 5
1
5
6
3
6
*/
当然,如果没想到离线处理,可以用可持久化树。
待更新