We need to parse the problem correctly. Given integer sequence a of length N. There are M = N(N+1)/2 nonempty contiguous subsequences (subarrays). Each subarray has a sum, called its "beauty". We can select K of these subarrays (they may overlap; essentially any K distinct subarrays) and compute the bitwise AND of their beauties. We want to maximize this AND value over all possible choices of K subarrays. So we need to find the maximum possible value X such that there exist at least K subarrays whose sums have all bits of X set? Wait careful: The bitwise AND of the chosen beauties. If we choose K subarrays with sums S1,...,SK, the AND is AND_{i=1..K} Si. We want to maximize this AND value. Since we can choose any K subarrays, we have freedom to pick those whose sums share common bits. The maximum AND value we can achieve is the maximum number X (as integer) such that there exist at least K subarrays whose sums all have bitwise superset of X? Actually, if we want AND of K numbers to be exactly X, then each of the chosen numbers must have bits that are 1 wherever X has 1, but they can also have extra 1's, but AND will zero out bits that are not 1 in all numbers. So to achieve AND exactly X, we need each of the K numbers to have (at least) all bits of X set (i.e., Si & X = X), and for bits not in X, they can be arbitrary, but they must be consistent such that after AND, the bits not in X are 0. That means that for any bit that is 0 in X, there must be at least one chosen Si that has 0 in that bit. However, we are not required to ensure that the AND equals X exactly; we want to maximize the resulting AND value. Typically, we can approach by considering that if we want to achieve a candidate value X, we need to check if we can pick K subarrays such that AND_{i} Si >= X (in the sense of bitwise, meaning X is a subset of the AND). But we are looking for maximum X that is actually attainable as the AND of some K subarrays. That is equivalent to: There exists a set of K subarrays such that the bitwise AND of their sums is at least X (i.e., has all bits of X set). Because if the AND is Y, then Y >= X means Y has all bits of X set (bitwise, X is a submask of Y). So the maximum possible AND is the maximum Y such that we can pick K subarrays with AND = Y. However, it may be easier to test candidate bits from high to low. Typical method: iterate bits from high to low (like 60 down to 0), and try to see if we can achieve an AND that has that bit set, while maintaining previous bits we already decided to set. So we can try to construct the answer greedily: start with ans=0; for bit from 60 down to 0, consider candidate = ans | (1<<bit). Check if it's possible to select K subarrays such that the AND of their sums is at least candidate. If yes, set ans = candidate. After all bits, ans is the maximum AND.
Thus we need a subroutine: given a target mask X, can we select K subarrays such that for each subarray, (sum & X) == X? Actually we need the AND of all selected sums to have all bits of X set. That condition is equivalent to: for every bit set in X, that bit must be 1 in every selected sum. For bits not in X, they can be whatever, but we need that the final AND (which will be the intersection of bits of all sums) doesn't accidentally have extra bits set that we don't care about (since we are testing whether we can achieve AND having X as a subset). Actually, we are testing if we can achieve an AND Y such that Y >= X (i.e., Y includes X). That means we need to select K subarrays such that for all bits b where X has 1, every sum has bit b = 1. For bits where X has 0, we don't care as long as we can possibly have the final AND not necessarily having that bit set. But we must ensure that we can actually have K subarrays satisfying that each sum has bits of X set. However, is that sufficient to guarantee that there exists a set of K subarrays with AND at least X? Suppose we pick K subarrays, each having all bits of X set. Then the AND of them will have at least all bits of X set (since intersection of 1's is 1). So the resulting AND will be at least X. So the condition for existence of K subarrays with AND >= X is exactly that there exist at least K subarrays whose sum has all the bits of X set (i.e., (sum & X) == X). Because if we pick those K subarrays, the AND will have at least X. There's no additional constraint because any extra bits might also be set, but that's okay because it still satisfies AND >= X? Actually if the AND has extra bits set, then it is > X in terms of value (maybe), but that's fine because we are only checking if we can achieve an AND that is at least X. However, we need to be careful: If we have K subarrays each having bits of X set, then the AND will have at least X. That means we can achieve an AND value that is >= X. But does that guarantee that we can achieve exactly some AND >= X? The question asks for the maximum possible value of the AND of the beauties of K subarrays. So if we can achieve AND >= X, then we can potentially achieve a higher AND (maybe by selecting different subarrays), but at least we know that X is feasible as a lower bound. In the greedy algorithm, we are trying to see if we can set a bit while keeping previous bits set. Typically we test: can we achieve AND at least candidate? If yes, we set that bit. This works because if we can achieve AND at least candidate, then we can achieve some AND value Y >= candidate. But we are building the maximum possible AND, so we check if there exists any selection of K subarrays such that AND >= candidate. That's exactly the condition of existence of K subarrays each having all bits of candidate set (since if they all have candidate bits set, AND >= candidate). So the subroutine is correct: for a given X, we need to count the number of subarrays whose sum has all bits of X set (i.e., (sum & X) == X). If that count >= K, then it is possible to achieve AND >= X (by picking any K of them). Conversely, if there is a selection of K subarrays with AND >= X, then each of those subarrays must have all bits of X set (since the AND has those bits set, each must have them). So the count of subarrays satisfying (sum & X) == X must be at least K. Therefore condition is necessary and sufficient. Good.
Thus problem reduces to: Given N up to 1000, we have up to about 500k subarrays (M up to ~500k). For each candidate X, we need to count how many subarrays have sum s such that (s & X) == X. But we have to test many candidates? In greedy algorithm, we test at most number of bits (like 60) times. So up to 60 checks. For each check we need to count subarrays meeting bit condition. N=1000 gives M=500k, we can afford O(N^2) per check? 60 * 500k = 30 million, which is okay in Python? 30 million operations maybe borderline but probably okay if optimized (C++ sure, Python maybe okay with some care, but 500k*60 = 30 million, which is like 0.3e8, might be okay with bit operations, but we need to compute sums of all subarrays. However, naive O(N^2) enumeration of all subarrays for each candidate would be 60 * (N^2) = 60 * 1e6 = 60 million, which is fine in Python (maybe ~0.5 seconds per 10 million? Actually Python loops are slower; 60 million operations could be 1-2 seconds? Might be okay within typical time limits (2 sec? but need to be careful). However, there is also the need to compute sums quickly; we can precompute prefix sums to get subarray sum in O(1) per subarray. So each candidate we could loop over all l,r and compute sum = pref[r] - pref[l-1]; then check if (sum & X) == X. That is O(N^2) per candidate. N=1000 => 500k subarrays, times 60 = 30 million. 30 million integer operations and bitwise AND check in Python might be okay, but we also need to count. Let's estimate: 30 million operations maybe 0.3-0.5 seconds if simple? Actually Python can do around 50 million integer operations per second? It depends. Usually Python can handle ~100 million simple operations? Not exactly; typical Python can do ~10-30 million operations per second on CP? Let's approximate: 30 million might be ~1 second. That is okay. However, we need to also handle the input, etc. So it seems feasible.
But we must also consider that K can be up to M, and we just need count >= K. So counting subarrays satisfying condition is straightforward.
Now, are there any pitfalls? The values a_i up to 1e9, so sums up to N*1e9 = 1e12, fits in 64-bit (around 40 bits). Actually 1e12 < 2^40 (1,099,511,627,776), so up to 40 bits. But we can go up to 60 bits just to be safe.
Now, is greedy algorithm always valid? Usually for bitwise AND maximization, we try to set bits from high to low, checking feasibility. This works because if we can achieve AND with certain bits set, we can try to set higher bits. The condition is monotonic: if X is feasible (exists K subarrays with AND >= X), then any Y <= X (bitwise) is also feasible? Not exactly: Y being a submask of X means if we have AND >= X, then AND >= Y because if all bits of X are set, then all bits of Y are set as Y's bits are subset of X's bits. So feasibility is monotone in the sense: if X is feasible, then any submask is feasible. In greedy, we start from ans=0. For each bit from high to low, we try ans|bit. If that candidate is feasible, we set it. This yields the maximum X because we decide each bit independently. The typical proof: suppose optimal answer is opt. Then for each bit from high to low, we maintain that ans is a prefix of opt (i.e., ans is bits higher than current that are same as opt). At current bit, if opt has that bit set, then candidate = ans|bit is feasible because opt itself (which is feasible) has that bit set and is >= candidate (since opt has all bits of candidate). Actually careful: If opt has the bit set, then candidate = ans|bit is a submask of opt (since ans is the higher bits of opt, we are considering adding the current bit that opt also has). Since opt is feasible (there exists a set with AND >= opt, which implies AND >= candidate because candidate <= opt), then candidate is feasible. So greedy will set it. Conversely, if opt does not have that bit set, but candidate is feasible, then setting it would produce a number greater than opt? Actually candidate would have that bit set while opt does not, but since ans matches higher bits of opt, candidate would be > opt in integer value? Not necessarily, because bits lower could differ. But could there be a feasible candidate with that bit set while opt does not have it? If candidate is feasible, there exists a selection with AND >= candidate. That AND could be >= candidate, which may be > opt? Actually opt is defined as the maximum possible AND value. If we can achieve an AND >= candidate, then we could achieve an AND maybe even greater than opt? Wait, the maximum AND is the supremum; if candidate is feasible, then there exists some selection whose AND is some value Y that is >= candidate. But Y itself could be the AND of those K subarrays. Since we are only considering the existence of a selection with AND at least candidate, that does not guarantee that the maximum possible AND is at least candidate? Actually if there is a selection with AND >= candidate, then the maximum AND (over all selections) is at least candidate. Because the maximum is the maximum over all selections; if one selection yields Y (which might be > candidate), then max >= Y >= candidate. So candidate feasible means max >= candidate. Since opt is the maximum, we have opt >= candidate. If candidate has a bit set that opt does not, we would have candidate > opt? Not necessarily; candidate could be > opt in integer value if it has a higher bit set that opt lacks. Suppose opt = 1000 (binary) and candidate = 1100, which is larger. Then if candidate is feasible, then max >= candidate > opt, contradicting opt being maximum. So that cannot happen. Therefore, if opt does not have a bit set, then candidate (with that bit set) cannot be feasible. So greedy correctly only sets bits that are in opt. This reasoning assumes that feasibility of candidate implies existence of selection with AND >= candidate, which yields max >= candidate. So if candidate > opt, contradiction. So indeed candidate feasible iff that bit is set in opt. Thus greedy yields opt. So algorithm correct.
Now, we need to implement count_subarrays_with_all_bits_set(X). We have to compute for all subarrays sum S, condition (S & X) == X. Since N=1000, we can do double loop. But we need to be careful about performance: In each candidate check, we will compute sums of all subarrays. However, we might also precompute all subarray sums once and store them? That would be M = up to ~500k numbers. Storing them is okay: 500k integers, each maybe 8 bytes, about 4 MB. Then for each candidate, we iterate over the list and check condition. That's 500k * 60 = 30 million checks, similar to double loop. But precomputing may reduce overhead of computing sums repeatedly? Actually if we compute sums for each candidate via double loop, we need to compute each sum from prefix sums each time, which is a subtraction, that's fine. Precomputing would compute sums once and store them. That might be slightly faster because we avoid repeated prefix lookups? But double loop also uses prefix lookups: sum = pref[r] - pref[l-1]. That's cheap. But double loop also involves two loops overhead. Possibly precomputing list and then counting for each X by iterating over list is simpler and may be faster if we can reuse the list. However, note that M = N(N+1)/2 up to 500500 for N=1000. That's manageable. We'll just precompute all sums into a list once. Complexity: O(N^2) to generate list. Then for each candidate X (max 60), we iterate list and count condition. That's 30 million simple operations. Acceptable.
But we also need to consider that candidate X changes across bits; we will call the count function many times. The list remains same, but we need to compute condition for each sum and each X. That's fine.
Alternative: we might be able to optimize using bitset or DP but not needed.
Now, check example: N=4, a=[2,5,2,5], K=2. All subarray sums: [2,7,9,14,5,7,12,2,7,5] Actually let's compute: subarrays: (1,1)=2, (1,2)=7, (1,3)=9, (1,4)=14; (2,2)=5, (2,3)=7, (2,4)=12; (3,3)=2, (3,4)=7; (4,4)=5. Counts. Need max AND of 2 numbers. Let's see: answer given 12. 12 in binary 1100. Which two sums give AND 12? Possibly 12 and 12? But we have only one sum 12? Actually we have sum 12 from (2,4): 5+2+5=12. Also sum 14 (1110) AND 12 (1100) gives 12? 14&12=12. So could pick 14 and 12 gives 12. So 12 is achievable. Could we get higher? 13? Not present. So answer 12.
Our algorithm: we test bits from high to low. Sums max ~14 so bits up to 4. Should work.
Second example: N=8, K=4, answer 32.
Alright.
Now, we need to be careful about integer overflow? Python handles big ints.
Now, we need to consider: K can be large, up to M. So count of subarrays with condition must be >= K.
Now, complexity: Precomputing sums: O(N^2) ~ 1e6 (since N=1000 gives 500k subarrays, which is about 0.5e6; we can just compute all subarray sums by iterating l from 0..N-1, and cumulative sum). Let's do:
pref[0] = 0; for i in range(N): pref[i+1] = pref[i] + a[i].
Then subarray_sums = []
for l in range(N):
s = 0
for r in range(l, N):
s += a[r] (or use prefix: pref[r+1]-pref[l])
subarray_sums.append(s)
That yields M sums.
Now, for each candidate X (at most 61 bits, but we only need to consider bits up to maybe 60 because sum max up to 1e12 ~ 2^40, but we can consider up to 60 to be safe). Actually we can find the maximum sum and set max bit accordingly. But we can just loop from 60 down to 0.
Now, feasibility check: count = 0; for s in subarray_sums: if (s & X) == X: count += 1. If count >= K: return True.
But we have to be careful: X can be up to maybe large, but sum & X == X condition essentially checks that all bits of X are set in s. So that's fine.
Now, the greedy: ans = 0; for b in reversed(range(61)): (or 60 down to 0). candidate = ans | (1<<b). If feasible(candidate): ans = candidate. Finally print ans.
But wait: The candidate may be ans| (1<<b) and we have to check feasibility. But note that when we check feasibility, we are counting subarrays where (sum & candidate) == candidate. However, after we have set some higher bits in ans, we need to also enforce those bits are set in the sums. So indeed candidate includes the previously set bits plus the new bit. So condition (sum & candidate) == candidate ensures that all bits set in candidate are present. That's correct.
Now, is there any subtlety? Suppose we have candidate = ans|bit, and we check if there exist K subarrays such that each sum has all bits of candidate. That is correct for verifying that we can achieve AND at least candidate.
Now, the count of subarrays may be huge, but we just need to compare with K. K up to 500k, so int fits.
Now, let's test with sample.
But we must consider that subarray sums can be negative? No, a_i positive (1 <= a_i <= 1e9), so sums positive.
Now, is there any potential for more optimization? Not needed.
Edge cases: N=2, K=1. Then we can choose any subarray, so maximum AND is just the maximum subarray sum? Actually for K=1, the AND of one number is just that number. So we can choose the maximum sum subarray, but wait, we can pick any one subarray, so the AND is that sum. So we want the maximum possible AND, which is the maximum sum. Our algorithm: for K=1, feasibility of candidate X requires at least one subarray sum having all bits of X set. That is true if there exists any sum >= X and also with those bits set? Actually (sum & X) == X means that sum has those bits set, but could be larger. The maximum possible X would be the maximum sum's bits? But the answer would be the maximum sum because you can choose that subarray. But is it possible that a candidate X not equal to any sum but still feasible? If there exists sum that has bits X set, then AND >= X can be achieved by picking that sum. The maximum such X is the maximum value that is a submask of some sum. That is not necessarily the maximum sum; it could be some value less than max sum but with bits set that may be present in many sums. However for K=1, the maximum AND is just the maximum sum, because for any candidate X, if some sum has X bits, then that sum's AND is itself, which is at least X but could be larger. The maximum possible AND would be the maximum sum among all subarrays. Because picking that sum yields AND = that sum. Could there be a larger number that is not a sum but is a submask of some sum? That number would be less than that sum? Actually if sum = 5 (101), a submask could be 4 (100) which is less than 5. The AND with itself is 5, which is larger than 4. So the maximum AND you can get is the maximum sum, because you can choose that subarray. So algorithm should output maximum sum. Let's test: For K=1, candidate check for a high bit would require at least one sum with that bit set. The maximum sum will have highest bits. Our greedy would produce the maximum sum? Possibly not exactly because the greedy builds a number bit by bit, and if there exists a sum with that bit set, it will set it. But after setting high bits, it will only set lower bits if they can be simultaneously set with the high bits in some sum. That essentially is constructing the maximum number that is a submask of some sum? Actually if there is at least one sum with all bits of candidate set, then we can set that bit. The final ans will be the bitwise OR of all bits that appear in at least one sum? Not exactly: Because we only set a bit if there is at least one sum that has that bit set and also all previously set higher bits? Wait, greedy: ans starts 0. For bit from high to low: test candidate = ans | (1<<b). Check if exists at least one sum (since K=1) with (sum & candidate) == candidate. That means the sum must have all bits set that are currently in ans plus the new bit. This essentially tests if there exists a sum that has a superset of the bits in candidate. So the greedy finds the maximum value X such that there exists a sum s with s >= X and (s & X) = X? Actually (s & X) = X is equivalent to X being a submask of s. So it's exactly the maximum number that is a submask of some sum? But the maximum submask of any sum is the sum itself (since any number is a submask of itself). The maximum among all submasks of sums is the maximum sum itself. Because if s is a sum, then s is a submask of s, and if we consider any number X that is a submask of some sum, X <= s? Not necessarily; if X is a submask of s, then X <= s in integer? Not always: For example, s=5 (101), X=6 (110) is not a submask because 110 & 101 = 100, not 110. So submask condition implies that wherever X has 1, s has 1. So X can have 1 only where s has 1. Therefore, the integer value of X is at most the integer value of s, because if we consider binary, having 1's only where s has 1's means X's bits are subset of s's bits, so X <= s (as an integer) because for any bit position, if s has 0, X must have 0; so X is obtained by zeroing some 1 bits of s, which makes it less than or equal to s. Indeed, if you clear some bits, the number decreases. So the maximum possible X that is a submask of any s is the maximum s itself (since you can take X = s). So for K=1, the greedy will produce max sum. Good.
For K>1, we require at least K sums that all have those bits set. So it's about the intersection of bits across at least K sums.
Now, we must ensure that counting subarrays with (s & X) == X is correct. It might be that there are overlapping subarrays but that doesn't matter. So we just need count.
Now, one more nuance: The AND of K numbers is at least X if each number has all bits of X set. But what if we select K numbers each having those bits, but then the AND could have additional bits set that we didn't guarantee? That's fine; it means AND >= X, not exactly equal. So feasibility condition is exactly count >= K.
Thus the algorithm stands.
Now, we need to implement feasibility check efficiently. As mentioned, we can precompute all subarray sums. However, N=1000 gives ~500k sums. Storing them as Python integers is fine. Then for each candidate X we iterate over all sums and count. 60 * 500k = 30 million iterations, each with a bitwise AND and comparison. This should be okay. We can further speed up by using list comprehension or built-in sum with generator? But Python loops are slower; we might use filter or sum(1 for s in sums if (s & X) == X). That still loops in Python. Could we use numpy? Not allowed.
Alternatively, we can process the bits in a smarter way: Since N is only 1000, we can perhaps for each candidate compute count in O(N^2) but with early exit if we reach K? In worst case, we need to scan all subarrays anyway. But we can break if count >= K to save time. That helps for many candidates: if K is small, we might find quickly. But K can be up to M, so worst-case we might need to scan all. Still fine.
But perhaps we can reduce number of candidate checks. Actually we only need to test at most 60 bits, so it's constant.
Thus solution is straightforward.
Now, double-check constraints: N up to 1000, a_i up to 1e9, sum up to 1e12, which fits in 40 bits. So we only need to check bits up to, say, 40 or 41. But to be safe, we can go up to 60 (since 1e12 < 2^40, but maybe sums could be up to 1000*1e9 = 1e12, that's about 2^40. But we might also consider that a_i can be 1e9, but sum could be up to 1e12, so 40 bits enough. However, we can go to 60, it's fine.
Potential optimization: Determine max possible sum, then find highest bit position of max sum (or maybe of max possible answer). Since answer cannot exceed max sum, we can limit bits to that. But not necessary.
Now, we must be careful about the possibility of large K close to M, and candidate X maybe high. In that case, the count of sums that have those bits might be low. But we just count.
Now, check with sample 2: N=8, K=4, answer 32 (binary 100000). Let's test conceptually: sums? We'll trust.
Now, let's think about correctness further: Suppose we have candidate X, and we count sums that have bits of X. If that count >= K, we can select any K of them, and their AND will have at least X. But what if the AND of those K sums also has extra bits not in X? That's fine, it yields a value > candidate? Actually could it be that the AND has bits not in X, making it larger? That's okay because we are checking if we can achieve an AND at least candidate. But when we are building ans greedily, we are trying to see if we can set this bit while keeping previous bits set. But if the AND we get from selecting K sums that satisfy (s & candidate) == candidate actually yields some Y that may have some bits set that we haven't yet considered (lower bits) and may have bits we haven't set yet. That Y would be >= candidate, meaning candidate is achievable as a lower bound. However, does that guarantee that there exists a selection that yields AND exactly candidate? Not needed. We only need existence of some selection with AND >= candidate. Because the maximum possible AND value is the supremum; if we can achieve something >= candidate, then the maximum is at least candidate. So to decide whether to set a bit in ans, we need to know if there is any selection whose AND value is at least ans|bit. That's exactly what we check. So the algorithm yields the maximum value that can be achieved as AND of K subarrays.
Now, confirm: The final ans is the maximum X such that there exists a selection with AND >= X? Actually the greedy yields the maximum integer that is a submask of the AND of some selection? Let's think: The maximum achievable AND value is M = max_{selection of K subarrays} AND(S_i). For each bit, we test if there exists a selection with AND having that bit set along with previous bits. So the final ans is exactly M. So it's correct.
Now, we should also consider if there is any nuance about "nonempty contiguous subsequences" and "subsequences may share elements" – that's fine.
Now, we need to code.
Implementation plan:
-
Read N, K.
-
Read list a of length N.
-
Compute prefix sums: pref = [0] * (N+1); for i in range(N): pref[i+1] = pref[i] + a[i].
-
Generate list sums = [].
For l in range(N):
s = 0
for r in range(l, N):
s += a[r] # alternative: s = pref[r+1] - pref[l]; but adding each time is fine.
sums.append(s)
Actually using prefix might be simpler: for l in range(N): for r in range(l, N): sums.append(pref[r+1] - pref[l]).
But note that computing by cumulative addition per l might be faster because you avoid double indexing? Probably similar.
We'll compute by two loops and prefix subtraction.
-
Determine the highest bit we need to consider: maybe max_sum = max(sums). Then max_bit = max_sum.bit_length() - 1 (since bit_length returns number of bits needed). We'll iterate from that bit down to 0. But to be safe, we can iterate from 60 down to 0 (or maybe 50). But if we go higher than max_sum, candidate may be > max_sum, and then feasibility will be false because no sum can have those bits (since sum would need to be at least candidate). So we can start from, say, 60. That's fine.
-
Define function possible(mask):
cnt = 0
for s in sums:
if (s & mask) == mask:
cnt += 1
if cnt >= K: return True
return False
-
ans = 0
for b in range(60, -1, -1):
if possible(ans | (1 << b)):
ans |= (1 << b)
-
Print ans.
Now, complexity: O(N^2 + B * M) where B=61, M~500k.
Now, test with examples.
Let's simulate first example:
N=4, a=[2,5,2,5], K=2.
Pref: [0,2,7,9,14]
Sums:
(1,1)=2
(1,2)=7
(1,3)=9
(1,4)=14
(2,2)=5
(2,3)=7
(2,4)=12
(3,3)=2
(3,4)=7
(4,4)=5
List: [2,7,9,14,5,7,12,2,7,5]
Now, bits: max sum 14 -> bit_length=4 (1110). We'll iterate from say 60 down to 0, but only bits up to maybe 3 will matter. Greedy:
ans=0
b from high to low, let's test bits 60..0; for most, candidate will be >0. But possible(ans|1<<b) for high bits will be false because mask large. So ans remains 0 until we hit bit 3 (8). Check candidate=8. Count sums where (s & 8) ==8? 8 in binary 1000. Which sums have that bit? 8: 8? Actually 9 has 8? 9=1001 has bit3=1; 12=1100 has bit3=1; 14=1110 has bit3=1; maybe others? 7=0111 no; 5=0101 no; 2=0010 no. So sums with bit3 set: 9,12,14 => count=3 >=2 => set ans=8.
Next bit2 (4): candidate = 8|4=12. Check sums where (s & 12)==12? 12=1100. Which sums have bits 8 and 4 both set? Need both bit3 and bit2=1. 9=1001 (bits: 8 and 1) -> missing bit2 (4). 12=1100 has bits 8 and 4 -> yes. 14=1110 has bits 8,4,2? 14=1110 -> bits 8,4,2 (yes). Also maybe others? 13? none. So sums: 12 and 14 => count=2 >=2 => set ans=12.
Next bit1 (2): candidate = 12|2=14. Check (s & 14)==14? Need bits 8+4+2=14. Which sums? 14=1110 -> has bits 8,4,2 -> yes. 12=1100 missing bit2 -> no. Others? none. So only one sum (14) has all bits. count=1 <2 => not set.
Next bit0 (1): candidate =12|1=13. Check (s &13)==13? Need bits 8,4,1. 9=1001 has 8 and 1 but missing 4. 13? none. So count=0. So ans remains 12. Works.
Now second example: We'll trust.
Now, consider potential issue: The sum list might be large but we can store as Python integers. However, note that N=1000, M=500500, each integer ~28 bytes? Actually Python ints are objects, overhead big. Storing 500k Python ints could be memory heavy: 500k * 28 bytes = 14 MB, plus list overhead maybe 4 MB, total ~18 MB. That's okay for typical memory limit (like 256 MB or 512 MB). So it's fine.
But we could also avoid storing all sums and recompute each time using double loops to save memory, but memory is fine. However, recomputing sums each time might be slower because we have to compute sums again (N^2 each time). But computing sums with prefix is cheap; the overhead of creating list once and then iterating 60 times over it may be similar to recomputing each time. Actually recomputing each time would involve O(N^2) loops for each candidate; that would be 60 * 500k = 30 million subarray computations (each computing sum via prefix subtraction). That's also 30 million operations, but with the overhead of nested loops. The list method does the same number of checks, but also has to store sums. Which is more efficient? Usually, precomputing list and then iterating flat list is faster because it's a single loop per candidate and uses memory, while nested loops have two-level loop overhead. However, Python nested loops (for i in range(N): for j in range(i,N)) have overhead of range and loops. The flat list iteration also has overhead of iterating a list. But the difference may be small. However, we also need to generate the list initially which is O(N^2). That's fine. So I'll go with precomputing sums.
But caution: The sum of a subarray could be up to 1e12, which fits in Python int.
Now, there is also possibility to further optimize using bit DP: Since N is only 1000, but we have many candidate masks, we might precompute for each subarray its sum bits. But not needed.
Now, about K: K can be up to M. Counting subarrays with condition may be exactly M for mask=0 (since all sums satisfy (s & 0)==0? Actually 0 mask: (s & 0)==0 is true for all s, because 0 is 0. But mask 0 is not considered as candidate? But we start ans=0, and candidate=ans|bit. So we never check mask=0. For final answer, it's at least 0. So no issue.
Now, check when K = M (all subarrays). Then we need to find maximum X such that for every subarray sum s, (s & X) == X? Actually we need at least K subarrays. For K = M, we need that all subarrays satisfy the condition. So X must be a submask of every subarray sum. Then the maximum X is the bitwise AND of all subarray sums (since the AND of all sums yields bits that are 1 in all sums). So answer would be the AND of all subarray sums. Our algorithm: we test bits from high to low; if there exist at least M subarrays with that bit set (i.e., all subarrays), then we set the bit. That yields the AND of all sums. So works.
Now, consider case where many subarrays have certain bits. The algorithm basically constructs the largest X such that at least K subarrays have all bits of X.
Now, one nuance: The condition (s & X) == X means that s has at least the bits of X set. For X=0, always true. For X>0, we require that s has those bits. So it's about the count of subarrays that have certain bits set.
Now, maybe we can also think about using prefix sums and bit contributions? But N=1000 is small.
Now, we should also consider that the number of bits we need to consider is up to maybe 40, but 60 is safe. However, if we use 60, candidate masks may be huge (like 2^60). But sums only up to 1e12, so bits beyond 40 will never be set in any sum, so for bits > max_bit, possible(ans|1<<b) will be false because (s & candidate) == candidate would require those high bits to be set in s, which never happen. So ans remains 0 for those bits. So it's fine.
But we might slightly optimize by computing max_sum and then iterating from its bit_length down to 0. That reduces loops from 60 to maybe 40. That's minor.
Now, let's implement.
We'll write:
def possible(mask):
cnt = 0
for s in sums:
if (s & mask) == mask:
cnt += 1
if cnt >= K:
return True
return False
Edge: When mask is 0, condition (s & 0)==0 always true, so count = M. That could be used if K=0? But K>=1 so not needed.
Now, one more nuance: The sums list can be large, but we can also early exit when count reaches K. So for many masks, we may not need to scan entire list if K is small. That helps.
Now, complexity worst-case when K is close to M, we might scan entire list for each mask. That's okay.
Now, confirm with N=1000, M=500500, 60 passes * 500k = 30 million checks. Each check: bitwise AND and compare. In Python, 30 million loops might be borderline but should be acceptable in 2 seconds? Actually typical Python can do ~50 million simple operations per second? Not exactly; on Codeforces, 10^7 operations is about 0.1-0.2 sec? It depends. 30 million might be around 1-2 seconds. Combined with list creation, it should fit within typical 2 sec limit? Possibly. But we can optimize by using Python's built-in functions like sum with generator? That still loops. We could use numpy but not allowed. We can also reduce number of bits by using max sum's bit length. That reduces from 60 to maybe 40. So 40*500k = 20 million. That's a bit better. Also, we might pre-filter sums for each bit? Not needed.
Alternatively, we can compute for each candidate mask by scanning the list once and incrementing count. That is simplest.
We can also store sums as a list of ints. When iterating, we can use a for loop. That is fine.
Now, test with N=1000 and all a_i=1e9, sums up to 1e12. 500k numbers each 1e12, memory maybe 28 bytes each ~14 MB, plus list overhead maybe 8 bytes per reference? Actually Python list holds references to objects. Each reference is 8 bytes (on 64-bit). So list of 500k references = 4 MB. Each integer object maybe 28 bytes (for small ints up to 2^30, but 1e12 is larger, Python ints have variable size, but still maybe 28-32 bytes). So total memory ~500k * (8+28) = 18 MB plus overhead. Acceptable.
Now, what about time to create the list? O(N^2) loops, about 500k iterations, each sum calculation. That's fine.
Now, potential micro-optimizations: Use local variables in loops, avoid attribute lookups. Write possible as inline within main with sums and K as closure variables. Or define as a nested function.
I'll implement as:
def can(mask):
cnt = 0
for val in sums:
if val & mask == mask: # precedence: bitwise & has lower precedence than ==, so need parentheses: (val & mask) == mask
cnt += 1
if cnt >= K:
return True
return False
But careful: bitwise & has lower precedence than ==, so we need parentheses: (val & mask) == mask.
Now, main loop:
ans = 0
max_sum = max(sums)
max_bit = max_sum.bit_length() # returns number of bits needed, so bits positions from max_bit-1 down to 0.
for b in range(max_bit-1, -1, -1):
if can(ans | (1 << b)):
ans |= (1 << b)
Alternatively, we can still iterate from 60 down to 0 but break early if (1<<b) > max_sum and ans==0? But using max_bit is simpler.
Now, one more nuance: The answer could be larger than max_sum? No, because answer is AND of sums; each sum <= max_sum, so AND <= max_sum. So we can safely restrict bits to max_sum's bits.
But what if max_sum is 0? Not possible as a_i >=1, so sums >=1.
Thus, we can compute max_bit.
Now, test with example: max_sum=14 -> bit_length=4, bits from 3 down to 0.
Now, edge case: N=1000, K=1. Then answer should be max_sum. Our algorithm: starting from high bit, for each bit, if there exists at least 1 sum with that bit set along with previous bits, we set it. Since we require that the sum has all bits set that we have accumulated, that effectively builds the maximum possible number that is a submask of some sum. But is that equal to max_sum? Let's see: Suppose we have sums like 1000 (8) and 0111 (7). max_sum is 8. Greedy: start with ans=0, b=3 (8). Check candidate=8: is there sum with bit 3 set? Yes (8). So ans=8. Next b=2 (4): candidate=12. Need a sum with bits 8 and 4 set. None, because only sum with 8 doesn't have 4, and sum with 7 has neither? Actually 7 has no 8. So fails. Next b=1 (2): candidate=10 (8+2=10). Need sum with bits 8 and 2 set? None. b=0: candidate=9? Actually 8+1=9. Need sum with bits 8 and 1 set? 9? None. So ans=8, which equals max_sum 8. Good.
But what if max_sum is 9 (1001) and there is also sum 10 (1010). max_sum=10? Actually max_sum would be 10. But if we have sums: 9 and 10. max_sum=10. Greedy: b=3: candidate=8 -> exists? 9 has 8, 10 has 8 -> yes, ans=8. b=2: candidate=12 -> need both bits 8 and 4. 9 has 8, not 4; 10 has 8, not 4. So fails. b=1: candidate=10 -> need bits 8 and 2. 10 has 8 and 2? 10 binary 1010: bits 8 and 2. Yes. So ans=10. So answer =10 = max_sum. Good.
Now if we have sum 9 and 6, max_sum=9. Greedy: b=3:8 -> yes (9 has 8). ans=8. b=2:12 -> fail (9 no 4). b=1:10 -> need 8 and 2; 9 has 8 but not 2; 6 has not 8. fail. b=0:9 -> need 8 and 1; 9 has both, yes. ans=9. So ans= max_sum. So for K=1, it works.
Thus algorithm seems correct.
Now, double-check with K>1 case: Example 1 gave 12, which is not simply the AND of any two sums? Actually it's the maximum AND possible.
Now, potential pitfall: The candidate check for ans|bit requires that there exist at least K sums that have all bits set. However, suppose we set a bit b after setting higher bits. But maybe there is a way to set bit b without having the same set of sums that have the higher bits? That is, the selection of K sums for the candidate may be different from the selection we will eventually use for final answer. But the feasibility condition only requires existence of some K sums that satisfy the candidate mask. In greedy, we only check existence; we don't need to commit to a specific set. So it's fine.
Thus algorithm is correct.
Now, we should implement with careful attention to performance. Possibly we can accelerate counting using bitwise operations and maybe using numpy, but not needed.
One more thought: Since N=1000, M=~500k, and we are doing at most ~40 passes (if max_sum up to 2^40), each pass scanning entire list, maybe 20 million operations, which is fine.
But let's be precise: M = N(N+1)/2 = 1000*1001/2 = 500500. 40 * 500500 = 20,020,000. That's 20 million. Each iteration does a bitwise AND and comparison, and possibly increment count. Python can handle 20 million operations in under 1 second? Possibly around 0.5-1 second. Should be okay.
But we also have to compute the list of sums. That's another 500k operations. So overall fine.
Now, let's think about potential improvements: Instead of scanning entire list for each mask, we could precompute for each subarray sum the bit representation and maybe sort? But not needed.
Edge case: K may be larger than number of subarrays? But constraints say K <= N(N+1)/2, so K <= M.
Now, also note that the sum values could be large; but we only use bitwise operations.
Now, implement.
Pseudo:
def solve():
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
a = list(map(int, input().split()))
pref = [0]*(N+1)
for i in range(N):
pref[i+1] = pref[i] + a[i]
sums = []
for l in range(N):
for r in range(l, N):
sums.append(pref[r+1] - pref[l])
max_sum = max(sums)
max_bit = max_sum.bit_length()
# define function inside to capture sums, K
def ok(mask):
cnt = 0
for s in sums:
if (s & mask) == mask:
cnt += 1
if cnt >= K:
return True
return False
ans = 0
for b in range(max_bit-1, -1, -1):
if ok(ans | (1 << b)):
ans |= (1 << b)
print(ans)
Now test with examples.
Example 1:
N=4 K=2 a=2 5 2 5
pref: [0,2,7,9,14]
sums: as computed
max_sum=14 bit_length=4 -> bits 3..0
b=3: mask=8 -> count>=2? we computed 3 -> ok -> ans=8
b=2: mask=12 -> count>=2? 2 -> ok -> ans=12
b=1: mask=14 -> count? 1 -> not ok
b=0: mask=13 -> count? 0 -> not ok
print 12. OK.
Example 2: We'll trust.
Now, let's consider a tricky test: N=2, a=[1,1], K=2. Subarrays: [1], [2], [1] (indices: (1,1)=1, (1,2)=2, (2,2)=1). So sums: 1,2,1. We need max AND of two sums. Options: pick two 1's => AND=1; pick 2 and 1 => AND=0; pick two same maybe? Actually we have two 1's (two subarrays with sum 1) so we can pick both 1's => AND=1. Could we get AND=2? Need both sums have bit1 set. Only sum 2 has bit1 set; only one sum, so K=2 not possible. So answer=1. Our algorithm: max_sum=2 bit_length=2 bits positions 1,0. ans=0.
b=1: mask=2 -> need at least 2 sums with (s&2)==2. Only sum 2 qualifies -> count=1 -> not ok. So ans stays 0.
b=0: mask=1 -> need at least 2 sums with (s&1)==1. Sums 1,2,1: all have bit0? 1 has bit0=1; 2 has bit0=0 (2 binary 10). So only the two 1's qualify? Actually 2 does not have bit0 set, so only sums 1 and 1 qualify -> count=2 >=2 -> ok -> ans=1.
Print 1. Correct.
Now, another test: N=3, a=[1,2,3], K=3. Subarrays: (1,1)=1,(1,2)=3,(1,3)=6,(2,2)=2,(2,3)=5,(3,3)=3. Sums: 1,3,6,2,5,3. We need max AND of any 3. Let's brute: we want high bits. Which 3 sums have high common bits? Let's compute. Best AND maybe 2? Try sums 6(110), 5(101), 3(011) -> AND=0. Try 6,5,3? same. Try 6,3,3? 6&3&3=2? Actually 6 (110) & 3 (011) = 010 =2, &3 again =2. So AND=2. Can we get AND=4? Need all three sums have bit2 (4) set. Only 6 has bit2? 6 binary 110 has bit2=1 (4), also maybe 5 (101) has bit2=1? 5=101, bit2=1? Actually 5's bits: 4+1, so yes bit2=1 (value 4). 3 (011) does not have bit2. So only two sums have bit2. So cannot. So answer 2. Our algorithm: max_sum=6 bit_length=3 bits 2..0.
ans=0.
b=2 (4): mask=4 -> need at least 3 sums with (s&4)==4. Which sums have bit2? 6 (110) has 4; 5 (101) has 4; maybe others? 3 (011) no; 2 (010) no; 1 (001) no; another 3? There are two 3's? Actually (1,2)=3 and (3,3)=3, both are 3 -> no bit2. So count=2 <3 => not ok.
b=1 (2): mask=2 (since ans=0, candidate=2) -> need at least 3 sums with bit1 set (2). Which sums have bit1? 6 (110) bit1=1; 3 (011) bit1=1; 2 (010) bit1=1; 5 (101) bit1=0; 1 (001) bit1=0; another 3 bit1=1. So sums: 6,3,2,3 -> four sums have bit1=1? Actually check: 6-> yes; 3-> yes; 2-> yes; 5-> no; 1-> no; 3-> yes. So we have 6,3,2,3 => count=4 >=3 => ok -> ans=2.
b=0 (1): candidate=3 (2|1) -> need at least 3 sums with bits 2 and 0? Actually mask=3 (binary 011). Need s &3 ==3, i.e., both bits 1 and 0 set. Which sums have both? 3 (011) has both; also? 5 (101) has bits 4 and 1? Actually 5=101, bits: 4 and 1, not both 1 and 0? 5 has bit0=1, bit1=0, so no. 6=110 has bit1=1, bit0=0. 2=010 has bit1=1, bit0=0. 1=001 has bit0=1, bit1=0. So only the two 3's have both bits? Wait, 3=011, yes both. So count = 2 (<3) => not ok. So final ans=2. Good.
Now, test where K is large: N=3, a=[1,1,1], K=6 (all subarrays). Subarrays: 1,2,3,1,2,1 (actually sums: (1,1)=1,(1,2)=2,(1,3)=3,(2,2)=1,(2,3)=2,(3,3)=1). All sums: [1,2,3,1,2,1]. AND of all =? 1 & 2 =0, etc. Actually compute bitwise AND of all: 1 (01), 2 (10) -> 0, so overall AND=0. So answer 0. Our algorithm: max_sum=3 bit_length=2 bits 1..0.
ans=0.
b=1: mask=2 -> need at least 6 sums with bit1 set. Which sums have bit1? 2 (10) and 3 (11) have bit1? 3=11, yes bit1=1; 2=10, yes; 1=01, no. So counts: sums with bit1: 2,3,2 => three? Actually we have three 2's? Let's list: 1,2,3,1,2,1. That's two 2's? Actually (1,2)=2, (2,3)=2 => two 2's. Plus 3=3. So sums with bit1 set: 2,3,2 => three. But need 6, not enough. So not set.
b=0: mask=1 -> need at least 6 sums with bit0 set. Which sums have bit0? 1,3,1,2? Actually 1 has bit0=1; 2 has bit0=0; 3 has bit0=1; So counts: 1,3,1,1? Let's count: 1 (from (1,1)), 3 (from (1,3)), 1 (from (2,2)), 2 (from (2,3) has 0), 1 (from (3,3)). Also (1,2)=2 has 0. So sums with bit0=1: 1,3,1,1 = four? Actually (1,1)=1, (1,3)=3, (2,2)=1, (3,3)=1 => four. Not 6. So mask=1 fails. So ans=0. Good.
Now, confirm scenario where we might need to consider that the candidate mask might be 0? Not needed.
Thus algorithm works.
Now, consider performance improvements: The possible(mask) function is called many times. Since we have sums as a list, we can maybe convert to a numpy array to speed up, but not necessary.
One concern: The inner loop in possible() might be heavy if we have many masks (like 60). But we can reduce number of masks by breaking early if mask becomes too high? Not needed.
We can also pre-sort sums? Not needed.
Alternative approach: For each bit position, we could compute counts of sums that have that bit set, but we need conjunction of multiple bits. So we need to count sums that have a set of bits set. Could use bitset for each bit? Since N=1000, we have M up to 500k, we could create a boolean array per bit? That would be 40 bits * 500k = 20 million booleans, which is okay. Then for each mask, we need to count number of sums where for all bits in mask, the corresponding boolean is true. That would be an AND of bit vectors. We could use bitset (Python's integers as bitsets) to accelerate? But we only have 500k elements, and 40 masks, so we could precompute for each sum its bitmask of which bits are set (up to 40 bits). Then for each candidate X, we can count how many sums have (bitmask & X) == X. This is same as original check.
We can also pre-filter: For each candidate, we could iterate over sums and test. It's fine.
Now, we might think about memory: storing sums as Python ints is okay.
But one more nuance: The number of bits we test might be more than the bit length of max sum, but we can limit to, say, 60, but we need to ensure that for bits beyond max_sum, candidate will be > max_sum, and condition will fail. But we also have to consider that ans might accumulate bits beyond max_sum? It won't because if no sum has that bit, we cannot set it. So ans will never exceed max_sum. So we can start from, say, 60 down to 0; but that will do 61 checks, each scanning 500k sums. That's about 30.5 million checks. Might be okay but if time limit is strict, we can reduce to max_bit (maybe 40). So I'll use max_bit.
Now, what if max_sum is 0? Not possible. But just in case, handle.
Now, we should consider that a_i can be up to 1e9, sum up to 1e12, so bit length at most 40. Actually 2^40 = 1.0995e12, so bit length <= 40. So at most 40 bits.
Thus 40 * 500k = 20M checks.
Now, we can micro-opt: In possible(mask), we can store sums as a list of ints, and do for s in sums: if s & mask == mask: cnt += 1; if cnt >= K: return True. This is straightforward.
Potential micro-optimizations:
- Use local variable for sums and K inside function to avoid global lookups.
- Use a while loop or for loop with local variables bound to local scope.
- Possibly use list comprehension with sum? That would compute entire count, but we can early exit. So better to loop.
I think it's fine.
Now, let's also consider the possibility that K can be as high as M, and the mask may be high. The loop may go through all sums many times. But 20M is okay.
Now, confirm with worst-case N=1000, M=500500, max_bit maybe 40, so 40*500500 = 20,020,000 iterations. Each iteration: bitwise AND, equality compare, increment, condition check. In CP, Python can handle ~50 million simple operations per second? Actually typical Python does about 30-50 million integer ops per second? Not exactly; but 20 million should be within 1 second. However, if we have 60 bits, it's 30 million. Still okay.
But we must also account for creating the sums list: double loop with 500k iterations, each computing sum via pref subtraction, which is also some operations. That's another 0.5 million. So total maybe 20-30 million operations, which is okay.
Now, let's think about potential improvements: Instead of storing all sums, we can count on the fly for each mask, but then we would recompute sums each time. That would be 40 * 500k = same 20M sum computations, but each sum computation requires two array accesses (pref[r+1] and pref[l]), which may be slightly slower than just fetching a precomputed int. So storing sums is better.
Now, check memory: 500k ints, each maybe 28 bytes -> 14 MB, plus list overhead 4 MB, total ~18 MB, fine.
Now, one more nuance: The input size is small.
Now, code.
We'll define solve() and call it.
Now, consider edge case: K=0? But constraints say K>=1, so ignore.
Now, test with random small N to verify with brute force for sanity.
We could write a brute for N small (N<=8) to check. But not now.
Now, let's consider an alternative approach: Use DP to compute counts per mask? But not needed.
Now, finalize code.
We'll include fast I/O.
Potential Pitfall: The bit length of max_sum might be 0 if all a_i are 0? But a_i >=1, so at least one positive, sum>=1, so bit_length>=1.
Now, code:
import sys
def solve():
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
a = list(map(int, input().split()))
pref = [0] * (N+1)
for i, val in enumerate(a):
pref[i+1] = pref[i] + val
sums = []
for l in range(N):
# use