2.最大异或对
题意:从一个序列中选出异或(XOR)结果最大的一对数,输出最大的异或值
暴力可过 要注意到今天学的是 字典树 ,那要如何写呢?
给出例子10 13 12 3
把他们拆成二进制
| 原数 | 拆的二进制 |
|---|---|
然后把他们放到字典树上面
好吧其实我没看出什么为了让异或值尽可能大,我们要让高位的bit尽量不同好吧我其实画反了所以要贪心
#include<bits/stdc++.h>
using namespace std;
const int N=1e5;
int node[N*32][2];
int a[N];
int tot=0;
void insert(int val){
int u=0;
for(int k=30;k>=0;k--){
int c=(val>>k)&1;
if(node[u][c]==0)
node[u][c]=++tot;
u=node[u][c];
}
return;
}
int query(int val){
int u=0;
int ans=0;
for(int k=30;k>=0;k--){
int c=(val>>k)&1;
if(node[u][c^1]){
u=node[u][c^1];
ans+=(1<<k);
}
else{
u=node[u][c];
}
}
return ans;
}
int main(){
ios::sync_with_stdio(0),cin.tie(nullptr);
int t;
int n;
cin>>n;
int mmax=0;
for(int i=1;i<=n;i++){
int s;
cin>>s;
insert(s);
mmax=max(mmax,query(s));
}
cout<<mmax;
return 0;
}抑或路径
因为树上到的路径等同于,而异或中异或两次正好抵消了
于是问题转化为给定个值,求最大异或值
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int node[N*32][2];
int a[N];
int dep[N];
int tot=0;
struct P{int v,w;};
vector<P>g[N];
int mmax=0;
void dfs(int u,int ans,int fa){
mmax=max(mmax,ans);
for(auto v:g[u]){
if(fa==v.v)continue;
dep[v.v]=dep[u]^v.w;
dfs(v.v,ans^v.w,u);
}
}
void insert(int val){
int u=0;
for(int k=30;k>=0;k--){
int c=(val>>k)&1;
if(node[u][c]==0)
node[u][c]=++tot;
u=node[u][c];
}
return;
}
int query(int val){
int u=0;
int ans=0;
for(int k=30;k>=0;k--){
int c=(val>>k)&1;
if(node[u][c^1]){
u=node[u][c^1];
ans+=(1<<k);
}
else{
u=node[u][c];
}
}
return ans;
}
int main(){
ios::sync_with_stdio(0),cin.tie(nullptr);
int t;
int n;
cin>>n;
int mmax=0;
for(int i=1;i<n;i++){
int u,v,w;
cin>>u>>v>>w;
g[u].push_back({v,w});
g[v].push_back({u,w});
}
dfs(1,0,0);
for(int i=1;i<=n;i++){
insert(dep[i]);
mmax=max(mmax,query(dep[i]));
}
cout<<mmax;
return 0;
}3
首先,意为
同时还要避免自己和自己比
按输入顺序依次处理每个字符串,查询它与之前所有字符串的 LCP 之和,再把它插入 字典树。
#include<bits/stdc++.h>
using namespace std;
const int N=3e5+7;
int node[N][65];
int cnt[N];
int vis[N];
int tot=0;
int getas(char c){
if(c>='a' and c<='z')return c-'a';
if(c>='A' and c<='Z')return c-'A'+26;
return c-'0'+52;
}
void insert(string s){
int u=0;
for(int i=0;i<s.size();i++){
int c=getas(s[i]);
if(node[u][c]==0){
++tot;
node[u][c]=tot;
}
u=node[u][c];
cnt[u]++;
}
return;
}
int query(string s){
int u=0;int ans=0;
for(int i=0;i<s.size();i++){
int c=getas(s[i]);
if(node[u][c]==0){
return ans;
}
u=node[u][c];
ans+=cnt[u];
}
return ans;
}
int main(){
ios::sync_with_stdio(0),cin.tie(nullptr);
int n;
cin>>n;
int ans=0;
for(int i=1;i<=n;i++){
string s;
cin>>s;
ans+=query(s);
insert(s);
}
// for(auto i:p)ans+=query(i);
cout<<ans;
return 0;
}