PIPIOJ 1485: PIPI's bit operation problem Ⅳ bit operation

http://pipioj.online/problem.php?id=1485
Insert picture description here
Idea: The core idea is to convert the input into a binary representation, and then consider the contribution of each bit separately. We can use sumi sum_isumiIt indicates the input data stream represents binary iiThe sum of i -bit 1, then when the i-th data is read,sum sumThe s u m array records the information of the first i-1 data, then considering each bit of the i-th data separately, we can easily get the first i-1 data equal to or not in this bit The number of equals can be accumulated according to the nature of XOR.

#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;

using ll=long long;

ll ans=0;
int n,sum[30];

int main()
{
    
    
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
    
    
        int idx=0,mask=1,v;
        scanf("%d",&v);
        while(idx<30)
        {
    
    
            if(v&mask)
            {
    
    
                ans+=(ll)(i-sum[idx])*mask;
                ++sum[idx];
            }
            else
                ans+=(ll)sum[idx]*mask;
            mask<<=1;
            ++idx;
        }
    }
    printf("%lld\n",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/xiji333/article/details/114582651