HDU 4712Hamming Distance(隨機函式運用)

果7發表於2013-09-10

Hamming Distance

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


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
 


     題目大意:給你很多串,最多10^5個串,每個串長度是5,16進位制轉化為2進位制,問你任意兩個串抑或得到1的最小的個數。

解題思路:做題的時候只顧著如何降低複雜度,簡單的O(n^2)肯定會超時,最後才得知是隨機函式寫。結果只可能是0~20.自己寫的時候10W次還是WA了,人品不行啊,果斷隨機100W次A了。 不過聽說可以更暴力地直接列舉最前面的10000個也可以A。網路賽要敢於嘗試。

題目地址:Hamming Distance

AC程式碼:
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[100005];

int main()
{
    int tes,i,j,k,res,ans;
    scanf("%d",&tes);
    while(tes--)
    {
        int n;
        scanf("%d",&n);
        for(i=0;i<n;i++)
            scanf("%X",&a[i]);  //16進位制讀取
            
        res=20;  //結果初始為最大20
        for(i=1;i<=1000000;i++)
        {
            j=rand()%n;  //隨機函式
            k=rand()%n;
            if(j==k)
                continue;
            ans=0;
            int tmp=a[j]^a[k];  //抑或
            while(tmp)  //抑或算1的個數,儲存到ans中
            {
                if(tmp&1)
                    ans++;
                tmp>>=1;
            }
            if(ans<res)
                res=ans;
        }
        cout<<res<<endl;
    }
    return 0;
}

//2453MS 676K




相關文章