题目:给定整数m以及n各数字A1,A2,..An,将数列A中所有元素两两异或,共能得到n(n-1)/2个结果,请求出这些结果中大于m的有多少个。
输入描述:第一行包含两个整数n,m.
第二行给出n个整数A1,A2,…,An。
数据范围
对于30%的数据,1 <= n, m <= 1000
对于100%的数据,1 <= n, m, Ai <= 10^5
输出描述:输出仅包括一行,即所求的答案
输入:
3 10
6 5 10
输出:2
一、如果使用暴力解大数据超时
二、使用Trie树,时间复杂度O(N)
使用数据结构
class Node{
Node[] next = new Node[2];
int count;
}
创建头结点head。
遍历数组a[n],这里的值给的都是正数且小于100000,所以从右边开始取17位即可,其余位都是0。从高位开始,如果a[i]的第j位为0,创建head.next[0]节点,更新节点中count的值
所有代码如下:
package 今日头条_异或.用字典序;
import java.util.Scanner;
class Node{
Node[] next = new Node[2];
int count;
}
public class Main {
public static long res = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
int n = scanner.nextInt();
int m = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
//建立字典序
Node head = BuildDictionary(a, m);
for (int i = 0; i < a.length; i++) {
QueryDictionary(head, a[i], m, 3);
}
System.out.println(res/2);
}
return;
}
public static Node BuildDictionary(int[] a, int m){
Node head = new Node();
for (int i = 0; i < a.length; i++) {
Node node = head;
for (int j = 3; j >= 0 ; --j) {
int tmp = (a[i]>>j)&1;
if (tmp == 1){
if (node.next[1] == null){
node.next[1] = new Node();
node.next[1].count = 1;
}
else {
++node.next[1].count;
}
node = node.next[1];
}
else {
if (node.next[0] == null) {
node.next[0] = new Node();
node.next[0].count = 1;
} else {
++node.next[0].count;
}
node = node.next[0];
}
}
}
return head;
}
public static void QueryDictionary(Node head, int a,int m, int index) {
if (index == -1){
return;
}
int tmp1 = (a>>index) &1;
int tmp2 = (m >> index) & 1;
if (tmp1 == 0 && tmp2 == 0) {
if (head.next[1] != null){
res += head.next[1].count;
}
if (head.next[0] != null){
QueryDictionary(head.next[0],a, m, index -1);
}
}
else if (tmp1 == 1 && tmp2 == 0){
if (head.next[0] != null){
res += head.next[0].count;
}
if (head.next[1] != null){
QueryDictionary(head.next[1], a, m, index-1);
}
}
else if (tmp1 == 0 && tmp2 == 1){
if (head.next[1] != null){
QueryDictionary(head.next[1], a, m, index-1);
}
}
else if (tmp1 == 1 && tmp2 == 1){
if (head.next[0] != null){
QueryDictionary(head.next[0],a, m, index -1);
}
}
}
}
本文介绍了一种利用Trie树解决特定异或问题的方法。针对给定的整数数组,通过构建Trie树来高效计算数组中所有两两元素异或结果大于指定阈值的数量。该方法的时间复杂度为O(N),适用于大数据集。
1307

被折叠的 条评论
为什么被折叠?



