题解:P14947 Minpopcount
P14947 Minpopcount 题解
题意
维护一个集合
- 插入一个
[0,2^k) 内的整数x (保证x 不在S 中) - 查询对于给定的
x,\min_{y\in S}\operatorname{popcount}(x\oplus y) 的值(保证查询时S 非空)
其中
观察
我们需要快速回答查询:对于给定的
由于
考虑用 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;
}
①:汉明距离是两个等长字符串在对应位置上不同字符的个数,特别对于二进制串就是异或后