Gym - 101532A Subarrays Beauty(位操作找規律)

Cymbals發表於2018-03-19

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();
    }
}

相關文章