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(找規律)
- HDU 4951 Multiplication table(找規律)
- QOJ7789-一道位運算找規律好題
- Touring cities (找規律 哈密爾頓迴路)
- HDU5139 Formula (找規律+離線處理)ORM
- Java欄位初始化規律Java
- HDU 5795 A Simple Nim (SG函式+打表找規律)函式
- LeetCode-6. Z字形變換(找規律)LeetCode
- codeforces 340CTourist Problem(找規律數學題)
- HUNAN -11566 Graduation Examination(找規律)NaN
- HDU-6415 Rikka with Nash Equilibrium (DP/找規律)UI
- HDU 5439 Aggregated Counting(找規律+預處理)
- 【組合數+找規律】codeforces 815B - Karen and Test
- HDU 2897-邂逅明下(博弈-SG函式打表找規律)函式
- 山東省第四屆ACM大學生程式設計競賽-Alice and Bob(二進位制&&找規律)ACM程式設計
- ZOJ Monthly, January 2019 - A Little Sub and Pascal's Triangle(找規律)
- HDU 1847 Good Luck in CET-4 Everybody!(找規律版巴什博奕)Go
- IO流下:位元組流、流操作規律(java基礎)Java
- EMS單號規律與順豐單號規律(C#)C#
- HDU 1847-Good Luck in CET-4 Everybody!(博弈-SG函式/找規律)Go函式
- A Multiplication Game (博弈,規律)GAM
- 規範的位操作方法
- 【LeetCode動態規劃#04】不同的二叉搜尋樹(找規律,有點像智力題)LeetCode動態規劃
- Number of k-good subarraysGo
- leedcode-單詞規律
- 圖片跨域規律探尋跨域
- LeetCode-單詞規律LeetCode
- 索引的應用規律總結索引
- gym建立環境、自定義gym環境
- 軟體開發的21條規律
- LeetCode-290-單詞規律LeetCode
- votedisk在ASM diskgroup上的存放規律ASM
- [leetcode] 898. Bitwise ORs of SubarraysLeetCode
- 位操作
- Python裡的引用與拷貝規律Python
- python3 中 and 和 or 運算規律Python
- 事理圖譜:事件演化的規律和模式事件模式