hdu 4712 Hamming Distance ( 随机算法混过了 )

Hamming Distance

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


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
 

ps:不知道正解是怎样做,用随机算法水过了。
思路:
答案的范围不大,0~20,数据不强,可以考虑随机算法。

代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <algorithm>
#define maxn 105
#define maxx 100005
#define INF 0x3f3f3f3f
using namespace std;

int n,m,ans;
int xr[maxn][maxn];
int a[]= {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
char s[maxx][6];

int cal(int k1,int k2)
{
    int i,j,t=0,x,y;
    for(i=0; i<5; i++)
    {
        x=s[k1][i];
        if(x>='A'&&x<='F') x=x-'A'+10;
        else x=x-'0';
        y=s[k2][i];
        if(y>='A'&&y<='F') y=y-'A'+10;
        else y=y-'0';
        t+=xr[x][y];
    }
    return t;
}
void solve()
{
    int i,j,t,x,y;
    srand((unsigned)time(NULL));
    for(i=1; i<=100000; i++)
    {
        x=rand()%n;
        y=rand()%n;
        if(x==y) continue ;
        t=cal(x,y);
        if(ans>t) ans=t;
        if(!ans) return ;
    }
}
int main()
{
    int i,j,t;
    for(i=0; i<16; i++)
    {
        for(j=0; j<16; j++)
        {
            xr[i][j]=a[i^j];
        }
    }
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(i=0; i<n; i++)
        {
            scanf("%s",s[i]);
        }
        ans=INF;
        solve();
        printf("%d\n",ans);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值