HDU 3333 | Codeforces 703D 树状数组、离散化

时间:2021-03-20 09:18:46

HDU 3333:http://acm.hdu.edu.cn/showproblem.php?pid=3333

这两个题是类似的,都是离线处理查询,对每次查询的区间的右端点进行排序。这里我们需要离散化处理一下,标记一下前面是否出现过这个值,然后不断更新last数组(该数组保存的是每个数最后一次出现的位置)。最后用树状数组维护。

 #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = ;
const int maxq = ;
struct node{
int l,r,index;
};
node query[maxq];
ll sum[maxn],ans[maxq];
ll a[maxn],b[maxn],last[maxn];
int n;
bool cmp(node a,node b){
return a.r < b.r;
}
ll getsum(int i){
ll s = ;
while(i > ){
s += sum[i];
i -= i&(-i);
}
return s;
}
void add(int i,ll x){
while(i <= n){
sum[i] += x;
i += i&(-i);
}
}
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(int i = ;i<=n;i++){
scanf("%I64d",&a[i]);
b[i] = a[i];//离散化用
}
sort(b+,b++n);//排序,以每个数的下标标记
int q;
scanf("%d",&q);
for(int i = ;i<=q;i++){
scanf("%d%d",&query[i].l,&query[i].r);
query[i].index = i;
}
sort(query+,query++q,cmp);
memset(sum,,sizeof(sum));
memset(last,,sizeof(last));
int cnt = ;//每个查询的下标
for(int i = ;i<=n;i++){
int index = lower_bound(b+,b++n,a[i])-b-;//找到该数对应的下标
if(last[index])//判断该数是否出现过,有的话减去
add(last[index],-a[i]);
add(i,a[i]);
last[index] = i;
while(query[cnt].r==i && cnt<=q){
ans[query[cnt].index] = getsum(query[cnt].r)-getsum(query[cnt].l-);
cnt++;
}
}
for(int i = ;i<=q;i++)
printf("%I64d\n",ans[i]);
}
return ;
}

Codeforces 703D:http://codeforces.com/contest/703/problem/D

这道题需要多思考的一步是,要求的区间内出现偶数次的数的异或和,等于这个区间内所有数字的异或和异或这个区间内不同数字的异或和,以1、2、1、3、3、2、3举例,结果就是(1^2^1^3^3^2^3)^(1^2^3),原理就是出现偶数次的数异或它自己等于它本身,出现奇数次的数异或它自己为0。对于区间的异或和,我们可以用数组很方便的求出,不同数字的异或和,只需要对上题进行一下改造就好了。

 #include<bits/stdc++.h>
using namespace std;
typedef long long ll; const int maxn = ;
struct node{
int l,r,index;
};
node query[maxn];
ll sum[maxn],a[maxn],b[maxn],c[maxn],last[maxn],ans[maxn];
int n;
bool cmp(node a,node b){
return a.r < b.r;
}
ll getsum(int i){
ll s = ;
while(i > ){
s ^= sum[i];//注意
i -= i&(-i);
}
return s;
}
void add(int i,ll x){
while(i <= n){
sum[i] ^= x;//注意
i += i&(-i);
}
}
int main(){
scanf("%d",&n);
for(int i = ;i<=n;i++){
scanf("%I64d",&a[i]);
c[i] = a[i]^c[i-];//求前缀异或和
b[i] = a[i];
}
sort(b+,b++n);
int q;
scanf("%d",&q);
for(int i = ;i<=q;i++){
scanf("%d%d",&query[i].l,&query[i].r);
query[i].index = i;
}
sort(query+,query++q,cmp);
int cnt = ;
for(int i = ;i<=n;i++){
int index = lower_bound(b+,b++n,a[i])-b-;
if(last[index])
add(last[index],a[i]);
last[index] = i;
add(i,a[i]);
while(query[cnt].r==i && cnt<=q){
ans[query[cnt].index] = (c[query[cnt].r]^c[query[cnt].l-])^(getsum(query[cnt].r)^getsum(query[cnt].l-));//注意
cnt++;
}
}
for(int i = ;i<=q;i++)
printf("%I64d\n",ans[i]);
return ;
}