HDUOJ---Hamming Distance(4712)

 

Hamming Distance

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others) Total Submission(s): 916    Accepted Submission(s): 335

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
 

 

Source
 


 随机算法,第一次接触......

这里需要具备的知识是:(1)16进制的输入输出......
(2)查了以下资料,有关汉明距离的算法:

对于两个字串...可以是数组,字符,求其汉明距离的是对两个字串求异或^。。。

该部分的代码为:

 

/*

  ussigned dist(unsigned a, unsigned b)

  {

    int val=a^b,da=0;

    while(val)

    {

     val ^= val -1;

     da++;

    }

    return 0;

  }

*/


随机算法需要知道的几个函数srand(),rand(),---》头文件为stdlib.h

时间的头文件为time.h-----time();

所以代码为:

 1 #include<iostream>

 2 #include<cstdio>

 3 #include<cstring>

 4 #include<ctime>

 5 #include<algorithm>

 6 #define maxn 100000

 7 using namespace std;

 8 int dist(int a,int b)   //gongshi

 9 {

10     int val=a^b,distance=0;

11     while(val)

12     {

13         ++distance;

14         val &= val - 1 ;

15     }

16  return distance;

17 }

18 int Hex[maxn+1];

19 int main()

20 {

21     int t,i,n,min,x,y,c,cnt;

22 //time_t t1;

23     scanf("%d",&t);

24     while(t--)

25     {

26      scanf("%d",&n);

27      for(i=0;i<n;i++)

28      scanf("%X",&Hex[i]);

29         srand((unsigned)time(NULL));

30      for(cnt=i=0;i<maxn;i++)

31      {

32          x=rand()%n;

33          y=rand()%n;

34          if(x!=y)

35          {

36            c=dist(Hex[x],Hex[y]);

37            if(cnt==0||min>c)

38               min=c,cnt=1;

39            else

40                 if(min==0) break;

41          }

42      }

43      printf("%d\n",min);

44     }

45  return 0;

46 }
View Code

 

你可能感兴趣的:(HDU)