跳到正文

题解

题解:P14947 Minpopcount

#SUSPENDED#约 4 分钟
原文

这是 2026年1月7日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年1月6日
收录
2026年1月7日
更新
2026年11月14日
篇幅
约 4 分钟
获赞
1
题目
P14947

版本

  1. v2当前
  2. v1

P14947 Minpopcount 题解

题意

维护一个集合 SS,初始为空。支持两种操作:

  1. 插入一个 [0,2k)[0,2^k) 内的整数 xx(保证 xx 不在 SS 中)
  2. 查询对于给定的 x,min⁡y∈Spopcount⁡(x⊕y)x,\min_{y\in S}\operatorname{popcount}(x\oplus y) 的值(保证查询时 SS 非空)

其中 1≤q≤5×106,1≤k≤201\leq q\leq 5\times 10^6,1\leq k\leq 20。

思路

观察

我们需要快速回答查询:对于给定的 xx,找到集合 SS 中与其汉明距离 ①{^①} 最小的元素。

由于 k≤20k\leq 20,整个值域 [0,2k)[0,2^k) 最多只有 2202^{20} 个元素。我们可以考虑预处理所有值到集合 SS 的最小汉明距离。

BFS

  1. 状态定义:设 d[i]d[i] 表示数字 ii 到集合 SS 的最小汉明距离(即 min⁡y∈Spopcount⁡(i⊕y)\min_{y\in S}\operatorname{popcount}(i\oplus y))。
  2. 插入操作:当插入一个新元素 xx 时:
    • 如果 d[x]=0d[x]=0(已是最小值),则跳过;
    • 否则,设置 d[x]=0d[x]=0,并以 xx 为起点进行 BFS。
    • BFS 过程中,对于当前点 uu,检查所有与 uu 汉明距离为 11 的点 v←u⊕2iv\gets u\oplus 2^i;
    • 如果 d[v]>d[u]+1d[v]>d[u]+1,则更新 d[v]←d[u]+1d[v]\gets d[u]+1,并将 vv 加入队列。
  3. 查询操作:直接返回 dist[x]dist[x] 即可。

代码

C++
#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;
}

①:汉明距离是两个等长字符串在对应位置上不同字符的个数,特别对于二进制串就是异或后 11 的个数。