gym-101532 A Subarrays Beauty

来源:互联网 发布:工业控制网络结构 编辑:程序博客网 时间:2024/06/07 12:34

You are given an array a consisting of n integers. A subarray (l, r) from arraya is defined as non-empty sequence of consecutive elementsal, al + 1, ..., ar.

The beauty of a subarray (l, r) is calculated as thebitwise AND for all elements in the subarray:

Beauty(l, r) = al & al + 1& al + 2& ... & ar

Your task is to calculate the summation of the beauty of all subarrays (l, r) (1 ≤ l ≤ r ≤ n):


Input

The first line contains an integer T, whereT is the number of test cases.

The first line of each test case contains an integer n(1 ≤ n ≤ 105), wheren is the size of the array a.

The second line of each test case contains n integersa1, a2, ..., an(1 ≤ ai ≤ 106), giving the arraya.

Output

For each test case, print a single line containing the summation of the beauty of all subarrays in the given array.

Example
Input
237 11 9411 9 6 11
Output
4048


题意

求所有连续子区间的按位与运算和。


挺水的一道题,把所有数转化为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;    }}


原创粉丝点击