P7502 「HMOI R1」不知道是啥的垃圾题
小蒟蒻来水一水题解。
题意
维护可重集三个操作:
- 插入一个数对
- 删一个数对
- 给一个数对 ,问集合里多少个数对 满足 。
思路
首先值得推导的就是第三条了,我们假设两个二进制数 和 ,显然只需要从高往低,逐个判断,找到第一个不同的位,谁是 谁大。
容易得出,若 ,
存在唯一的 ,
- 若 :
- 若 :
- 若 :随便。
那么把 和 等价换成题目的两个部分,则
- 若 :
- 若 :
我们的目标此刻为:求从高到低第一个不同位恰好是 的数对数量。
从以上推导(和显示算法标签)我们可以使用 Trie 来维护。
对每个数对 ,从最高位到最低位,在 Trie 树上记录 ,在每个节点上记录该节点这一位上 的四种组合各有多少个。
每个节点一个数组 表示经过 的数对中这一位对应 的数对个数,插入完之后这个数对就相当于存在了树里。
操作
插入
显然,
void update(int a, int b, int val) {
int u = 0; // 根
for (int i = 62; i >= 0; i--) {
int ai = (a>>i) & 1;
int bi = (b>>i) & 1;
cnt[u][ai][bi] += val;
int d = ai^bi; // 沿着它走完
if (!ch[u][d]) ch[u][d] = ++tot;
u = ch[u][d];
}
}查询
依旧枚举,对于当前的 ,我们需要的 刚刚已经推导好了是已知的,所以直接累加答案。
同时枚举要从最高节点向下枚举直到不满足我们推导的条件:
则若想要继续向下枚举,必须满足这个条件,那么计算 往下走,因为我们的建树,若沿着 有子节点,就证明可以继续匹配。若没有,说明没有数对能在这一位匹配上,后面更低的显然也不可能,故直接结束。
int query(int x, int y) {
int u = 0, ans = 0;
for (int i = 62; i >= 0; i--) {
int xi = (x>>i)&1;
int yi = (y>>i)&1;
// 所需的ai,bi
int ai = 1-xi;
int bi = yi;
ans += cnt[u][ai][bi];
int d = xi^yi;
// 若符合条件就可以往下接着走
if (!ch[u][d]) break;
u = ch[u][d];
}
return ans;
}那么这题也就顺利解决了,一定要开 long long。
code
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ull unsigned long long
#define rd read()
#define rdstr readstr()
#define rdch readchar()
#define enter putchar('\n')
#define fo(a,b,c) for(int a = (b); a <= (c); ++a)
#define of(a,b,c) for(int a = (b); a >= (c); --a)
#define pii pair<int,int>
#define pb push_back
#define endl '\n'
const int N = 2e7+7, M = 2e5+7, INF=0x3f3f3f3f;
inline int read() {
int x=0,f=1; char ch = getchar();
while (ch<'0' || ch>'9') {if (ch == '-')f=-1;ch=getchar();}
while (ch>='0' && ch<='9') {x=x*10+ch-'0';ch=getchar();}
return x*f;
}
inline string readstr() {
int ch = getchar(); string s;
while (ch != EOF && ch <= ' ') ch=getchar();
while (ch != EOF && ch > ' ') {s.push_back(ch); ch=getchar();}
return s;
}
inline char readchar() {
int ch = getchar();
while (ch != EOF && ch <= ' ') ch = getchar();
return ch;
}
int m;
int cnt[N][2][2], ch[N][2], tot;
void Input() {
m = rd;
}
void update(int a, int b, int val) {
int u = 0;
for (int i = 62; i >= 0; i--) {
int ai = (a>>i) & 1;
int bi = (b>>i) & 1;
cnt[u][ai][bi] += val;
int d = ai^bi;
if (!ch[u][d]) ch[u][d] = ++tot;
u = ch[u][d];
}
}
int query(int x, int y) {
int u = 0, ans = 0;
for (int i = 62; i >= 0; i--) {
int xi = (x>>i)&1;
int yi = (y>>i)&1;
int ai = 1-xi;
int bi = yi;
ans += cnt[u][ai][bi];
int d = xi^yi;
if (!ch[u][d]) break;
u = ch[u][d];
}
return ans;
}
signed main() {
Input();
while (m--) {
int op=rd, x=rd, y=rd;
if (op == 1) update(x, y, 1);
else if (op == 2) update(x, y, -1);
else {
int ans = query(x, y);
printf("%lld\n", ans);
}
}
return 0;
}