Hamming Distance

Problem Description
(From wikipedia) For binary strings a and b the Hamming distance is equal to the number of ones in a XOR b. For calculating Hamming distance between two strings a and b, they must have equal length.
Now given N different binary strings, please calculate the minimum Hamming distance between every pair of strings.
 
Input
The first line of the input is an integer T, the number of test cases.(0<T<=20) Then T test case followed. The first line of each test case is an integer N (2<=N<=100000), the number of different binary strings. Then N lines followed, each of the next N line is a string consist of five characters. Each character is '0'-'9' or 'A'-'F', it represents the hexadecimal code of the binary string. For example, the hexadecimal code "12345" represents binary string "00010010001101000101".
 
Output
For each test case, output the minimum Hamming distance between every pair of strings.
 
Sample Input
2 2
12345
54321
4
12345
6789A
BCDEF
0137F
 
Sample Output
6
7

 

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

char a[11];
int key[111111];
int hash[1111111];
int que[2111111];
int front,end;
int ans;

void bfs()
{
    while(front<=end)
    {
        int now=que[front++];
        if(hash[now]>=ans) continue;
        for(int i=0; i<=19; i++)
        {
            int to=(now^(1<<i));
            if(hash[to]>hash[now]+1)
            {
                hash[to]=hash[now]+1;
                que[++end]=to;
            }
        }
    }
}

int cal(int t,int s)
{
    int sum=0,i;
    for(int i=0; i<=19; i++)
    {
        int tmp=key[t]&(1<<i);
        int txt=key[s]&(1<<i);
        if(tmp^txt) sum++;
    }
    return sum;
}

int main()
{
    freopen("a.txt","r",stdin);
    int T,i,j,n;
    scanf("%d",&T);
    while(T--)
    {
        memset(hash,1,sizeof(hash));
        ans=33;
        scanf("%d",&n);
        getchar();
        for(i=1; i<=n; i++)
        {
            for(j=1; j<=5; j++)
            {
                scanf("%c",&a[j]);
                if(a[j]==' '||a[j]=='\n')  j--;
            }
            int txt=1,sum=0;
            for(j=1; j<=5; j++)
            {
                if(a[j]>='0'&&a[j]<='9') sum+=(a[j]-'0')*txt;
                else sum+=(a[j]-'A'+10)*txt;
                txt*=16;
            }
            key[i]=sum;
        }
        sort(key+1,key+1+n);
        for(i=1; i<n; i++) ans=min(ans,cal(i,i+1));

        for(i=1; i<=n; i++)
        {
            ans=min(ans,hash[key[i]]);
            front=1,end=0;
            que[++end]=key[i];
            hash[key[i]]=0;
            bfs();
        }
        printf("%d\n",ans);
    }

    return 0;
}
View Code

 

posted @ 2013-09-09 21:45  1002liu  阅读(254)  评论(0编辑  收藏  举报