HDU6955 2021多校 Xor sum(字典樹+字首和異或)
阿新 • • 發佈:2021-07-22
思路:
將序列轉化為字首和的異或陣列,問題就轉化成了尋找兩個數使得異或值大於等於\(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\n",l,r); } return 0; }