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();
}
}
相關文章
- 打表找規律
- HDU 6298 Maximum Multiple(找規律)
- HUNAN -11566 Graduation Examination(找規律)NaN
- QOJ7789-一道位運算找規律好題
- LeetCode-6. Z字形變換(找規律)LeetCode
- HDU-6415 Rikka with Nash Equilibrium (DP/找規律)UI
- Touring cities (找規律 哈密爾頓迴路)
- Java欄位初始化規律Java
- ZOJ Monthly, January 2019 - A Little Sub and Pascal's Triangle(找規律)
- HDU 5795 A Simple Nim (SG函式+打表找規律)函式
- HDU 6415(dp/找規律-2018多校第九場1001)
- 【LeetCode動態規劃#04】不同的二叉搜尋樹(找規律,有點像智力題)LeetCode動態規劃
- Number of k-good subarraysGo
- leedcode-單詞規律
- 三、凸透鏡成像規律
- LeetCode-單詞規律LeetCode
- 覆盤每一個C位出道的爆款,背後都有規律可循
- [leetcode] 898. Bitwise ORs of SubarraysLeetCode
- LeetCode-290-單詞規律LeetCode
- 1106: 找第K位數
- gym建立環境、自定義gym環境
- HDU 2197 本原串 (規律+快速冪)
- 快三長龍有規律嗎?
- 如何探索事物的客觀規律?
- 圖片跨域規律探尋跨域
- 位操作
- python3 中 and 和 or 運算規律Python
- ●連續質數2.3.5.7.11.13.17.19的規律●(9)
- ●連續質數2.3.5.7.11.13.17.19的規律●(6)
- ●連續質數2.3.5.7.11.13.17.19的規律●(5)
- ●連續質數2.3.5.7.11.13.17.19的規律●(4)
- ●連續質數2.3.5.7.11.13.17.19的規律●(3)
- ●連續質數2.3.5.7.11.13.17.19的規律●(10)
- ●連續質數2.3.5.7.11.13.17.19的規律●(1)
- ●連續質數2.3.5.7.11.13.17.19的規律●(2)
- ●連續質數2.3.5.7.11.13.17.19的規律●(15)
- ●連續質數2.3.5.7.11.13.17.19的規律●(16)
- ●連續質數2.3.5.7.11.13.17.19的規律●(11)