HDU6955 2021多校 Xor sum(字典树+前缀和异或)

link

思路:

将序列转化为前缀和的异或数组,问题就转化成了寻找两个数使得异或值大于等于(k)并且距离最小。
考虑用(01)字典树维护,枚举一遍右端点,求他之前的所有数与他的异或值的最大值,如果(>=k)的话就尝试更新答案。然后将该端点加入字典树。

代码:


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read()
{
    ll 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 * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

inline void out(ll x){
	if (x < 0) x = ~x + 1, putchar('-');
	if (x > 9) out(x / 10);
	putchar(x % 10 + '0');
}

inline void write(ll x){
	if (x < 0) x = ~x + 1, putchar('-');
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
	puts("");
}

#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)
ll ksm(ll a, ll b, ll p)
{
    ll res = 1;
    while(b)
    {
        if(b & 1)res = res * a % p;
        a = a * a % p;
        b >>= 1;
    }
    return res;
}
const int inf = 0x3f3f3f3f;
#define PI acos(-1)
const int maxn=100000+100;

int n,k,a[maxn],tr[maxn*31][2],val[maxn*31],tot;

void insert(int x,int idx){
	int p=0;
	for(int i=30;i>=0;i--){
		int u=x>>i&1;
		if(!tr[p][u]) tr[p][u]=++tot;
		p=tr[p][u];
	}
	val[p]=idx;
}

int find(int x){
	int p=0;
	for(int i=30;i>=0;i--){
		int u=x>>i&1;
		if(tr[p][!u]) p=tr[p][!u];
		else p=tr[p][u];
		if(!p) return -1;
	}
	return val[p];
}

int main(){
	int _=read;
	while(_--){
		for(int i=0;i<=tot;i++) 
			tr[i][0]=tr[i][1]=0,val[i]=0;
		tot=0;
		n=read,k=read;
		a[0]=0;
		rep(i,1,n) a[i]=a[i-1]^read;
		int l=-1,r=-1,len=inf;
		for(int i=1;i<=n;i++){
			int tmp=find(a[i]);
			if((a[tmp]^a[i])>=k){
				if(len>i-tmp){
					len=i-tmp;
					l=tmp+1,r=i;
				}
				else if(len==i-tmp){
					l=tmp+1,r=i;
				}
			}
			insert(a[i],i);
		}
		if(len==inf) puts("-1");
		else printf("%d %d
",l,r);
	}
	return 0;
} 












原文地址:https://www.cnblogs.com/OvOq/p/15046094.html