-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChefAndSubArrays.java
More file actions
73 lines (58 loc) · 1.89 KB
/
ChefAndSubArrays.java
File metadata and controls
73 lines (58 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package problems.codechef;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* Created by arpit on 19/12/16.
*/
public class ChefAndSubArrays {
static int[]a=new int[100000];
static int[]bitCount=new int[32];
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t,n,k;
String[]s;
t=Integer.parseInt(br.readLine());
while (t-->0){
s=br.readLine().split("\\s");
n=Integer.parseInt(s[0]);
k=Integer.parseInt(s[1]);
s=br.readLine().split("\\s");
Arrays.fill(bitCount,0);
for (int i = 0; i < n; i++) {
a[i]=Integer.parseInt(s[i]);
}
System.out.println(solve(n,k));
}
}
private static long solve(int n, int k) {
//l represents left index and r represents right index of the sub array.
int l,r=0;
long ans=0;
for (l = 0; l < n; l++) {
while ((r<n) && bitwiseOr(bitCount)<k){
for (int j =0; j<32; j++) {
if ((a[r]&(1<<j))>=1)
bitCount[j]++;
}
r++;
}
if (bitwiseOr(bitCount)>=k)
ans+=(n-r+1);
//This loop removes the effect of element with lth index from bitcount array.
for (int j = 0; j < 32; j++) {
if ((a[l]&(1<<j))>=1)bitCount[j]--;
}
}
return ans;
}
//returns the bitwise xor of elements between l to r inclusive based on bitcount array.
private static long bitwiseOr(int[] bitCount) {
long ans=0;
for (int i = 0; i < 32; i++) {
if (bitCount[i]>0)ans+=(1<<i);
}
return ans;
}
}