1. 程式人生 > >codeforces 703D 樹狀陣列 + 離線處理 + 離散化

codeforces 703D 樹狀陣列 + 離線處理 + 離散化

題意:給你m個操作,每個操作求區間[l,r]中偶數個元素的異或值。

分析:根據異或的性質,偶數個的異或為0,所以我們考慮再一次元素本身,因此,偶數變成奇數,奇數變成偶數。

具體詳見程式碼:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 +20;
struct node
{
	int l,r,id;
bool operator < (const node & a)
{
	return r < a.r;
}
}q[maxn];
int n , A[maxn],B[maxn],sum[maxn],ans[maxn],Map[maxn];
struct BIT
{
	int bit[maxn];
	void add(int x,int v)
	{
		while(x<=n)
		{
			bit[x] ^= v;
			x += x&-x;
		}
	}
	int sum(int x)
	{
		int res = 0;
		while(x)
		{
			res ^= bit[x];
			x -= x&-x;
		}
		return res;
	}
}bit;
int main(void)
{
	cin>>n;
	for(int i = 1;i <= n;i++)
	{
		scanf("%d",&A[i]);
		sum[i] = sum[i-1] ^ A[i];
		B[i] = A[i];
	}
	sort(B + 1,B + n + 1);
	int  x = unique(B + 1,B + n + 1) - B - 1;
	for(int i = 1;i <= n; i ++)
	{
		A[i] = lower_bound(B + 1,B + x + 1,A[i]) - B;
	}
	int m,a,b,pos = 0;
	cin>>m;
	for(int i = 1;i <= m;i ++)
	{
		scanf("%d%d",&q[i].l,&q[i].r);
		q[i].id = i;
	} 
	sort(q+1,q+m+1);
	for(int i = 1;i <= m ; i ++)
	{
		while(pos < q[i].r)
		{
			pos++;
			if(Map[A[pos]]) bit.add(Map[A[pos]],B[A[pos]]);
			bit.add(pos,B[A[pos]]);
			Map[A[pos]] = pos;
		}
		ans[q[i].id] = sum[q[i].r] ^ sum[q[i].l-1] ^ bit.sum(q[i].r) ^ bit.sum(q[i].l-1);
	}
	for(int i = 1;i <= m; i++)
	{
		printf("%d\n",ans[i]);
	} 
}