HDU 4712 Hamming Distance(随机算法)

时间:2022-06-25 15:24:42

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4712

题目大意:任意两个数按位异或后二进制中含1的个数被称为海明距离,给定n个数,求出任意其中两个最小的海明数,输入是16进制。

Sample Input
2
2
12345
54321
4
12345
6789A
BCDEF
0137F
 
Sample Output
6
7

分析:用随机数来模拟,加srand()函数,放置产生伪随机数。代码有2个。

代码1:

 # include<iostream>
# include<cstdio>
# include<cstring>
# include<ctime>
# include<cstdlib>
# define INF 0x3f3f3f3f using namespace std; int cmp[][];
char data[][]; int solve(int q,int w)
{
int a,b,ret=;
for(int i=; i<; i++)
{
char x = data[q][i];
char y = data[w][i];
if(x>='' && x<='')
a = x-'';
else
a = x-'A' + ;
if(y>='' && y<='')
b = y-'';
else
b = y-'A' + ;
ret += cmp[a][b];
}
return ret;
}
int main()
{
int i,j;
for(i=; i<; i++)
{
for(j=; j<; j++)
{
int ans=;
int tmp = i^j;
for(int k=; k<; k++)
if((<<k) & tmp)
ans ++;
cmp[i][j] = ans;
}
} int T,n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(i=; i<=n; i++)
scanf("%s",data[i]);
int ans = INF;
srand((unsigned)time(NULL));
for(i=; i<=; i++)
{
int a = rand()%n + ;
int b = rand()%n + ;
if(a==b)
b= b%n+;
int tmp = solve(a,b);
if(tmp < ans)
ans = tmp;
}
printf("%d\n",ans);
}
return ;
}

代码2:

 # include<iostream>
# include<cstdio>
# include<cstring>
# include<ctime>
# include<cstdlib>
# define INF 0x3f3f3f3f using namespace std; int data[]; int get_one(int x)
{
int ret = ;
while(x)
{
ret ++;
x = x&(x-);
}
return ret;
}
int main()
{
srand((unsigned)time(NULL));
int T,n,i;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(i=; i<n; i++)
scanf("%x",&data[i]);
int ans = INF;
for(i=; i>=; i--) //好奇怪,这里从前往后循环返回WA
{
int a = rand()%n ;
int b = rand()%n ;
if(a != b)
ans = min(ans,get_one(data[a]^data[b]));
}
printf("%d\n",ans);
}
return ;
}