Hamming Distance HDU - 4712 (随机)

 

Hamming Distance

 HDU - 4712 

(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

https://blog.csdn.net/HackerTom/article/details/73189121

#include <algorithm>
#include <cstring>
#include <cstdio>
#include <ctime>
using namespace std;
const int N = 1e5 + 7;
int a[N];

int dis(int x, int y) {
	x = a[x] ^ a[y];
	y = 0;
	for (int i = 0; i < 20; ++i) {
		y += ((x >> i) & 1);
	}
	return y;
} 

int main() {
	
	srand((unsigned)time(NULL)); //把时间作为随机函数的种子 
	int t;
	scanf ("%d", &t);
	while (t--) {
		int n;
		scanf ("%d", &n);
		for (int i = 1; i <= n; ++i) {
			scanf ("%x", a+i); //%x读入一个16进制 
		}
		int ans = 0x3f3f3f3f;
		for (int i = 1, x, y; i <= 500000; ++i) { //随机选500000次 
			x = rand() % n + 1;
			y = rand() % n + 1;
			if (x == y) continue;
			ans = min(ans, dis(x, y));
		} 
		printf ("%d\n", ans);
	}
	
	return 0;
}

优化: 

#include <algorithm>
#include <cstring>
#include <cstdio>
#include <ctime>
using namespace std;
const int N = 1e5 + 7;
int a[N];

int dis(int x, int y) {
	x = a[x] ^ a[y];
	y = 0;
	while (x) y += x&1, x >>= 1;
	return y;
} 

int main() {
	
	srand((unsigned)time(NULL)); //把时间作为随机函数的种子 
	int t;
	scanf ("%d", &t);
	while (t--) {
		int n;
		scanf ("%d", &n);
		for (int i = 1; i <= n; ++i) {
			scanf ("%x", a+i); //%x读入一个16进制 
		}
		int ans = 0x3f3f3f3f;
		int m = n * (rand()%100+100);
		m = min(m, 200000);
		for (int i = 1, x, y; i <= m; ++i) { //随机选m次 
			x = rand() % n + 1;
			y = rand() % n + 1;
			if (x == y) continue;
			ans = min(ans, dis(x, y));
		} 
		printf ("%d\n", ans);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/nucleare/article/details/88920312
今日推荐