You are given a sequence of N integer numbers A. Calculate the sum of Ai AND Aj for all the pairs (i, j) where i < j.
The AND operation is the Bitwise AND operation, defined as in here.
Input
The first line of input consists of the integer N.
The second line contains N integer numbers - the sequence A.
The second line contains N integer numbers - the sequence A.
Output
Output the answer to the problem on the first line of the output.
Example
Input: 5 1 2 3 4 5 Output: 9
Scoring
Subtask 1 (13 points): N <= 1000, Ai <= 1.
Subtask 2 (39 points): N <= 1000, Ai <= 109.
Subtask 3 (21 points): N <= 105, Ai <= 1.
Subtask 4 (27 points): N <= 105, Ai <= 106.
Subtask 2 (39 points): N <= 1000, Ai <= 109.
Subtask 3 (21 points): N <= 105, Ai <= 1.
Subtask 4 (27 points): N <= 105, Ai <= 106.
A very well designed problem that can be easily tackled with bit logic and hashing.
Let us observe few things, The and operator results in one only when both the bits are ON. So first step is hashing the
On bits . i.e finding the number of numbers for which 0th bit is on then 1th bit is On then 2nd bit is on and so On. there can be maximum 30 bits.
Now for a present number we break it bitwise. Suppose the ith bit of the number is ON then we first decrease the hash count of that bit and then we add power(2,i)*hash[i] to the result . as power(2,i) is the value in decimal of that bit being on
and hash[i] gives the count of such bits on the right side.
*** code goes here******
- #include<iostream>
- #include<bits/stdc++.h>
- using namespace std;
- int hash[35];
- long long int ans=0;
- long long int arr[100010];
- long long int power(int n ,int k)
- {
- if(k==0)
- return 1;
- long long int temp=power(n,k/2);
- if(k%2==0)
- return temp*temp;
- else
- return n*temp*temp;
- }
- int main()
- {
- int n;
- cin>>n;
- // cout<<power(2,5)<<" "<<power(2,10)<<endl;
- for(int i=0;i<n;i++)
- {
- cin>>arr[i];
- for(int k=0;k<31;k++)
- {
- if(arr[i]&1<<k)
- hash[k]++;
- }
- }
- ans=0;
- // cout<<"done "<<endl;
- for(int i=0;i<n;i++)
- {
- // cout<<arr[i]<<endl;
- for(int k=0;k<31;k++)
- {
- if(arr[i]& 1<<k)
- {
- // cout<<"for k ="<<k<<endl;
- hash[k]--;
- ans=ans+power(2,k)*hash[k];
- }
- }
- //cout<<"ans wer is "<<ans<<endl;
- }
- cout<<ans<<endl;
- return 0;
- }
- ****** ends here *****
No comments:
Post a Comment