Hamming Distance
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 772 Accepted Submission(s): 267
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.
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 <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
#define MAXN 100001
#define INF 999999999
int temp[MAXN];
int c[16][16];
int n;
int fun(int a, int b)
{
int sum = 0;
a = temp[a];
b = temp[b];
for (int i = 0; i < 5; i++)
{
int x = a % 16, y = b % 16;
sum += c[x][y];
a /= 16;
b /= 16;
}
return sum;
}
void input()
{
int t;
for (int i = 0; i <= 15; i++)
{
for (int j = 0; j <= 15; j++)
{
int t = i ^ j, num = 0;
for (int k = 0; k < 4; k++)
{
if ((1 << k) & t)
{
num++;
}
}
c[i][j] = num;
}
}
cin >> t;
while (t--)
{
cin >> n;
for (int i = 0; i < n; i++)
{
scanf("%x", &temp[i]);
}
srand(time(0));
int ans = INF;
for (int i = 0; i < MAXN; i++)
{
int a = rand() % n;
int b = rand() % n;
if (a != b)
{
int temp = fun(a, b);
ans = min(ans, temp);
}
}
cout << ans << endl;
}
}
int main()
{
std::ios::sync_with_stdio(false);
input();
return 0;
}