After traveling from Stockholm and Uppsala , I must come on and train some more.
Today training is still Trie Tree , The Trie not only can save the words , also can save the numbers, so it can save anything we want. The problem today is about in an array , how to find two numbers that’s xor is the max.
Step I is to think about the violence , but it will Time Limit Exceeded
And the Problem:
在给定的N个整数A1,A2……AN中选出两个进行xor(异或)运算,得到的结果最大是多少?
输入格式
第一行输入一个整数N。
第二行输入N个整数A1~AN。
输出格式
输出一个整数表示答案。
数据范围
1≤N≤105,
0≤Ai<231
输入样例:
3
1 2 3
输出样例:
3
Method 1 : Violence
To use two for to travers the array , basic method:
import java.io.*;
import java.util.*;
public class Main{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static Scanner sn = new Scanner(System.in);
public static void main(String []srga) throws Exception{
int n = sn.nextInt();
int nums[] = new int[n];
for (int i = 0; i < n; i++ ) nums[i] = sn.nextInt();
int max = -999999;
for (int i = 0; i < n - 1; i++ )
for (int j = i + 1; j < n ; j++ )
if ((nums[i] ^ nums[j]) > max) max = nums[i] ^ nums[j];
System.out.println(max);
}
}
That will TLE.
Current Method : Trie
Using trie to save the every binary number, and to get the max xor, we need…
ok, give an example.
If we have 3, 4, 5, 6, 7. The binary is 011, 100, 101, 110, 111
such like 3, 011 : if we want to get the max xor, the best first number is 1,and second is 0 and last 0.
So the trie like a tree that has two leaves, which is 1 or 0.
The code :
import java.io.*;
import java.util.*;
public class Main{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 100010, M = 31 * 100000 + 10;
static int nums[] = new int[N];
static int n, son[][] = new int[M][2], idx;
public static void main(String []srga) throws Exception{
n = Integer.parseInt(br.readLine());
String input[] = br.readLine().split(" ");
for (int i = 0; i < n; i++ ) nums[i] = Integer.parseInt(input[i]);
int res = 0;
for (int i = 0; i < n; i++ ) {
insert(nums[i]);
int t = query(nums[i]);
res = Math.max(res, (t ^ nums[i]));
}
pw.println(res);
pw.flush();
}
public static void insert(int x) {
int p = 0;
for (int i = 30; i >= 0 ; i-- ) {
int u = x >> i & 1;
if (son[p][u] == 0) son[p][u] = ++idx;
p = son[p][u];
}
}
public static int query(int x) {
int p = 0;
int res = 0;
for (int i = 30; i >= 0 ; i-- ) {
int u = x >> i & 1;
if (son[p][u ^ 1] != 0) {
p = son[p][u ^ 1];
res = res * 2 + (u ^ 1);
}else {
p = son[p][u];
res = res * 2 + u;
}
}
return res;
}
}