You are given an array a consisting of n integers. A subarray (l, r) from array a is defined as non-empty sequence of consecutive elements al, al + 1, ..., ar.
The beauty of a subarray (l, r) is calculated as the bitwise AND for all elements in the subarray:
Your task is to calculate the summation of the beauty of all subarrays (l, r) (1 ≤ l ≤ r ≤ n):
The first line contains an integer T, where T is the number of test cases.
The first line of each test case contains an integer n (1 ≤ n ≤ 105), where n is the size of the array a.
The second line of each test case contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106), giving the array a.
For each test case, print a single line containing the summation of the beauty of all subarrays in the given array.
2 3 7 11 9 4 11 9 6 11
40 48
题意
求所有连续子区间的按位与运算和。
挺水的一道题,把所有数转化为2进制,然后对二进制的每一位遍历一遍就行了。 复杂度O(n)
#include<stdio.h>
#include<iostream>
using namespace std;
const int MAX=1e5+10;
bool vis[MAX][25];
long long a[MAX];
long long bound[25];
int main()
{
int c=1;
for(int i=1;i<=24;i++)
{
bound[i]=c;
c*=2;
}
int T;
cin>>T;
while(T--)
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%lld",&a[i]);
}
for(int i=0;i<n;i++)
{
long long cnt=a[i];
for(int j=1;j<=22;j++)
{
vis[i][j]=(cnt&1);
//cout<<vis[i][j];
cnt>>=1;
}
//puts("");
}
long long ans=0;
for(int i=1;i<=22;i++)
{
long long len=0;
for(int j=0;j<n;j++)
{
if(vis[j][i])
len++;
else
{
ans+=(len*(len+1))/2*bound[i];
len=0;
}
}
ans+=(len*(len+1))/2*bound[i];
}
cout<<ans<<endl;
}
}