Hamming Codes

/*
ID: weitong4
LANG: C++
TASK: hamming
*/
#include<stdio.h>
#include<string.h>

#define max 64

int ans[max+5];
int N,B,D;

bool ham_dis(int x,int y){
    int cnt=0;
    for(int i=0;i<B;i++){
        if((x&1)!=(y&1)){
            cnt++;
        }
        x>>=1;
        y>>=1;
    }
    if(cnt>=D){
        return true;
    }
    return false;
}

bool OK(int sol,int x){
    for(int i=0;i<sol;i++){
        if(!ham_dis(ans[i],x)){
            return false;
        }
    }
    return true;
}

bool dfs(int cur,int sol){
    if(sol>=N){
        return 1;
    }
    for(int i=cur;i<=(1<<B);i++){
        if(OK(sol,i)){
            ans[sol]=i;
            if(dfs(i+1,sol+1)){
                return 1;
            }
        }
    }
}


int main(){
    freopen("hamming.in","r",stdin);
    freopen("hamming.out","w",stdout);
    while(~scanf("%d%d%d",&N,&B,&D)){
        ans[0]=0;
        dfs(1,1);
        for(int i=0;i<N;i++){
            if((i+1)%10==0){
                printf("%d ",ans[i]);
                continue;
            }
            printf("%d",ans[i]);
            if(i!=N-1){
                printf(" ");
            }
        }
        if(N%10){
            puts("");
        }
    }
    return 0;
}








原文地址:https://www.cnblogs.com/Stomach-ache/p/3703219.html