For a number X, let its "Coolness" be defined as the number of "101"s occurring in its binary representation. For example, the number 21 has Coolness 2, since its binary representation is 101012, and the string "101" occurs twice in this representation.
A number is defined as Very Cool if its Coolness is greater than or equal to K. Please, output the number of Very Cool integers between 1 and R.
Input:
The first line contains an integer T, the number of test cases.
The next T lines contains two space-separated integers, R and K.
Output:
Output T lines, the answer for each test case.
Constraints:
1 ≤ T ≤ 100
1 ≤ R ≤ 10^5
1 ≤ K ≤ 100
SAMPLE INPUT
1
5 1
SAMPLE OUTPUT
1
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to write a solution to count numbers from 1 to R inclusive such that the number of occurrences of substring "101" in their binary representation is at least K.
Constraints: R up to 100,000 and T up to 100. Straightforward approach: For each test case, iterate from 1 to R, compute binary string, count occurrences of "101", compare to K. Complexity O(T * R * length) ~ worst-case 100100k17 = 170 million operations, which might be borderline but likely okay in Python with optimizations? Possibly T=100, R=100k => 10 million numbers? Actually 100100k = 10 million, not 10 million? Wait: 100 * 100,000 = 10,000,000. For each number, we need to convert to binary string (max 17 bits for 100k ~ actually 2^17 = 131072, so ~17 bits). Counting "101" can be done in O(length) ~ 17. So total operations ~ 170 million, which might be okay in Python with careful coding? 170 million operations might be ~ 1-2 seconds? Possibly borderline but may pass given time limit not specified. But we can precompute coolness for all numbers up to max R across test cases to avoid repeated work. Since max R is up to 100k and T up to 100, we can compute once an array coolness[0..maxR] and then for each test case count how many numbers from 1 to R have coolness >= K. That reduces total operations: iterate from 1 to maxR, compute binary string and count, store. Then each query is O(1) to accumulate? Actually we need to answer for each R: number of Very Cool integers between 1 and R. So we can precompute prefix sums: prefix[i] = count of numbers from 1 to i with coolness >= K? But K varies per test case. So we need to answer for arbitrary K. We could precompute coolness values for all numbers, and then for each query, we need count of numbers <= R with coolness >= K. Since there are up to 100 queries, we could for each query iterate through numbers 1..R and count, but that's again O(R) per query. However if we precompute coolness, each query can be answered by scanning from 1 to R (max 100k) and summing if coolness[i] >= K. That's 100 * 100k = 10 million checks, which is fine. Or we could sort or precompute frequency by coolness and prefix sums per coolness value, but with K up to 100 but max coolness maybe not high. Let's compute max possible coolness for numbers <=100k. Binary length 17, maximum occurrences of "101"? The string "10101" contains overlapping "101"? For "10101": positions: 0-2 "101", 2-4 "101". So two occurrences in 5 bits. In 17 bits, max maybe floor((n-1)/2) if pattern length 3? Actually for pattern "101", the maximum number of (possibly overlapping) occurrences in a binary string of length L is at most floor((L-1)/2)? Let's think: The pattern is length 3. Overlapping possibilities require shift 2 to overlap? Because "101" overlaps such that the last two bits "01" become first two of next? The overlapping condition: if we have "10101", the first "101" ends at index 2, next starts at index 2. Overlap of 2 bits. So minimal distance between starts is 2. So in string of length L, maximum number of occurrences (starting indices) is at most floor((L - 3)/2) + 1? Actually start indices i from 0 to L-3. Overlap allowed, but we need to find maximum cardinality set of start indices such that each i is separated by at least 2? Not exactly: Since occurrences can overlap, you can have starts at 0,2,4,... as long as substring from start to start+3 is within length. So maximum is floor((L-1)/2) if L>=3? Let's test L=3: floor((2)/2)=1, correct. L=4: floor(3/2)=1, but we could have "1010": has "101" at start 0 only; at start 1 length 4 => substring from 1 to 3 = "010"? no. So 1. L=5: floor(4/2)=2, indeed "10101" yields 2. L=6: floor(5/2)=2, "101010": check: starts 0->"101",2->"101",4->"010"? no, start 4 out of range? Actually length 6, starts up to 3 (since 3+3=6). So starts 0 and 2 give 2. Could we get 3? Starts 0,2,4? start 4 gives substring 4..6 which is length 3, but index 6 not exist? Actually indices 0-5, start 4 -> 4,5,? need 6, so no. So max is 2. So indeed max occurrences = floor((L)/2) if L even? Actually for L=6, floor((L-1)/2)=2. For L=7, floor(6/2)=3. "1010101" (7 bits) has starts at 0,2,4? Check: 0-2:101, 2-4:101, 4-6:101 -> 3 occurrences. So max = floor((L)/2)? Actually for L=7, floor(7/2)=3? floor(7/2)=3, but need to check L=5: floor(5/2)=2, works. L=3: floor(3/2)=1, works. So maybe max occurrences = floor((L)/2) for L>=3? But for L=4: floor(4/2)=2, but maximum is 1. So not exactly. Let's derive: Starting index i, condition i+2 < L => i <= L-3. If we take i=0,2,4,... the maximum i_max <= L-3. So if L-3 is even? For L=4, L-3=1, sequence of i=0,2,... but 2 >1, so only i=0 =>1. For L=5, L-3=2, i=0,2 =>2. For L=6, L-3=3, i=0,2 =>2 (since 4 >3). For L=7, L-3=4, i=0,2,4 =>3. So number = floor((L-3)/2) + 1 = floor((L-1)/2). Indeed floor((L-1)/2) matches: L=4 -> floor(3/2)=1; L=5-> floor(4/2)=2; L=6-> floor(5/2)=2; L=7-> floor(6/2)=3. So max coolness <= floor((L-1)/2). For numbers up to 100k, binary length L <= 17 (since 2^17=131072). So max coolness <= floor(16/2)=8? Actually for L=17, floor(16/2)=8. But is it possible to achieve 8? Need string of length 17 with pattern at positions 0,2,4,6,8,10,12,14? That's 8 starts: 0,2,...,14. Last start 14 yields substring indices 14,15,16 => need 3 bits. So indices 0-16, that's 17 bits. So 8 occurrences possible. But can we construct a binary string that yields "101" at each of these positions? That would require bits: Let's define bits b0...b16. For start i, we need b_i=1, b_{i+1}=0, b_{i+2}=1. Overlapping constraints may force consistency. Let's try: For i=0: b0=1,b1=0,b2=1. i=2: b2=1,b3=0,b4=1 -> b2 already 1 okay, b3=0, b4=1. i=4: b4=1,b5=0,b6=1 -> b4=1 ok, b5=0,b6=1. i=6: b6=1,b7=0,b8=1 -> b6=1 ok, b7=0,b8=1. i=8: b8=1,b9=0,b10=1 -> b8=1 ok, b9=0,b10=1. i=10: b10=1,b11=0,b12=1 -> b10=1 ok, b11=0,b12=1. i=12: b12=1,b13=0,b14=1 -> b12=1 ok, b13=0,b14=1. i=14: b14=1,b15=0,b16=1 -> b14=1 ok, b15=0,b16=1. So string is determined: 1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1. That's alternating 1 and 0 starting with 1. So indeed "10101010101010101". That's 17 bits. This number's decimal value? Let's compute: It is sum_{i even? Actually bits positions from 0 LSB? Usually binary representation without leading zeros: The string written is most significant bit first? When we talk about binary representation, we usually write from most significant bit to least. The occurrence of "101" in the binary representation as a string (without leading zeros) refers to the standard representation without leading zeros. The string we constructed: "10101010101010101" has 17 bits. That number is (1<<16) + (1<<14) + ... + 1? Actually bits from leftmost (most significant) to rightmost (least). For pattern "101" we consider the string as it appears. Overlaps are allowed across the whole string. So the pattern "101" can start at position 0 of the string (char index 0). So indeed our constructed string yields 8 occurrences. The decimal value of this 17-bit number is? It's (2^16 + 2^14 + ... + 2^0)? Actually bits set at positions 16,14,12,...,0 (even positions from 0-indexed from right? Wait: The binary string "10101010101010101" has length 17, so the most significant bit (index 0 in string) corresponds to 2^16, next 2^15? Actually string positions: s[0] = 1 -> 2^16, s[1]=0 -> 2^15, s[2]=1 -> 2^14, s[3]=0 -> 2^13, ... s[16]=1 -> 2^0. So bits set at even positions from 0 to 16 in string index => exponent = 16 - i. So exponents: for i=0 =>16, i=2=>14, i=4=>12, ..., i=16=>0. So exponents: 16,14,12,...,0. That's 9 bits? Actually there are 9 ones: because from 0 to 16 inclusive step 2 => (16/2)+1=9 ones. So the number is sum_{k=0}^{8} 2^{16-2k} = 2^16 + 2^14 + ... + 2^0. That sum is (4^9 -1)/3? Actually 2^16 * (1 + 1/4 + 1/4^2+...+1/4^8) = 2^16 * (1 - (1/4)^9)/(1 - 1/4) = 2^16 * (1 - 4^{-9})/(3/4) = (2^16 * 4/3) * (1 - 4^{-9}) = (2^18/3)(1 - 4^{-9}) approx 87381.33? Compute exactly: sum of geometric series: a=2^16=65536, ratio r=1/4, n=9 terms => sum = 65536 * (1 - (1/4)^9)/(1 - 1/4) = 65536 * (1 - 1/262144)/(3/4) = 65536 * ( (262143/262144) ) * (4/3) = 65536 * 262143/262144 * 4/3 = (65536/262144) * 262143 * 4/3 = (1/4) * 262143 * 4/3 = 262143 * (1/4 * 4/3) = 262143/3 = 87381. So the number is 87381. That's <= 100k, so indeed possible to have coolness 8. Could we have 9? For length 18, floor((18-1)/2)=8, but 18-bit numbers > 2^17 = 131072, but max R=100k so numbers <=100k have at most 17 bits. So max coolness is 8. So K can be up to 100 but actually K max 100 is just an upper bound; practically for numbers <=100k, coolness max 8, so for K>8 the answer is 0. So we could early return for K>8.
Given these constraints, we can compute coolness for all numbers 1..100000. Approach: precompute array cool[0..100000]. For each number i, get its binary string representation without leading zeros using bin(i)[2:], then count overlapping occurrences of "101". Counting overlapping: iterate from start index 0 to len(s)-3, if s[i:i+3] == "101": count++. Could also compute using bit manipulation? But string conversion is okay.
After precomputing coolness, we need to answer each test case: count = sum(1 for i in range(1,R+1) if cool[i]>=K). That would be O(R) per test case, up to 100*100k = 10 million, which is acceptable in Python (maybe 0.2 sec per 10 million? Actually 10 million simple integer comparisons and loop overhead may be ~0.2-0.3 sec? Not sure but likely fine). Alternatively, we could precompute prefix sums for each possible K threshold. Since K max 8, we can create a 2D array prefix[9][n] where prefix[k][i] = number of numbers <= i with coolness >= k. But then for K>8 we just return 0. So we can compute an array freq[i] = coolness value (0..8). Then for each threshold k from 1 to 8, compute prefix. Then each query answered in O(1): if K>8 -> 0 else prefix[K][R]. This would be more efficient for many queries, but with only up to 100 queries, the simple sum per query is simpler and less code.
But to be safe and efficient, we'll precompute coolness and maybe also compute an array cumulative counts for each possible K? Actually we could compute for each number i its coolness, and then create an array count_cool[0..8] and then for each test case we need count of numbers with coolness>=K from 1..R. That can be done with a prefix sum for each coolness value? Let's think: We need to answer many range count queries for threshold. One approach: Build a Fenwick tree per coolness? Overkill.
Simplify: Since max R is only 100k, we can just precompute an array of coolness and then for each test case, loop 1..R and sum. That's total operations up to 10 million (since sum of R across test cases could be up to TmaxR = 100100k = 10 million). Actually worst-case each test case could have R=100k, so total numbers processed = 100 * 100k = 10 million. That is fine. Even with Python, 10 million loop iterations performing an if check and addition should be quick (maybe < 0.5 seconds). Actually typical Python can do ~50 million simple operations per second? Not exactly; maybe 50 million integer ops is around 1 second? I'm not sure. But 10 million is fine.
Alternatively, we could precompute an array prefix_coolness where prefix[i] = number of very cool numbers for a fixed K? But K varies. So not directly.
Thus solution: read T, collect all test cases, find max_R among them. Precompute coolness for numbers 1..max_R. Then for each test case, compute ans = sum(1 for n in range(1,R+1) if cool[n]>=K). Print ans.
But we must consider that T up to 100, and we might want to speed up by caching results in a list and possibly using list comprehension inside a loop.
Edge cases: R=0? Not allowed, R>=1. Numbers from 1 to R inclusive.
We need to be careful about the counting of overlapping occurrences. The problem statement says "the number of '101's occurring in its binary representation". Example: 21 binary 10101, and they say occurs twice. So overlapping is counted.
Implementation details: For each integer n, bin(n) returns string like '0b10101', so we can do b = bin(n)[2:] then count with loop.
Alternative: we can compute using bit operations but not needed.
Let's test sample: R=5, K=1. Numbers: 1 (1) -> no '101' (length<3) -> cool=0. 2 (10) ->0, 3 (11) ->0, 4 (100) ->0, 5 (101) ->1. So ans=1.
Now we need to ensure we count correctly: For 5 binary '101', one occurrence. For 21 binary '10101', we count from start 0: '101', start 2: '101', no more, so 2.
One more test: Number 85 decimal = 1010101 binary (7 bits). Should have 3 occurrences. Check: '1010101': positions 0,2,4 => 3.
Now we need to handle large T quickly. We'll precompute.
Pseudo-code:
def compute_coolness(limit):
cool = [0]*(limit+1)
for n in range(1, limit+1):
s = bin(n)[2:]
count = 0
for i in range(len(s)-2):
if s[i:i+3] == '101':
count += 1
cool[n] = count
return cool
Then for each test case, ans = sum(cool[n] >= K for n in range(1, R+1))
But we can also compute prefix sums for each possible K (0 to 8) but not necessary.
Nevertheless, we might consider optimizing by precomputing once and then for each test case using sum over slice? But sum with generator is fine.
Alternatively, we could precompute an array "good" where good[k][i] but K up to 8, so we can compute a cumulative array cum[k] where cum[k][i] = number of numbers <= i with coolness >= k. Then answer is cum[K][R] if K <= 8 else 0.
Let's compute cum: initialize 2D list of size (9) x (max_R+1) maybe. Actually we need only cum for thresholds 1..8, but we can create list of 9 (index 0..8) but we care about K>=1. So:
cum = [[0]*(max_R+1) for _ in range(9)] # but 9 rows for k=1..8, maybe index by k
But we can fill as:
for i in range(1, max_R+1):
c = cool[i]
for k in range(1,9):
cum[k][i] = cum[k][i-1] + (1 if c >= k else 0)
That's O(max_R * 8) = 800k, trivial. Then each query O(1). This might be simpler code and ensure speed.
But we need to handle K>8 -> 0. So we can do that.
Given that it's simple to implement and efficient, I'll go with that.
Implementation steps:
Read T.
Store test cases in list, also track max_R.
Precompute cool for 1..max_R.
Use bin conversion and count via find? Could use str.count('101') but it counts non-overlapping? Actually str.count counts non-overlapping occurrences. For overlapping we need custom. So loop or using regex? Better loop.
Option: use s.count('101')? Let's test: s = '10101', s.count('101') returns 1? Actually Python's str.count counts non-overlapping occurrences. For '10101', it finds '101' at position 0, then after that, it resumes at end of that match? Typically .count does not count overlapping. So it would return 1. So we need overlapping count. Could use a while loop with find with start index. But simplest is loop.
After cool array, create cum array of size (9) x (max_R+1). Actually we can store as list of lists, but we can also create a list of length max_R+1 for each threshold. But to be memory efficient, max_R <= 100000, 9100001 ~ 900k integers, fine.
We'll do: cum = [[0](max_R+1) for _ in range(9)] (index 0 unused maybe). Then for i from 1 to max_R:
for k in range(1,9):
cum[k][i] = cum[k][i-1] + (cool[i] >= k)
For each test case (R,K):
if K > 8: print(0) else: print(cum[K][R])
But note: cum[k][i] uses list of lists. Access cum[k][R] where k index from 0 to 8; we need to ensure correct. We'll create cum with 9 rows: rows 0..8, but we will use rows 1..8. So cum = [ [0]*(max_R+1) for _ in range(9) ].
Now the main loop: for each test case, if K > 8: answer = 0 else answer = cum[K][R].
Edge: K may be 0? Constraints say K>=1.
Now complexity: O(max_R * (L + 8)) where L average binary length ~17, so total ~ 100k * 25 = 2.5M, fine.
Alternatively, we could avoid the nested loop for cum by computing prefix sums per threshold using separate loops:
for k in range(1,9):
for i in range(1, max_R+1):
cum[k][i] = cum[k][i-1] + (cool[i] >= k)
But that is also fine.
Let's implement.
But maybe we can compute coolness using bit manipulations? Not necessary.
One more potential optimization: While computing cool for each n, we can use a sliding window technique? Not needed.
I'll implement:
def precompute(limit):
cool = [0]*(limit+1)
for n in range(1, limit+1):
s = bin(n)[2:]
cnt = 0
# use for i in range(len(s)-2):
# if s[i:i+3] == '101': cnt+=1
# But to be faster, maybe use while with str.find? e.g., start = 0; while True: pos = s.find('101', start); if pos==-1: break; cnt+=1; start = pos+1? That's overlapping? Actually str.find with start increment by 1 will find overlapping occurrences. So we can do:
start = 0
while True:
pos = s.find('101', start)
if pos == -1:
break
cnt += 1
start = pos + 1 # because we want overlapping, next search starts one char after found start
cool[n] = cnt
return cool
Using find may be slightly faster as it's implemented in C, but we have to loop per occurrence. But maximum occurrences is <=8, so loop up to 8 times per number, and find calls maybe overhead. But the simple Python loop over length-2 (max 15) is also fine. We'll use direct loop for simplicity.
Now note: For numbers with binary length <3, the loop range is empty -> cnt=0.
Now for cum: we need to compute for k=1..8.
But we can also compute cumulative counts for each k without storing cum as 2D: we can store an array of size max_R+1 of cool values, and then for each query compute sum. But we prefer cum for O(1) query.
But we could also precompute an array "prefix" that is a list of size max_R+1 where prefix[i] is number of numbers with coolness >= something? Actually we need variable threshold, so need multiple.
Alternatively, we can compute for each i the coolness, then sort? No.
Thus cum is fine.
Memory: cum 9*100001 ~ 900k integers, each maybe 28 bytes? Actually Python ints are heavy (~28 bytes), so 900k * 28 ~ 25 MB, times 2? plus cool array another 100k ints ~ 2.8 MB. So total maybe 30 MB, acceptable. But if we store 9 rows of ints, each row contains Python ints, memory might be high but likely within limit (common limits 256 MB). Alternatively, we could store only cumulative counts for each k as an array of ints in Python list; each element is Python int. That's still okay.
But to reduce memory, we could store only one cum array for all thresholds by using a binary indexed technique? Not needed.
We can also note that K max is 100, but we only need up to 8, but we could allocate 101 rows? That would be 101*100001 ~ 10 million ints, memory too high ( ~ 280 MB). So we must limit to 9 rows.
Thus we must treat K > 8 as zero.
Now ensure we handle test cases where R may be less than max_R? That's fine.
Potential pitfalls: We need to output each answer on separate line.
So count up to 21 with K=1: numbers:5,10,11,13,20,21 => 6. Also maybe other? ? Let's also check 85 (within 100k) but not needed.
Now test: R=21, K=2: only 21 (cool=2) => ans=1. 5,10,11,13,20 have 1 only.
Now proceed.
Now we should consider leading zeros? The problem says binary representation, which normally has no leading zeros. So we treat as no leading zeros.
Now confirm maximum coolness among numbers <=100k: we found 8 for 87381. Also maybe 874? Actually check 87381 binary is 10101010101010101. That's 17 bits, 8 occurrences. Could any number have coolness 8? Possibly also some others like 87380? But max is 8.
Now K up to 100 so many will be 0.
Now implement.
Potential optimization: When reading test cases, we might have multiple queries with same R or K, but not needed.
Now code structure:
import sys
def main():
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
t = int(next(it))
tests = []
max_R = 0
for _ in range(t):
R = int(next(it)); K = int(next(it))
tests.append((R, K))
if R > max_R:
max_R = R
# Precompute coolness
cool = [0](max_R+1)
for n in range(1, max_R+1):
s = bin(n)[2:]
cnt = 0
# loop
# Using Python's find method for overlapping:
# Alternatively:
for i in range(len(s)-2):
if s[i] == '1' and s[i+1] == '0' and s[i+2] == '1':
cnt += 1
cool[n] = cnt
# Precompute cumulative for thresholds 1..8
maxKThresh = 8
cum = [[0](max_R+1) for _ in range(maxKThresh+1)] # index 0..8, using 1..8
for k in range(1, maxKThresh+1):
c = 0
for i in range(1, max_R+1):
if cool[i] >= k:
c += 1
cum[k][i] = c
# Answer queries
out_lines = []
for R, K in tests:
if K > maxKThresh:
out_lines.append('0')
else:
out_lines.append(str(cum[K][R]))
sys.stdout.write('\n'.join(out_lines))
Now test with R=21, K=2: max_R maybe 21 if only test. cum[2] for i=21: count numbers with cool>=2: only 21 =>1. Good.
Now consider K=9: output 0.
Now confirm that we handled up to max_R=100k. Let's test computationally: maximum coolness? We'll rely on algorithm.
Potential micro-optimizations: In cool computation, we can avoid creating a new string for each n by using bit operations to detect pattern? Not needed.
But we might improve speed by using a precomputed table for small numbers? Not necessary.
Now one more thought: Could we compute coolness using recursion or DP? Not needed.
Now consider time: Precomputing cool for 100k numbers: for each n we do a loop over its binary length, average ~9 iterations (since len-2 average maybe 8-15). So total ~1 million operations, fine. Then cum loops: 8 * 100k = 800k, fine. So overall negligible.
Now output.
Edge: If max_R=0? Not possible because R>=1.
Now finalize.
Now ensure we use correct reading of input: sample input has "1\n5 1". Our code works.
Now about overlapping counting: Using s.find with start increment by 1 is also fine. But the manual loop is simpler and consistent.
Now let's think about potential errors: For numbers with binary representation that has length less than 3, the loop range is empty, count=0. Good.
Now we might consider the case where the binary representation includes "101" at the very start or end. Our loop includes up to len(s)-3 inclusive. Good.
Now test manually for 0? We don't need 0.
Now implement.
But wait: The problem statement says "For a number X, let its "Coolness" be defined as the number of "101"s occurring in its binary representation. For example, the number 21 has Coolness 2, since its binary representation is 101012, and the string "101" occurs twice in this representation." It might be that they consider the binary representation without leading zeros. So fine.
Now consider if they count overlapping? Example shows overlapping: 10101 has two. So yes.
Now check if there's any tricky aspect: Could there be numbers where binary representation is like "101101"? That would have two occurrences? Check: "101101": substrings: 0-2:101, 1-3:011,2-4:110,3-5:101 -> two occurrences (0 and 3). Overlapping? 0 and 3 not overlapping but that's okay.
Now done.
Now final answer code.
But before final, consider if we can reduce memory usage by not storing cool array and directly compute cum? We could compute cool and update cum in one pass. Instead of storing cool, we can compute cool for each n, and then for each k (1..8) we need to know if cool >= k. We could update cum arrays directly: after computing cnt, for each k from 1 to 8, if cnt >= k, then increment cum[k][i] = cum[k][i-1] + 1 else cum[k][i] = cum[k][i-1]. But that requires having cum arrays per k and we need previous values for each k. We can store cum as 2D and update in place: For each i, we need cum[k][i] = cum[k][i-1] + (cnt>=k). This can be done by first setting cum[k][i] = cum[k][i-1] for each k and then adding 1 for those k where cnt>=k. But we need cum[k][i-1] which is from previous iteration, so we can keep a running array of current cumulative counts for each k. We can initialize an array cur[k] = 0 for k=1..8. Then for i from 1 to max_R: compute cnt; for each k from 1 to 8: if cnt >= k: cur[k] += 1; then set cum[k][i] = cur[k]. This avoids storing cool array and does the cumulative update in one pass. That's more memory efficient. Let's adopt that.
Pseudo:
maxKThresh = 8
cum = [[0](max_R+1) for _ in range(maxKThresh+1)] # rows 0..8, ignore row0
cur = [0](maxKThresh+1) # 0..8
for i in range(1, max_R+1):
s = bin(i)[2:]
cnt = 0
for j in range(len(s)-2):
if s[j]=='1' and s[j+1]=='0' and s[j+2]=='1':
cnt += 1
# update cur for thresholds
for k in range(1, maxKThresh+1):
if cnt >= k:
cur[k] += 1
cum[k][i] = cur[k]
This is efficient.
Now final code:
import sys
def main():
data = sys.stdin.read().split()
if not data:
return
it = iter(data)
t = int(next(it))
tests = []
max_R = 0
for _ in range(t):
R = int(next(it)); K = int(next(it))
tests.append((R, K))
if R > max_R:
max_R = R
code
MAX_K_THRESH = 8 # because max coolness for numbers <= 100k is 8
# initialize cumulative array for thresholds 1..8, each of length max_R+1
cum = [[0]*(max_R+1) for _ in range(MAX_K_THRESH+1)] # index 0 unused
cur = [0]*(MAX_K_THRESH+1)
for i in range(1, max_R+1):
s = bin(i)[2:]
cnt = 0
# count overlapping "101"
# loop over positions
# Option: use while with find overlapping:
# But let's use simple loop
L = len(s)
for j in range(L-2):
if s[j] == '1' and s[j+1] == '0' and s[j+2] == '1':
cnt += 1
# update cumulative counts for each threshold
for k in range(1, MAX_K_THRESH+1):
if cnt >= k:
cur[k] += 1
cum[k][i] = cur[k]
out = []
for R, K in tests:
if K > MAX_K_THRESH:
out.append('0')
else:
out.append(str(cum[K][R]))
sys.stdout.write('\n'.join(out))
if name == "main":
main()
Now test sample.
Now we might want to confirm max coolness indeed is 8 for numbers <= 100000. The number we computed 87381 is <=100k, so yes. Could there be 9? For length 18, need 9 occurrences: pattern starts at 0,2,4,6,8,10,12,14,16? That would be 9 starts, last start 16 gives indices 16,17,18? Actually for length 18, indices 0..17, start 16 yields positions 16,17,18? out of range; start max is 15 (since 15+2=17). So max start 15? Let's compute: For length L, max start = L-3. For L=18, start max = 15. The arithmetic progression with step 2: 0,2,4,..., up to <=15. That gives floor(15/2)+1 = 8+1? Actually 15/2=7.5 floor=7, +1 => 8? Let's count: from 0 to 15 step2: 0,2,4,6,8,10,12,14 => 8 starts. So max is 8. So indeed for numbers up to 2^17-1 = 131071, max coolness is 8. For 2^17 = 131072, binary is '100000000000000000'? Actually 2^17 is a 1 followed by 17 zeros, length 18. Its coolness maybe lower. But anyway max_R=100k < 131072, so max coolness is 8. So our threshold is correct.
Now confirm that for numbers exactly 100000, what is coolness? Not needed.
Now final code above.
Now potential micro-optimizations: For counting "101", we can use a faster method: using bit shifts? For each i, we could check bits: while number > 0? But string conversion is fast.
But maybe we can even precompute coolness using DP? Not needed.
Now consider the possibility of using a built-in count for overlapping? Python doesn't have that, but we can use regular expression with lookahead? That would be overkill.
Now let's test for some random values.
Test with R=87381, K=8. Our code should count how many numbers <=87381 have coolness >=8. Likely only 87381? Possibly also other numbers like 87380? But maybe only 87381 and maybe some others? Let's think: To have coolness 8, the binary string must be length 17 and must contain "101" at positions 0,2,4,...,14. That forces the pattern exactly as 101010...101. Could there be another pattern with 8 occurrences? Possibly if the string length is 17, you need 8 occurrences. The start positions must be something like a set of indices i1,...,i8 each <=14, each i+2 <=16. Overlapping pattern forces constraints. Let's attempt to see if any other arrangement yields 8. The necessary condition for 8 occurrences is that the string length is at least 17 and we have starts at maybe 0,2,4,6,8,10,12,14 (the only possible set of 8 starts with minimal spacing). Could we have starts at 1,3,5,7,9,11,13,15? That would also be 8 starts? 1+2=3, so last start 15 gives indices 15,16,17? For length 17, indices 0..16, so start 15 yields indices 15,16,17 -> out of range, because index 17 doesn't exist. So start 15 invalid, so max start is 14. So only possible set of 8 is starts 0..14 step 2? Could there be a set like 0,2,4,6,8,10,12,13? That's not step 2 for the last? Overlap condition: for overlapping occurrences, if you have start i and i+1, then the substrings would be s[i:i+3] and s[i+1:i+4]. For them both to be "101", we need s[i]=1, s[i+1]=0, s[i+2]=1, and also s[i+1]=1? Because for start i+1, we need s[i+1]=1, s[i+2]=0, s[i+3]=1. That forces s[i+1] to be both 0 and 1, impossible. So starts must differ by at least 2. So the maximum number of starts in length L is floor((L-1)/2). To achieve that maximum, starts must be exactly 0,2,4,...,2*(M-1) where M = floor((L-1)/2). For L=17, M=8, starts 0,2,...,14. And the string pattern is forced: s[0]=1, s[1]=0, s[2]=1; then s[2]=1 forces s[3]=0? Actually from start 2 we have s[2]=1, s[3]=0, s[4]=1; so consistent. So the string is forced uniquely as alternating 1 and 0 starting with 1. So only one string of length 17 yields 8 occurrences: "10101010101010101". Similarly, for shorter lengths, there might be multiple strings achieving max occurrences for that length. But for length 17, only that one yields 8. Could there be numbers with binary length 18 that also have 8 occurrences? Actually 8 is the max for length 17. For length 18, max occurrences is floor((18-1)/2) = 8 as well (since 17/2 floor=8). To achieve 8 in length 18, you need starts 0,2,4,6,8,10,12,14? That gives 8 starts, last start 14 gives indices 14,15,16 => need bits 14..16, okay. The string would be forced as before for bits up to 16. The 18th bit (index 17) is not constrained by these starts? Let's see: For starts up to 14, we have constraints: s[0]=1,s[1]=0,s[2]=1,s[3]=0,s[4]=1,s[5]=0,s[6]=1,s[7]=0,s[8]=1,s[9]=0,s[10]=1,s[11]=0,s[12]=1,s[13]=0,s[14]=1,s[15]=0,s[16]=1. So bits up to 16 are determined: positions 0..16 are fixed as alternating starting with 1. The bit at position 17 (the 18th bit) is not constrained by any occurrence because occurrences only involve up to index 16 (since start max 14, i+2=16). So bit 17 can be either 0 or 1. So there are two strings of length 18 that have 8 occurrences: "101010101010101010" and "101010101010101011". However, these numbers would be >= 2^17 = 131072. Since max_R=100000 < 131072, they are not included. So for R<=100k, the only number with coolness 8 is 87381 (which corresponds to the 17-bit pattern). Actually 87381 is exactly that 17-bit pattern. Could there be any number with coolness 8 that is less than 87381? Possibly if the binary representation has length 17 but not starting with 1? But length 17 means the most significant bit is 1. To have coolness 8, the string must be exactly the alternating pattern, which is 87381. So only one number. But wait, what about a number with length 16? Max coolness for length 16 is floor((15)/2)=7. So cannot be 8. So indeed only 87381. So for K=8 answer is count of numbers <=R that are >=87381 and also equal to 87381 if R>=87381 else 0. For K>8 answer 0. So our threshold handling works.
Now ensure that we compute cum for k up to 8 correctly, but cum[8][i] for i >=87381 will be at least 1.
Now test quickly: if we have R=100000, K=8, answer should be 1. Let's manually compute: 87381 <=100000, so yes.
Now also consider K=7: many numbers could have coolness >=7. The max for length 16 is 7, so many numbers maybe have 7. But our code will count.
Now code is ready.
Now about reading input: Use sys.stdin.read to be fast.
Now final output.
Now we might consider using array module for cum? Not needed.
Now I will produce final answer.
But there is a nuance: In the problem, they said "For a number X, let its "Coolness" be defined as the number of "101"s occurring in its binary representation." It might be that they count non-overlapping? But example clarifies overlapping. So correct.
Now final code.
Now I'll produce final answer explanation and code. ```python
import sys
def main() -> None:
data = sys.stdin.read().split()
if not data:
return
it = iter(data)
t = int(next(it))
tests = []
max_R = 0
for _ in range(t):
R = int(next(it))
K = int(next(it))
tests.append((R, K))
if R > max_R:
max_R = R
code
# For numbers ≤ 10^5 the maximum possible coolness is 8
MAX_COOL = 8
# cum[k][i] = number of integers in [1..i] with coolness ≥ k (k = 1..8)
cum = [[0] * (max_R + 1) for _ in range(MAX_COOL + 1)] # index 0 unused
cur = [0] * (MAX_COOL + 1) # running counts
for i in range(1, max_R + 1):
s = bin(i)[2:] # binary representation without '0b'
L = len(s)
cnt = 0
# count overlapping occurrences of "101"
for j in range(L - 2):
if s[j] == '1' and s[j+1] == '0' and s[j+2] == '1':
cnt += 1
# update cumulative arrays for all thresholds
for k in range(1, MAX_COOL + 1):
if cnt >= k:
cur[k] += 1
cum[k][i] = cur[k]
out_lines = []
for R, K in tests:
if K > MAX_COOL:
out_lines.append('0')
else:
out_lines.append(str(cum[K][R]))
sys.stdout.write('\n'.join(out_lines))