AcWing 143. 最大异或对 For Java
原题链接
简单
作者:
咕咕咕OwO
,
2020-09-03 21:45:35
,
所有人可见
,
阅读 765
使用对象
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(in.nextLine());
String[] line = in.nextLine().split(" ");
int ans = 0;
Trie trie = new Trie();
for (int i = 0; i < n; ++i) {
int a = Integer.parseInt(line[i]);
trie.insert(a);
int b = trie.query(a);
ans = Math.max(ans, a ^ b);
}
out.print(ans);
out.flush();
}
static class Trie {
Trie[] trie;
int num;
public Trie() {
trie = new Trie[2];
}
public void insert(int x) {
Trie root = this;
for (int i = 30; i >= 0; --i) {
int u = x >> i & 1;
if (root.trie[u] == null) root.trie[u] = new Trie();
root = root.trie[u];
}
root.num = x;
}
public int query(int x) {
Trie root = this;
for (int i = 30; i >= 0; --i) {
int u = x >> i & 1;
if (root.trie[u ^ 1] != null) root = root.trie[u ^ 1];
else if (root.trie[u] != null) root = root.trie[u];
else return root.num;
}
return root.num;
}
}
}
使用数组
import java.util.*;
import java.io.*;
public class Main {
static int[][] son;
static int idx;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
son = new int[31 * 100010][2];
int n = Integer.parseInt(in.nextLine());
String[] line = in.nextLine().split(" ");
int ans = 0;
for (int i = 0; i < n; ++i) {
int a = Integer.parseInt(line[i]);
insert(a);
int b = query(a);
ans = Math.max(ans, a ^ b);
}
out.print(ans);
out.flush();
}
private static void insert(int a) {
int p = 0;
for (int i = 30; i >= 0; i--) {
int u = a >> i & 1;
if (son[p][u] == 0) son[p][u] = ++idx;
p = son[p][u];
}
}
private static int query(int a) {
int p = 0, res = 0;
for (int i = 30; i >= 0; i--) {
int u = a >> i & 1;
if (son[p][u ^ 1] != 0) {
res = res * 2 + u ^ 1;
p = son[p][u ^ 1];
} else {
res = res * 2 + u;
p = son[p][u];
}
}
return res;
}
}
为什么不能用<<来实现*2的操作啊老哥
可以的 用
res <<= 1
可以代替乘2操作