Gym - 101532A 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

位操作题,第一次做这种的只能喊666。
师兄指导说把二进制全部写出来找规律,6666。
题解看注释。

public class Main {
    static final int MAX_BIT = 20;// ai最大是10的6次幂,转成二进制是20位。

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int t = reader.nextInt();
        while (t-- > 0) {
            int n = reader.nextInt();
            int[] cnt = new int[MAX_BIT];
            long res = 0;
            for (int i = 0; i < n; i++) {
                int get = reader.nextInt();
                for (int j = 0; j < MAX_BIT; j++) {
                    if ((get >> j & 1) == 1) {// 判断每一位是不是1!
                        // 如果是,记录
                        cnt[j]++;
                        // 转回10进制累加
                        res += (long) cnt[j] << j;// 因为这里没转long一直wa...左移真是太容易爆了
                        continue;
                    }
                    cnt[j] = 0;// 一旦不是就归零(与操作的特点)
                    // 顺便把后面的位也都归零了....不然影响结果,这就是为什么硬要循环20次
                }
            }
            out.println(res);
        }
        out.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值