描述
给定一个数组A = [A1, A2, ... AN],请你找到异或和最大的一段连续子数组。
例如对于A = [1, 2, 3, 4, 5], 子数组[3, 4]的异或和最大,是7。
输入
第一行包含一个整数N。
第二行包含N个整数A1, A2, ... AN。
对于30%的数据,1 <= N <= 1000
对于100%的数据,1 <= N <= 100000 0 <= Ai <= 2147483647
输出
一个整数表示答案。
样例输入
5 1 2 3 4 5
样例输出
7
import java.util.Scanner;
public class Main {
public static class Node {
public Node[] nexts = new Node[2]; // 0,1
}
public static class NumTrie {
public Node head = new Node();
public void add(int num) {
Node cur = head;
for(int move = 31;move >= 0;move--) {
int path = ((num >> move) & 1);
cur.nexts[path] = (cur.nexts[path] == null ? new Node() : cur.nexts[path]);
cur = cur.nexts[path];
}
}
public int maxXor(int num) {
Node cur = head;
int res = 0;
for(int move = 31;move >= 0;move--) {
int path = (num >> move) & 1;
int best = (move == 31 ? path : (path ^ 1));
best = cur.nexts[best] != null ? best : (best ^ 1);
res |= (path ^ best) << move;
cur = cur.nexts[best];
}
return res;
}
}
public static int maxXorSubArray(int[] arr) {
if (arr == null || arr.length == 0)
return 0;
int max = Integer.MIN_VALUE;
int xor = 0;
NumTrie numTrie = new NumTrie();
numTrie.add(0);
for(int i = 0;i < arr.length;i++) {
xor ^= arr[i];
max = Math.max(max,numTrie.maxXor(xor));
numTrie.add(xor);
}
return max;
}
public static Scanner sc=new Scanner(System.in);
public static void main(String[] args) {
int n=sc.nextInt();
int []A=new int[n];
for(int i=0;i<n;i++) {
A[i] = sc.nextInt();
}
sc.close();
System.out.println(maxXorSubArray(A));
}
}