P14947 Minpopcount 题解
题意
维护一个集合 ,初始为空。支持两种操作:
- 插入一个 内的整数 (保证 不在 中)
- 查询对于给定的 的值(保证查询时 非空)
其中 。
思路
观察
我们需要快速回答查询:对于给定的 ,找到集合 中与其汉明距离 最小的元素。
由于 ,整个值域 最多只有 个元素。我们可以考虑预处理所有值到集合 的最小汉明距离。
BFS
- 状态定义:设 表示数字 到集合 的最小汉明距离(即 )。
- 插入操作:当插入一个新元素 时:
- 如果 (已是最小值),则跳过;
- 否则,设置 ,并以 为起点进行 BFS。
- BFS 过程中,对于当前点 ,检查所有与 汉明距离为 的点 ;
- 如果 ,则更新 ,并将 加入队列。
- 查询操作:直接返回 即可。
代码
#include<bits/stdc++.h>
using namespace std;
const int inf=1e9;
char buf[1<<21],*p1=buf,*p2=buf;
inline char getc(){
return p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++;
}
inline int read(){
int x=0,f=1;
char ch=getc();
while(ch<'0'||ch>'9'){
if(ch=='-')f=-1;
ch=getc();
}
while(ch>='0'&&ch<='9')x=x*10+(ch-'0'),ch=getc();
return x*f;
}
char pbuf[1<<21],*pp=pbuf;
inline void push(const char&c){
if(pp-pbuf==(1<<21))fwrite(pbuf,1,(1<<21),stdout),pp=pbuf;
*pp++=c;
}
inline void write(int x){
static int sta[35];
int top=0;
if(x<0)push('-'),x=-x;
do sta[top++]=x%10,x/=10;
while(x);
while(top)push(sta[--top]+'0');
push('\n');
}
inline void flush(){
fwrite(pbuf,1,pp-pbuf,stdout);
pp=pbuf;
}
int main(){
int q=read(),k=read(),n=1<<k;
vector<int> d(n,inf);
queue<int> que;
while(q--){
int op=read(),x=read();
if(op==1){
if(d[x]==0)continue;
d[x]=0,que.push(x);
while(!que.empty()){
int u=que.front();que.pop();
for(int i=0;i<k;i++){
int v=u^(1<<i);
if(d[v]>d[u]+1)d[v]=d[u]+1,que.push(v);
}
}
}
else write(d[x]);
}
flush();
return 0;
}①:汉明距离是两个等长字符串在对应位置上不同字符的个数,特别对于二进制串就是异或后 的个数。