每日一题之 hiho211 Total Hamming Distance

描述
The Hamming Distance between two integers is the number of different digits between their binary representation. For example the hamming distance between 4(=01002) and 14(11102) is 2.

Given N integers, A1, A2, … AN, find out the total hamming distance of all pairs of them.

输入
The first line contains an integer N.

The second line contains N integers denoting A1, A2, … AN.

For 80% of the data: 1 <= N <= 1000

For 100% of the data: 1 <= N <= 100000 1 <= Ai <= 1000000000

输出
The total hamming distance

样例输入
3
1 2 3
样例输出
4

题意:

求n个数中,每两个数之间的hamming距离的总和

思路:

对于 N 1000 来说可以枚举每个数来求,但是数据范围扩大的话就会超时, 所以要找个优化的方法,我们可以把每个数都分解成二进制的形式,并且一个矩阵来存,每一行表示一个数的二进制表示,对每个数这样分解之后,就得到一个 n*m的矩阵,其中m是所有数中二进制表示中位数最长的值。然后对于每一列,可以算出这一列的hamming距离,就是 one * (n-one) ,这里 one表示 这一列中有多少个1。把每列结果求和就是答案,这样算法时间复杂度是 O ( m n ) 的 m最大不超过35,可以满足题目要求。(注意要用 long long)

#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

const int maxn = 1e5+5;

long long A[maxn];
int mat[maxn][50];

int divid(int row, long long x)
{   
    int col = 0;
    while(x) {
        mat[row][col++] = x%2;
        x /= 2;
    }
    return col;
}

int main()
{
    long long n;
    cin >> n;
    memset(mat,0,sizeof(mat));
    for (int i = 0; i < n; ++i)
        cin >> A[i];
    int col = 0;
    for (int i = 0; i < n; ++i) {
        col = max(col,divid(i,A[i]));
    }
    long long res = 0;
    long long one = 0;
    for (int j = 0; j < col; ++j) {
        one = 0;
        for (int i = 0; i < n; ++i) 
            one += mat[i][j];
        res +=  one*(n-one);
    }

    cout << res << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/u014046022/article/details/81052536