Hamming Distance
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 1744 Accepted Submission(s): 687
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
题目大意:
求n个十六进制数两两异或的结果中最少的1的个数解题思路:
首先O(n^2)肯定会超时,那么我们可以每次生成[0,n-1]内的2个随机数a、b,然后计算num[a]^num[b],生成很多组后,结果就可以近似计算出来。这样我们就不必每个枚举了。具体生成多少组,如果生成1e6组,时间大概2000ms左右,AC率接近100%;如果生成1e5组,时间600ms左右,AC率很低。
1e5组随机数:
1e6组随机数:
参考代码:
#include<map>
#include<stack>
#include<queue>
#include<cmath>
#include<ctime>
#include<vector>
#include<cctype>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const double eps=1e-10;
const int INF=0x3f3f3f3f;
const int MAXN=1e6+50;
int n,num[MAXN];
int get_ones(int x)
{
int re=0;
while(x)
{
re+=x&1;
x>>=1;
}
return re;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif // ONLINE_JUDGE
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%X",&num[i]);
srand(time(NULL));
int cnt=1e6,ans=INF;
while(cnt--)
{
int a=rand()%n;
int b=rand()%n;
if(a==b)
continue;
ans=min(ans,get_ones(num[a]^num[b]));
}
printf("%d\n",ans);
}
return 0;
}