统计异或值在范围内的数对有多少(01字典树)
给你一个整数数组 nums (下标 从 0 开始 计数)以及两个整数:low 和 high ,请返回 漂亮数对 的数目。
漂亮数对 是一个形如 (i, j) 的数对,其中 0 <= i < j < nums.length 且 low <= (nums[i] XOR nums[j]) <= high 。
示例 1:
输入:nums = [1,4,2,7], low = 2, high = 6
输出:6
解释:所有漂亮数对 (i, j) 列出如下:
- (0, 1): nums[0] XOR nums[1] = 5
- (0, 2): nums[0] XOR nums[2] = 3
- (0, 3): nums[0] XOR nums[3] = 6
- (1, 2): nums[1] XOR nums[2] = 6
- (1, 3): nums[1] XOR nums[3] = 3
- (2, 3): nums[2] XOR nums[3] = 5
示例 2:
输入:nums = [9,8,4,2,1], low = 5, high = 14
输出:8
解释:所有漂亮数对 (i, j) 列出如下:
- (0, 2): nums[0] XOR nums[2] = 13
- (0, 3): nums[0] XOR nums[3] = 11
- (0, 4): nums[0] XOR nums[4] = 8
- (1, 2): nums[1] XOR nums[2] = 12
- (1, 3): nums[1] XOR nums[3] = 10
- (1, 4): nums[1] XOR nums[4] = 9
- (2, 3): nums[2] XOR nums[3] = 6
- (2, 4): nums[2] XOR nums[4] = 5
提示:
1 <= nums.length <= 2 * 1e4
1 <= nums[i] <= 2 * 1e4
1 <= low <= high <= 2 * 1e4
通过次数1,659提交次数4,276
这个题就是一个字典树的题:
const int maxn=1e5+100; int son[maxn][3],cnt[maxn],idx; class Solution { public: void insert(int x){ int p=0; for(int i=16;i>=0;i--){ int j=(x>>i)&1; if(!son[p][j]) son[p][j]=++idx; p=son[p][j]; cnt[p]++; } } int query(int x,int limit){ int res=0,p=0; for(int i=16;i>=0;i--){ int u=(x>>i)&1; int v=(limit>>i)&1; // 分情况讨论 // 如果u是1 v是1的话,那么这个结点的1儿子及下面的所有的结点都满足条件,然后尝试走0儿子 // 如果u是1 v是0的话,只能走1儿子 // 如果u是0 v是1的话,那么这个结点的0儿子及下面的所有的结点都满足条件,然后尝试走1儿子 // 如果u是0 v是0的话,那么只能走0儿子 if(u){ if(v){ res+=cnt[son[p][1]]; p=son[p][0]; } else{ p=son[p][1]; } } else{ if(v){ res+=cnt[son[p][0]]; p=son[p][1]; } else{ p=son[p][0]; } } if(!p) return res; // 无路可走,直接返回 } res+=cnt[p]; return res; } int countPairs(vector<int>& nums, int low, int high) { memset(son,0,sizeof(son)); memset(cnt,0,sizeof(cnt)); int ans=0; idx=0; for(auto x:nums){ ans+=(query(x,high)-query(x,low-1)); insert(x); } return ans; } };