gym-101532 A Subarrays Beauty

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:

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, 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.

Output

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

Example
Input
2
3
7 11 9
4
11 9 6 11
Output
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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值