#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
const int maxn=50010;
//离线算法
int n;
__int64 c[maxn];
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int val)
{
for(int i=x;i<=n;i+=lowbit(i))
{
c[i]+=val;
}
}
__int64 getsum(int x)
{
__int64 cnt=0;
for(int i=x;i>=1;i-=lowbit(i))
{
cnt+=c[i];
}
return cnt;
}
int a[maxn];
map<int,int> hash;
struct Node
{
int l,r;
int idx;
};
Node qu[maxn*4];
__int64 ans[maxn*4];
bool cmp(Node h,Node k)
{
return h.r<k.r;
}
int main()
{
int ci;scanf("%d",&ci);
while(ci--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
int q;
scanf("%d",&q);
for(int i=0;i<q;i++)
{
int l,r;
scanf("%d%d",&l,&r);
if(l>r) swap(l,r);
qu[i].l=l,qu[i].r=r;
qu[i].idx=i;
}
sort(qu,qu+q,cmp); //以r排序
for(int i=1;i<=n;i++)
c[i]=0; //树状数组
hash.clear();
int rr=1;
for(int i=0;i<q;i++)
{
while(rr<=qu[i].r)
{
if(hash[a[rr]]!=0)
{
update(hash[a[rr]],-a[rr]);
}
hash[a[rr]]=rr;
update(rr,a[rr]);
rr++;
}
ans[qu[i].idx]=getsum(qu[i].r)-getsum(qu[i].l-1);
}
for(int i=0;i<q;i++)
printf("%I64d\n",ans[i]);
}
return 0;
}
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
const int maxn=50010;
//离线算法
int n;
__int64 c[maxn];
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int val)
{
for(int i=x;i<=n;i+=lowbit(i))
{
c[i]+=val;
}
}
__int64 getsum(int x)
{
__int64 cnt=0;
for(int i=x;i>=1;i-=lowbit(i))
{
cnt+=c[i];
}
return cnt;
}
int a[maxn];
map<int,int> hash;
struct Node
{
int l,r;
int idx;
};
Node qu[maxn*4];
__int64 ans[maxn*4];
bool cmp(Node h,Node k)
{
return h.r<k.r;
}
int main()
{
int ci;scanf("%d",&ci);
while(ci--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
int q;
scanf("%d",&q);
for(int i=0;i<q;i++)
{
int l,r;
scanf("%d%d",&l,&r);
if(l>r) swap(l,r);
qu[i].l=l,qu[i].r=r;
qu[i].idx=i;
}
sort(qu,qu+q,cmp); //以r排序
for(int i=1;i<=n;i++)
c[i]=0; //树状数组
hash.clear();
int rr=1;
for(int i=0;i<q;i++)
{
while(rr<=qu[i].r)
{
if(hash[a[rr]]!=0)
{
update(hash[a[rr]],-a[rr]);
}
hash[a[rr]]=rr;
update(rr,a[rr]);
rr++;
}
ans[qu[i].idx]=getsum(qu[i].r)-getsum(qu[i].l-1);
}
for(int i=0;i<q;i++)
printf("%I64d\n",ans[i]);
}
return 0;
}
本文介绍了一种利用离线算法和树状数组解决排序区间查询问题的方法,通过预处理和动态更新,实现高效的数据查询和统计。
546

被折叠的 条评论
为什么被折叠?



