01trie
算法概述
问题引入
算法分析
模板code
// 01tries 模板, 求ai^aj最大值
#include "bits/stdc++.h"
using namespace std;
using ll = long long;
const ll MAXN = 210000;
ll a[MAXN], ch[MAXN][2], val[MAXN], n, ans, tot;void insert(ll n)
{int now = 0;for (int j = 31; j >= 0; j--){int pos = ((n >> j) & 1);if (!ch[now][pos]) ch[now][pos] = tot++;now = ch[now][pos];}val[now] = n;return;
}ll check(ll n)// check不是在挑选与使得a^b最大的b,而是直接挑选max(a ^ b);
{int now = 0;for (int j = 31; j >= 0; j--)//注意从高到低枚举{int pos = ((n >> j) & 1);if (ch[now][pos ^ 1]) now = ch[now][pos ^ 1];else now = ch[now][pos];}return val[now];
}int main()
{cin >> n; cin >> n;for (int i = 1; i <= n; i++){cin >> a[i]; insert(a[i]);}for (int i = 1; i <= n; i++){ans = max(ans, check(a[i]));}cout << ans << endl;return 0;
}
例题
题解:
key:异或的性质
(n1^n2^n3^...^nn)^(m1^m2^m3^...^mn) =(prefix_roots^n1^n2^n3^...^nn)^(prefix_roots^m1^m2^m3^...^mn)
prefix_roots是两个节点的公共路径,ni ^ mj 是两点间的路径
只需要dfs处理出各节点到root的路径的异或,就可以转化为”问题引入"中的例题