题解:P14947 Minpopcount

· · 题解

P14947 Minpopcount 题解

题意

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

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

其中 1\leq q\leq 5\times 10^6,1\leq k\leq 20。

观察

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

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

考虑用 BFS 算法做这题。

设 d[i] 表示数字 i 到集合 S 的最小汉明距离(即 \min_{y\in S}\operatorname{popcount}(i\oplus y))。

每当插入一个新元素 x 时:
如果 d[x]=0(已是最小值),则跳过,否则,设置 d[x]=0,并以 x 为起点进行 BFS。

BFS 过程中,对于当前点 u,检查所有与 u 汉明距离为 1 的点 v\gets u\oplus 2^i,如果 d[v]>d[u]+1,则更新 d[v]\gets d[u]+1,并将 v 加入队列。

查询时直接返回 d[x] 即可。

代码

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

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