We need to count number of pairs (i,j), i<j such that Hamming distance between ai and aj is exactly k. n up to 1e5, ai up to 10000, which fits within 14 bits? 10000 ~ 10011100010000, actually 14 bits (2^14 = 16384). Also k <=14. So the values are limited to 0..10000, but could be up to 10000. However note that input constraint says ai <= 10000, so max 10000 < 2^14. However some numbers might be up to 16383? Actually 0 ≤ ai ≤ 10^4, so max is 10000, so 14 bits enough. But we should consider that Hamming distance is defined on binary representation presumably with leading zeros to some fixed length? Usually, for such problems, they consider binary representation of numbers up to some maximum bits, but since numbers are small, we can just compute bitwise XOR and count bits. Since k up to 14, and values up to 10000, we can compute popcount of XOR.
A naive O(n^2) is too slow. We need to count pairs with Hamming distance exactly k. With n up to 100k, and ai values limited to at most 2^14 distinct values? Actually the range is 0..10000, so at most 10001 distinct values. So we can compress frequencies. Then for each distinct value x, we need to count number of y such that popcount(x xor y) = k, and sum over x<y? Actually pairs (i,j) with i<j. With frequencies f[x], the number of unordered pairs between distinct values x and y is f[x] * f[y], and for same value x, it's C(f[x],2) if k=0 (since popcount(x xor x)=0). If k>0, same value doesn't contribute because xor=0, popcount=0 ≠ k (unless k=0). So we can solve by iterating over all distinct values (max about 10001) and for each value x, we need to sum over y where popcount(x xor y)=k, but careful to avoid double counting: we can sum for each x, then for each y > x? But if we just do for each x, sum over all y (including x) with condition, then we'd double count unordered pairs. We can either compute for each x, accumulate f[x] * sum_{y: popcount(x xor y)=k} f[y] and then divide by 2, because each pair counted twice. However if we include y=x, then that contributes f[x]*f[x] which is fine for k=0? Actually for k>0, y=x would not satisfy condition (popcount=0). So we can simply compute total = 0.5 * sum_x f[x] * (sum_{y: popcount(x xor y)=k} f[y]), but careful: for x=y case, if k=0, it satisfies; then sum includes f[x]*f[x] = f[x]^2, which would count ordered pairs (i,j) with i and j possibly same? But we need unordered pairs with i<j. For ordered pairs, if we sum over all (i,j) with i != j? Actually we want unordered pairs i<j. The expression 0.5 * sum_{x} sum_{y} f[x] f[y] * indicator(popcount(x xor y)=k) would give the number of unordered pairs if we consider (x,y) distinct? Wait: For each unordered pair of distinct values x != y, this counts f[x]f[y] twice (once when x is the outer, y is inner, and once when y is outer, x inner). So dividing by 2 yields f[x]f[y] for each unordered distinct pair. For x=y, the term appears only once (when x outer and y inner, with y=x). But we are summing over all x and all y (including x). For x=y, the product f[x] f[x] = f[x]^2. This counts ordered pairs of indices (i,j) with i and j from the same value. But we only want unordered pairs i<j, which is C(f[x],2) = fx/2. Our expression 0.5 * f[x]^2 gives f[x]^2/2, which is too high by f[x]/2. So for the case k=0 and x=y, we need to adjust. But we can avoid this by only considering y with popcount(x xor y)=k and y != x if k>0? For k=0, the condition includes x=y. Then we can compute total = sum_{x<y, popcount(x xor y)=0? Actually popcount(x xor y)=0 only if x=y, so only same values. So for k=0, the answer is sum_x C(f[x],2). So we can handle k=0 separately.
Alternatively, we can use inclusion: For each x, we need sum over y (including possibly x) such that popcount(x xor y)=k. But we can compute count = sum_x f[x] * cnt[x] where cnt[x] = sum_{y: popcount(x xor y)=k} f[y]. Then answer = (count - (if k==0? something else? ) )/2? Let's examine.
If we compute count = Σ_x f[x] * Σ_y f[y] * I(popcount(x xor y)=k). This counts ordered pairs (x,y) where x and y refer to values, weighted by frequencies. More precisely, it's Σ_{i} Σ_{j} I(popcount(ai xor aj)=k) over all i,j (including i=j). Because each ai corresponds to a value x, each aj to value y. So count = Σ_{i=1..n} Σ_{j=1..n} I(popcount(ai xor aj)=k). That includes i=j pairs. For i=j, popcount(ai xor ai)=0, so they are counted only if k=0. So count includes n additional terms when k=0 (since each i=j contributes 1). For k>0, i=j does not contribute. Now the number of unordered pairs i<j we need is = (count - extra)/2, where extra is the number of ordered pairs (i,i) counted (i=j) if any, because we want i0, extra=0. For k=0, extra = n (since each i=j contributes 1). So answer = (count - (k==0 ? n : 0)) / 2.
That seems correct: For k=0, count = Σ_i Σ_j I(ai=aj). This equals Σ_x f[x]^2. Then answer = (Σ_x f[x]^2 - n)/2 = Σ_x (f[x]^2 - f[x])/2 = Σ_x C(f[x],2). Good.
So we need to compute count = Σ_i Σ_j I(popcount(ai xor aj)=k) efficiently.
We have n up to 1e5, but values domain small (0..10000). However n is large, but the number of distinct values is at most 10001. So we can compute the frequency array f of size M = max possible value + 1. Since ai ≤ 10000, we can set M = 10001? Actually 0..10000 inclusive => 10001 values. But careful: Could there be values > 10000? The constraint says 0 ≤ ai ≤ 10^4, so yes up to 10000. So M = 10001 is fine. But wait, the XOR and Hamming distance computed on binary representation? Usually, numbers are represented in binary without leading zeros, but they said "binary representation differs exactly in k bits". Usually, we consider their representation up to a common length? For example, x=5 (101) and y=3 (011) differ in two bits if we align them as 3-bit numbers. However, if one number has more bits, then leading zeros matter. For example, 4 (100) and 1 (001) differ in two bits if we consider same number of bits? 4 in 3-bit is 100, 1 is 001 -> differ in two bits. But if we consider minimal representation, 1 is '1' and 4 is '100', then to compare we need to align to the same length, typically by considering a fixed number of bits (like up to maximum value). Since max value is 10000 (< 2^14), we can consider all numbers represented with 14 bits (since 2^14 = 16384 > 10000). So we should use a fixed bit-length L such that all numbers fit. The natural choice: since k <= 14 and ai ≤ 10000 < 2^14, L = 14 suffices. But is it guaranteed that the Hamming distance computed with L=14 bits matches the problem's definition? Usually, they mean you write numbers in binary without extra leading zeros except to have same length? Let's check example: 5=101, 3=011 differ exactly in two bits. That suggests they used 3 bits because both numbers are less than 8. If one number had more bits, they'd pad with zeros to match the length of the larger number? Actually for 5 and 3, max is 5 (101) so they likely used 3 bits for both. If numbers were 5 (101) and 2 (10), they'd likely write 5 as 101, 2 as 010, difference in two bits? Let's test: 5 (101) and 2 (010) differ in all three bits? Actually 101 vs 010 -> bits: 1 vs 0 diff, 0 vs 1 diff, 1 vs 0 diff: three differences. But if we used minimal length, 5 is 101, 2 is 10, then aligning right: 101 vs 010? That would be padding with leading zero to 2 -> 010? Actually aligning to the larger length, we pad the smaller with zeros on the left. That's typical. So using a fixed bit length (like 14) is fine as long as it's at least the maximum bit length needed. Since k ≤ 14, even if numbers use fewer bits, leading zeros are considered as zeros. So we can define L = 14 (or maybe 15? 2^14=16384, 10000 fits, so bits 0..13? Actually 2^13=8192, 2^14=16384, so numbers up to 10000 need 14 bits (bits 13 down to 0). Since 10000 in binary: 10011100010000, that's 14 bits (positions 13 to 0). So L = 14 is enough. But careful: k can be up to 14, which includes the possibility of differing in all bits. So we need to represent numbers with L bits, where L >= max bits of any number. Could numbers be exactly 16383? No, max 10000. So L=14 is safe.
Alternatively, we could compute popcount(xor) directly using built-in functions on integers; since integers are 32-bit, popcount(xor) will count bits in the full 32-bit representation, which includes leading zeros? Actually popcount(xor) counts the number of 1 bits in the XOR result. The XOR of two numbers, say 5 (101) and 3 (011) gives 110 (6), popcount(6)=2. That matches. For 4 (100) and 1 (1) -> XOR = 101 (5), popcount(5)=2? Actually 4 ^ 1 = 5 (101) -> popcount=2. So indeed, popcount(xor) counts bits in the XOR, which is the same as Hamming distance if we consider the numbers represented in binary with no leading zeros? Wait, is it always? For 2 (10) and 1 (1), XOR = 3 (11), popcount(3)=2. But what is the Hamming distance between 2 and 1? If we write 2 as "10" and 1 as "01" (with leading zero to match length 2), they differ in both bits: that's 2. So popcount(xor) gives the Hamming distance when we consider the numbers represented without leading zeros? Actually, if we take XOR, the bits where they differ are exactly the bits set in xor. However, if one number has more bits, the bits in the higher positions of the larger number are compared to 0 for the smaller number? Because the smaller number, when expressed in the same number of bits, has leading zeros. The XOR operation automatically includes those leading zeros because the smaller number's higher bits are zero. For example, 4 (100) and 1 (001) -> 4 ^ 1 = 101, popcount=2. So yes, XOR's popcount yields the number of differing bits when numbers are considered with infinite leading zeros. That's the common definition. So we can simply compute popcount(ai ^ aj). So no need to fix length.
Thus we need to compute count = Σ_i Σ_j [popcount(ai ^ aj) = k].
Since values domain is up to 10000, but n up to 100k, we can use a frequency array freq of size maybe 2^14? Actually max value is 10000, but XOR of two numbers can be up to ~16383? Since max ai is 10000, xor of two 10000 numbers is up to maybe 16383? Actually 10000 in binary is 10011100010000. The maximum xor of two numbers <= 10000 is when they have complementary bits; e.g., 10000 (0b10011100010000) and its bitwise complement within 14 bits (0b01100011101111) = 16383? That's > 10000. But both numbers must be ≤ 10000, so can we have such a complement? The complement of 10000 within 14 bits is 16383 - 10000? Actually 2^14 - 1 = 16383. 16383 xor 10000 = (16383 - 10000?) Wait, xor of a number and its bitwise complement is all ones = 16383. But is the complement ≤10000? The complement of 10000 (within 14 bits) is 16383 - 10000 = 6383? Actually complement of x in L bits is (2^L - 1) ^ x = (2^L - 1) - x? Not exactly subtraction; but (2^L -1) ^ x = (2^L -1) - x if x has no overlapping? Actually for L-bit numbers, the bitwise complement of x is (~x) & ((1<<L)-1) = (2^L -1) ^ x = (2^L -1) - x? This is true only if there is no borrow? Actually (2^L -1) - x = bitwise NOT of x in L bits? Let's check with L=3: 2^3-1=7. 7 - x: if x=5 (101), 7-5=2 (010) which is complement of 5 (010). Yes, it works because subtraction with all ones yields complement. In binary, subtracting from all ones yields bitwise complement. So complement of x is (2^L -1) - x. So if L=14, complement = 16383 - x. So for x=10000, complement = 6383, which is ≤10000. So indeed both numbers can be ≤10000? 6383 ≤ 10000, so we can have both numbers in the set. XOR = 16383, popcount = 14. So XOR values can go up to 16383. So the domain of values is 0..10000, but XOR of two values can be up to 16383 (which is less than 2^14). So the space of possible XOR values is up to 16383, which is about 16384. That's manageable. So we could use a frequency array of size 1<<14? Actually 2^14 = 16384. That is small! Because numbers are up to 10000, but the bit length needed is 14, but numbers themselves could be up to 16383? No, numbers are ≤ 10000, but we can still consider the universe as 0..16383 (2^14). However numbers only appear in the lower 10001 values, but we could still treat freq array of size 16384 (2^14). That is also small (16384). Then we can compute count by iterating over all pairs of values (x,y) in the frequency array? There are 16384^2 ≈ 268 million, which might be borderline but possibly acceptable with optimizations? 268M operations is a bit high for 1 second in Python, but we can try to optimize using convolution-like techniques? However note that n is up to 1e5 but values domain small. 2^14 = 16384, iterating over all pairs x,y would be about 268 million, which in Python might be too slow (but maybe with early exit and using numpy? but not allowed). We need something more clever.
We can treat the problem as: count pairs (x,y) with frequencies f[x], f[y] such that popcount(x ^ y) = k. Since k is small (≤14) and L=14, we could iterate over x, and for each x, iterate over all y such that popcount(x ^ y) = k. The number of y with popcount(x ^ y)=k is C(L, k) if we consider all numbers in the full space of L bits? Actually for a fixed x, the set {y: popcount(x ^ y) = k} are exactly numbers y obtained by flipping exactly k bits of x (in L-bit representation). There are C(L, k) such y. Since L=14 and k up to 14, C(14, k) maximum when k=7 => about 3432. That's not huge. And we have up to 16384 possible x values (but many have f[x]=0). However we only have at most 10001 distinct values with f[x]>0. So if we iterate over each x that appears (f[x]>0), and for each such x, iterate over all y that can be obtained by flipping exactly k bits of x (which are at most C(14, k) <= 3432). Then we can compute contributions f[x] * f[y] (with y possibly same as x if k=0). But careful: when k=0, flipping 0 bits gives y = x, and C(14,0)=1. So for k>0, y != x. So that would count ordered pairs (x,y) with condition? Let's see: For each x, we consider all y in the set S_k(x) = {y: popcount(x^y)=k}. Then sum over x f[x] * sum_{y in S_k(x)} f[y] yields count of ordered pairs (i,j) where ai = x, aj = y and condition holds. This is exactly count, because for each x we consider all y, including possibly y = x if k=0. So we can compute count = Σ_{x: f[x]>0} f[x] * ( Σ_{y ∈ S_k(x)} f[y] ). However note that if we iterate over all x (even with f[x]=0, we don't need). For each x, we need to sum f[y] for y that are at Hamming distance k. But we have to ensure we consider all y, including those that might not appear? If y doesn't appear, f[y]=0, so it's fine. So we can compute by iterating over x in the set of values that appear, and for each such x, iterate over all combinations of flipping k bits among L bits. But L = number of bits needed? Since we need to consider all bits up to? If we use L=14, then numbers are represented with 14 bits. However what about numbers that have higher bits? They don't, because max is 10000 < 2^14. But if we treat numbers as 14-bit, flipping bits beyond the 14th? Actually 14 bits cover 0..16383. That's sufficient. But note: What if some numbers have a 1 in bit 14? Not possible because max 10000 < 2^14. So 14 bits are enough. However we need to decide which L to use. Since k ≤ 14, we could use L = 14 (or maybe 15 to be safe? 2^15=32768, but then C(15,7)=6435, bigger). The problem constraints: ai ≤ 10^4 = 10000, which is less than 2^14. So we can safely use 14 bits. But wait, what about numbers like 0? That's fine. So the Hamming distance on 14 bits matches the XOR popcount. However, is it guaranteed that popcount(xor) on 32-bit integers yields the same as flipping exactly k bits on a representation with some length? Since xor counts bits, flipping bits beyond the most significant bit (leading zeros) doesn't matter because they are zeros. So if we restrict to 14 bits, flipping bits only within those 14 bits covers all differences, because any higher bits are zero for both numbers. But is it possible that two numbers have a differing bit above 13? For example, consider numbers 0 and 16384? But 16384 is >10000, so not in input. So no.
Thus we can use L=14. But we need to verify that the XOR of two numbers that are both ≤10000 can have a 1 in bit 13 (since 2^13=8192) and also maybe bit 14? 2^14=16384. Since max is 10000, bit 14 (value 16384) is not set in any number, but XOR could set bit 14 if one number has bit 14=1? Neither has it, so XOR cannot have bit 14=1. Actually XOR's bits are set only if one number has 1 and the other 0. Since both numbers have 0 in bit 14, XOR will have 0. So the highest possible bit is 13 (8192). So we could use L=14, which includes bit 13 (value 8192) and also bit 14? Actually 14 bits would have bits indexed 0 to 13. Wait, "14 bits" means bits positions 0..13. The highest value is 2^13=8192, 2^14-1=16383. So bit 13 is the 14th bit (counting from 0). So indeed numbers up to 10000 may have bit 13 set? 10000 in binary: let's compute: 8192 (2^13) is 8192, remainder 1808; 2^11=2048 is >1808? Actually 2^11=2048 >1808, so bit 12? Let's do properly: 2^13 = 8192, 2^12=4096, 2^11=2048, 2^10=1024, 2^9=512, 2^8=256, 2^7=128, 2^6=64, 2^5=32, 2^4=16, 2^3=8, 2^2=4, 2^1=2, 2^0=1. 10000 - 8192 = 1808. 1808 - 1024 = 784 (since 2048 > 1808, skip bit 11? Actually bit 11 is 2048, >1808, so bit 11=0. Then bit 10=1024 <= 1808, subtract -> 784. Next bit 9=512 <=784, subtract ->272, bit 9=1. Next bit 8=256 <=272, subtract->16, bit 8=1. Next bit 7=128 >16? 128>16 so bit 7=0. bit 6=64>16 ->0; bit 5=32>16 ->0; bit 4=16 <=16 subtract->0, bit4=1; bits 3,2,1,0=0. So binary: bits: 13:1,12:0? Actually we didn't check bit 12: 2^12=4096, >1808, so bit 12=0. So representation: bit13=1, bit12=0, bit11=0, bit10=1, bit9=1, bit8=1, bit7=0, bit6=0, bit5=0, bit4=1, bit3=0, bit2=0, bit1=0, bit0=0. That is 14 bits (positions 13 down to 0). So indeed bit 13 is set. So we need to include bit 13 (i.e., 14 bits). So L=14.
Thus we can generate all numbers up to (1<<L)-1 = 16383. But we only need to consider those that appear? For each x that appears, we want to iterate over all y obtained by flipping exactly k bits in the L-bit representation of x. That set includes numbers that may be outside the range 0..10000? Actually flipping bits could produce numbers up to 16383, which is okay because frequencies for those numbers are 0 (since not in input). But we still need to consider them? No, because f[y]=0, so we can skip. However we can still generate all y values; checking f[y] and summing will be fine. But generating all y for each x could include many y that don't appear. However we still have to iterate over them. But number of y per x is C(14,k). The maximum C(14,7) = 3432. If we have up to 10001 distinct x values, that's about 10001 * 3432 ≈ 34 million operations, which is feasible in Python if optimized? 34 million maybe okay with simple integer operations, but we need to also compute indices, retrieve f[y] from a dictionary or array, etc. 34 million is borderline but might pass within 1-2 seconds in PyPy? Let's estimate: 34 million integer operations and dictionary lookups? If we use a list of size 16384 for freq, then f[y] is O(1) indexing. So we can have freq array of length 1<<14. Then for each x with freq[x] > 0 (at most 10001), for each combination of k bits, compute y = x ^ mask, where mask is the combination of bits (i.e., an integer with exactly k bits set). Then sum += freq[x] * freq[y]. But careful: This would count each ordered pair (i,j) exactly once? For each x, we iterate over y that satisfy condition. That yields count = Σ_x f[x] * Σ_y∈S_k(x) f[y]. That's exactly the ordered pairs count (including i=j if k=0). So then answer = (count - (k==0? n:0))/2. However we must be careful about double counting due to x and y both having freq>0 and the same condition when we later process y as outer x? That's fine because it's ordered pairs. So our method gives count directly.
Complexity: For each x with freq>0, we need to generate all masks with exactly k bits set among L bits. Number of masks = C(L, k). For each mask, compute y = x ^ mask, and add freq[x] * freq[y] to count. That yields count. However note that when we iterate over all such masks, we include the mask=0 if k=0. For k=0, there's only one mask (0), giving y=x. That's correct.
But there is a subtlety: For k>0, we are summing over all y such that popcount(x^y)=k. But note that for each unordered pair (x,y), this condition holds both ways. So in count we get f[x]f[y] + f[y]f[x] = 2 f[x]f[y]? Wait, in our sum, when we process x, we add f[x] * f[y]. Later when we process y (if y also appears), we will add f[y] * f[x] as well. So indeed each unordered pair contributes twice, which is correct for ordered pairs count (since i and j order). So final answer = (count - (k==0? n:0))/2. So that's fine.
Now we need to generate all masks with exactly k bits set among L bits. L=14. We can precompute all masks for given k. Since k can vary (given per test case), we need to generate masks for that k. There are at most C(14,k) masks, maximum 3432. That's fine.
So algorithm:
- Read n, k.
- Read array a.
- Determine L = 14? But careful: Could the numbers require more bits because of k? Actually k ≤ 14. However if numbers are all small, say up to 7 (3 bits) and k = 5, then flipping 5 bits among L bits? If we set L=14, flipping bits that are beyond the original's highest bit could still produce y that are within 0..16383. But those y would be considered? But does the Hamming distance include those higher bits? Since the numbers are represented with infinite leading zeros, those higher bits are 0 for both numbers. If we flip a higher bit (say bit 13) of x (which is 0), we get y with that bit 1. Then popcount(x^y) would include that bit, indeed it differs. So if we consider x with value 1 (binary ...0001) and we flip bit 13, then y = 1 ^ (1<<13) = 8193. The Hamming distance between 1 and 8193 is 2? Actually 1 (000...0001) and 8193 (1000...0001) differ only in bit13? They differ in one bit? Actually bit13: 0 vs 1 => diff; other bits same? Wait, 1 in 14-bit: 00000000000001; 8193 is 10000000000001 -> two ones? That's two bits? Actually 8193 in binary 14-bit: bit13=1, bit0=1, others 0. So XOR = 10000000000000? Actually 1 ^ 8193 = 8192? Let's compute: 1 (0b00000000000001) ^ 8193 (0b10000000000001) = 0b10000000000000 = 8192. Popcount(8192)=1. So they differ in exactly 1 bit? Wait, 1 and 8193 have bits: bit13: 0 vs 1 (diff), bit0: 1 vs 1 (same). So they differ in 1 bit. So flipping bit 13 of 1 yields Hamming distance 1. So that is valid.
But what about the condition that the Hamming distance must be exactly k? If we consider all bits up to L, flipping any of the L bits will create a difference. So for a given x, the set of y at Hamming distance exactly k includes those where we flip exactly k bits among the L bits (including those that are zero in both original numbers). That matches the Hamming distance computed on infinite leading zeros (or fixed-width L bits). So L should be large enough to cover all bits that might be toggled. Since numbers are at most 10000, which is less than 2^14, the bits beyond 13 are zero for all numbers. But if we set L=14, we include bits 0..13. That's enough. However, could there be any effect if k > number of bits needed? For example, suppose all numbers are small, e.g., max 7 (3 bits), and k=5. Then to have Hamming distance 5, you need to flip 5 bits. Since numbers have zeros in higher bits, flipping those zeros to ones yields differences. So indeed there could be pairs with distance 5, such as x=0 (0000..0) and y having exactly 5 bits set (like some number with 5 ones). Since y could be up to 16383, but is that allowed? As long as y appears in the input. But if all numbers are ≤7, then numbers with high bits set won't appear. So such pairs may not exist. But that's fine.
Thus using L=14 is correct.
But we must be careful: If numbers could be up to 10000, we might need to consider bits up to 13 (since 2^13=8192, 2^14=16384 > 10000). However, numbers like 10000 have bit 13 set. So L must be at least 14. If we set L=14, the highest bit index is 13. That's fine.
But what about numbers that have value exactly 16383? Not in input. So we can safely use L=14.
Now, one potential optimization: Instead of iterating over all x with freq>0 and for each generating all masks, we could use FWT (Fast Walsh-Hadamard Transform) or convolution to compute count = Σ f[x] * (f * something)? Actually this is like: count = Σ_{i,j} f[i] f[j] [popcount(i^j)=k]. This can be computed by convolving frequency with itself under Hamming distance. There is known technique: using Walsh-Hadamard transform for XOR convolution, but with popcount condition? For each possible XOR value z, we can compute how many pairs have i^j = z, which is (f xor-convolution with f)[z] = Σ_{i} f[i] f[i^z]. Then count = Σ_{z: popcount(z)=k} (f xor-convolution)[z]. So we can compute the XOR convolution via FWHT in O(L * 2^L) time. L=14 => 2^L=16384, L2^L = 1416384 ≈ 229k operations, which is very fast. Then for each z with popcount(z)=k, sum up conv[z]. But careful: conv[z] = Σ_i f[i] f[i^z]. This counts ordered pairs? Actually (i,j) such that ai = i_val, aj = j_val and i_val ^ j_val = z. That counts each unordered pair (i,j) twice? Let's check: For a fixed z, if we sum over i of f[i] f[i^z], this counts each pair (x, y) where x^y = z. For each unordered pair (x,y) with x^y = z, there will be two contributions? When i = x, i^z = y, yields f[x]f[y]; when i = y (since y^z = x because y^z = y^(x^y) = x), yields f[y]f[x] = f[x]f[y]. So conv[z] = 2 * Σ_{x<y, x^y=z} f[x]f[y] + if z=0, then i^z = i, so conv[0] = Σ_i f[i] f[i] = Σ_i f[i]^2, which counts ordered pairs? Actually for z=0, i^0 = i, so conv[0] = Σ_i f[i] f[i] = Σ_i f[i]^2. That includes i=j. So conv[z] for z>0 is 2 * Σ_{x<y, x^y=z} f[x]f[y]. For z=0, conv[0] = Σ_i f[i]^2. So then count of ordered pairs (i,j) with popcount(ai^aj)=k would be: if k=0, we need only pairs with xor=0, i.e., z=0, and count ordered pairs = conv[0]. If k>0, we need for all z with popcount(z)=k, ordered pairs = conv[z]. But careful: For k>0, does conv[z] already count ordered pairs? Yes, because for each such z, conv[z] counts ordered pairs (i,j) where ai^aj = z. Since z != 0, conv[z] = 2 * (unordered product sum). That's exactly the number of ordered pairs (including both orders). So the total count = Σ_{z: popcount(z)=k} conv[z] for k>0. For k=0, it's conv[0].
But note: conv[0] includes i=j ordered pairs (self-pairs). For our count of ordered pairs (i,j) we want all ordered pairs including i=j? Our earlier definition of count = Σ_i Σ_j [popcount(ai^aj)=k] includes i=j if k=0. So conv[0] exactly matches that for k=0 (since popcount(0)=0). For k>0, conv[z] for nonzero z does not include i=j because then xor=0. So conv[z] is the ordered pairs count (i,j) with i^j = z. So we can compute total ordered pairs count as:
if k == 0: count = conv[0]
else: count = sum_{z: popcount(z)=k} conv[z]
Then answer = (count - (k==0? n:0)) / 2.
Now, we need to compute conv = f XOR convolution with f: conv[z] = Σ_i f[i] f[i^z]. That's essentially the autocorrelation under XOR. This can be computed via FWHT: If we let F = FWHT(f), then G = F^2 elementwise, then conv = inverse FWHT(G) / N? Actually the XOR convolution defined as (f * g)[k] = Σ_i f[i] g[i^k]. If we want (f XOR f)[z], we can compute: Compute FWHT of f (size N=2^L). Then let H = F * F (elementwise product). Then inverse FWHT gives conv. Since FWHT is its own inverse up to factor 1/N (depending on normalization). Typically, with Walsh-Hadamard Transform (for XOR), if we define transform as: For each step, for each pair (a, b), a' = a + b, b' = a - b (or a-b). Then after transform, convolution: (f * g)[k] = invFWHT( FWHT(f) * FWHT(g) ) / N. So we need to be careful with normalization.
Alternatively, we can compute conv by brute force: Since size is only 16384, we could compute conv[z] directly by iterating over all i (0..16383) and adding f[i] * f[i^z]. That's O(2^L * 2^L) = 268M if done naively. But we can compute conv using FWHT in O(L * 2^L) which is much faster.
Given L=14, 2^L=16384, we can easily implement FWHT in Python. It's straightforward: In-place transform with loops. 16384 is small; the transform will be fast. Then we compute elementwise square, then inverse transform. We need to be careful with integer overflow? f values up to 1e5, square up to 1e10, sum up to maybe 1e10 * 16384? Actually conv[z] can be as large as n^2 = 1e10, which fits in 64-bit (python int unlimited). So fine.
Thus the FWHT method seems efficient and simpler than iterating over all x and masks (which might be up to 34M). Actually 34M is also fine, but FWHT is more elegant and likely faster.
Let's compute both complexities:
Option 1: For each x with freq>0 (<=10001), for each mask (<=3432), do y = x ^ mask; count += freq[x] * freq[y]. That's at most 34 million operations (multiplications, array access). In Python, 34 million may be okay, but we have to be careful about loops overhead. But 34M is possibly acceptable in PyPy (2-3 seconds). However we also need to handle the case k=0 separately (since mask set only contains 0, that would be cheap). Also we need to precompute all masks with exactly k bits set. That can be done by generating all integers from 0 to (1<<L)-1 and checking popcount, or using combinatorial generation. But generating all masks with exactly k bits set can be done using itertools.combinations. That's fine.
Option 2: FWHT: O(L * 2^L) ≈ 14*16384 = 229,376 operations plus some multiplications. That's extremely fast. Also we need to compute popcount for each z to sum conv[z] for those with popcount(z)=k, which is O(2^L) = 16384, trivial. So FWHT is much more efficient and simpler to code, especially with small 2^L.
Thus I'll go with FWHT.
Implementation details:
- Determine L. Since max(ai) ≤ 10000, but we need to consider bits up to maybe 13? But we need to include all bits that could affect popcount up to k (which is ≤14). If we set L = 14, we need to ensure that numbers' binary representation fits within L bits. But what about numbers like 0? fine. However, if numbers could be up to 10000, the maximum bit index needed is floor(log2(10000)) = 13. So L = 14 includes bits 0..13. But is it possible that two numbers differ in bit 14? Since both have 0 in bit 14, they don't differ. So it's fine. But what about k=14? To have popcount(xor)=14, we need xor to have 14 bits set. Since xor can have at most 14 bits if we consider up to bit 13? Actually there are 14 bits in positions 0..13, so max popcount is 14. So xor could have all 14 bits set. That requires numbers to be complements within 14 bits: x ^ y = 2^14 -1 = 16383. Since both x and y ≤ 10000, can we have such pair? For example, x=0 (000...0) and y=16383? But y=16383 is >10000, so not allowed. But we need both numbers ≤10000. As we saw, complement of 10000 is 6383, and 10000 ^ 6383 = 16383 (popcount 14). So both are ≤10000. So yes, it's possible. So L=14 is enough.
But is there any scenario where XOR could have a 1 in bit 14? For that, one of the numbers must have bit 14=1, i.e., >=16384. Not possible. So we can set L=14.
We need to ensure that the FWHT covers all possible values from 0 to 2^L -1. So we'll create array F of length N = 1 << L, where L = 14, N = 16384. Then for each ai, increment F[ai]. Note: Since ai ≤ 10000, which is less than N, we can directly use F[ai] as index.
Now compute the XOR convolution of F with itself: conv[z] = Σ_i F[i] * F[i ^ z]. The FWHT procedure:
Define function fwht(a, invert=False):
n = len(a)
step = 1
while step < n:
for i in range(0, n, step*2):
for j in range(i, i+step):
u = a[j]
v = a[j+step]
a[j] = u + v
a[j+step] = u - v
step <<= 1
if invert:
for i in range(n):
a[i] //= n # Since using integer arithmetic, we need to divide by n after inverse. Because after forward transform, the inverse would have division by n. Actually in many implementations, they do not divide in forward, then in inverse they divide by n. But we need to be careful: The convolution result is obtained by: transform both, multiply pointwise, then inverse transform and divide by n. However if we only have one array, we need to square the transformed array, then inverse transform and divide by n. So steps:
- Copy F into array A of length N.
- Do fwht(A) (forward transform).
- For i in range(N): A[i] = A[i] * A[i] (this gives FWT of convolution).
- Do fwht(A, invert=True) (which includes dividing each element by N).
- Then A[z] = conv[z] (the convolution result).
But we have to ensure that the forward transform is the same as used for convolution. There are different conventions. Let's derive.
The XOR convolution using Walsh-Hadamard transform:
Given two vectors a and b of length N (power of two), define their XOR convolution c where c[k] = Σ_i a[i] * b[i ^ k].
The transform is: For each step, do for pairs: x = a[i], y = a[i+len/2]; a[i] = x+y; a[i+len/2] = x-y.
After applying this transform to a and b separately, we get A = FWHT(a), B = FWHT(b). Then pointwise multiply C = A * B. Then apply inverse transform: which is same as forward transform (since it's its own inverse up to scaling) and then divide each element by N. So indeed, after forward transform, we can compute C = A * A, then apply forward transform again? Actually the inverse transform is the same as forward? For the XOR Walsh-Hadamard, the transform matrix is orthogonal up to factor 1/N: H * H = N * I. So applying the transform twice gives the original scaled by N. More precisely: If we apply transform T (without scaling), then applying T again yields the original vector multiplied by N. So the inverse transform is T / N. So if we do T once, then multiply pointwise, then do T again, we get N * c. Actually let's check:
We have a, b. Compute A = T(a), B = T(b). Then C = A * B (elementwise). Then compute c' = T(C). Then c = c' / N. That's the convolution.
Alternatively, we can do: A = T(a), then A[i] = A[i] * A[i], then apply T again, then divide by N. That yields c = T( (T(a))^2 ) / N.
So implementation:
def fwht(a):
n = len(a)
step = 1
while step < n:
for i in range(0, n, step*2):
for j in range(i, i+step):
x = a[j]
y = a[j+step]
a[j] = x + y
a[j+step] = x - y
step <<= 1
Now, if we call fwht(A) to get transform, then square, then call fwht(A) again (which applies transform again), then for i in range(n): A[i] //= n. This yields convolution.
But careful: The second fwht will produce N * c, so we need to divide by N. Since we're using integer division, but convolution values are integers? They should be integers because it's sum of products. Dividing by N should give integer? Let's test with small N: N=2. Suppose a = [1,2]. Convolution c: c[0]=11+22=5; c[1]=12+21=4. Now compute fwht: a = [1,2] -> step=1: for i=0: x=1,y=2 => a[0]=3,a[1]=-1. So A = [3,-1]. Square: [9,1]. Apply fwht again: step=1: x=9,y=1 => a[0]=10,a[1]=8. Then divide by N=2: [5,4] matches. So integer division works because result is divisible. In general, because the convolution yields integer and the transform with these operations yields multiples of N, dividing by N yields integer. In Python integer division is fine.
Thus we can use fwht, square, fwht, divide by N.
Now, after obtaining conv array, we compute count_ordered = sum(conv[z] for z in range(N) if popcount(z) == k). But for k=0, only z=0 contributes? Actually popcount(0)=0, so yes.
But we must be careful: conv[z] as computed includes both ordered pairs (i,j) with i^j = z. For k=0, conv[0] includes i=j pairs. So count_ordered = conv[0] for k=0. For k>0, sum over all z with popcount(z)=k.
Then answer = (count_ordered - (k == 0 ? n : 0)) // 2.
Check with examples:
Example 1:
n=4, k=1, a = [0,3,2,1]
Values: 0,3,2,1. Compute frequencies: f[0]=1, f[1]=1, f[2]=1, f[3]=1. N=16? Actually L? 0..3 need at most 2 bits? But we use L=14, N=16384. But we can simulate.
Compute conv: We can compute manually. pairs with XOR popcount=1: We need pairs with XOR having exactly one bit set.
List all numbers: 0(00),3(11),2(10),1(01). Compute XORs:
0^3=3 (11) popcount=2
0^2=2 (10) popcount=1 -> ordered (0,2)
0^1=1 (01) popcount=1 -> (0,1)
3^0=3 popcount=2
3^2=1 (01) popcount=1 -> (3,2)
3^1=2 (10) popcount=1 -> (3,1)
2^0=2 popcount=1 -> (2,0)
2^3=1 popcount=1 -> (2,3)
2^1=3 popcount=2
1^0=1 popcount=1 -> (1,0)
1^3=2 popcount=1 -> (1,3)
1^2=3 popcount=2
Ordered pairs with popcount=1: (0,2),(0,1),(3,2),(3,1),(2,0),(2,3),(1,0),(1,3) = 8 ordered pairs. Then answer = 8/2=4 unordered. Works.
Now compute conv via FWHT for L=2? Actually we used 2 bits. conv[z] for z with popcount=1: z=1 and z=2. conv[1] = sum_i f[i] f[i^1] = f[0]f[1] + f[1]f[0] + f[2]f[3] + f[3]f[2] = 11+11+11+11=4. conv[2] similarly = f[0]f[2]+f[2]f[0]+f[1]f[3]+f[3]f[1] = 4. Sum = 8. count_ordered=8. Then answer = (8-0)/2=4. Good.
Example 2:
n=6, k=0, a = [200,100,100,100,200,200]
f[200]=3, f[100]=3. conv[0] = Σ f[i]^2 = 3^2+3^2 = 9+9=18. count_ordered=18. Then answer = (18-6)/2 = 12/2=6. Good.
So method works.
Now we need to choose L. The maximum value in input is up to 10000. But we also need to consider that the XOR of two numbers can be up to 16383. However conv array of size N = 1<<L must be at least max possible xor value+1. Since max xor = (1<<L)-1 if we set L such that all numbers are within L bits. So we need L such that (1<<L)-1 >= max_xor_possible. max_xor_possible is the maximum xor of two numbers each ≤ max_a. That maximum occurs when one number has bits wherever the other doesn't, up to the highest bit of max_a. But with numbers ≤ 10000, highest bit is 13, so max xor can be up to (1<<14)-1 = 16383. So L must be at least 14. If we set L=14, N=16384, covers all possible xor results. So we can set L=14.
But is there any case where L=14 is not enough because numbers could be up to 10^4 but we need bits beyond? Actually 10^4 < 16384, so L=14 is enough. But we need to be careful: The problem statement says ai ≤ 10^4, but could they be larger? No, it's given. So L=14 is safe.
However, what if k=14 and numbers are all small? Then there might be pairs with xor having 14 bits set? For that, the xor must be 16383, which requires numbers that are complements within 14 bits. But if the maximum number is less than 8192, then the complement may exceed the max? For instance, if max number is 1000 (< 1024? Actually 1000 < 1024, so highest bit is 9? 2^9=512, 2^10=1024, so highest bit index 9? Actually 1000 in binary: 1111101000, that's 10 bits? 2^9=512, 2^10=1024 >1000, so highest bit is 9? Actually 1000 decimal: binary representation: 1111101000, which is 10 bits (bits 9 down to 0). So the highest bit index is 9. So if we fix L=14, we consider bits 10-13 as zero for all numbers. Then the XOR of two numbers can have bits set up to bit 9 only, so popcount maximum is at most number of bits up to 9? Actually if all numbers have zeros in bits 10..13, then those bits are 0 for both, so XOR will have 0 there. So maximum popcount is at most number of bits up to highest set bit in any number. So if max_a is 1000 (10 bits), then max popcount is at most 10. So if k=14, there will be zero pairs. That's fine, our method will still work because we will sum over z with popcount(z)=14, but no such z will have non-zero conv? Actually conv[z] for such high z (with bits beyond 10) will be zero because F[i] is zero for i with those bits? Not necessarily. Suppose there is a number 0 and a number 16383? But 16383 is not present. So conv[z] for z having bits set beyond the range of numbers will be zero because to have i^j = z, both i and j must be within the set. If z has a bit set at position 13, then for any i, j such that i^j has bit 13=1, one of them must have bit 13=1. Since no number has bit 13=1 if max_a < 8192, then conv[z]=0. So sum over z with popcount=14 will be 0. So answer 0. That's correct.
Thus L=14 works.
But we could also compute L dynamically as the smallest integer such that (1<<L) > max_a, maybe plus some? Actually to cover all possible XOR results, we need L such that 2^L > max_a, i.e., L = floor(log2(max_a)) + 1. Since max_a ≤ 10000, that L could be 14 (since 2^13=8192, 2^14=16384). So we can compute L = max_a.bit_length()? Actually bit_length gives number of bits necessary to represent max_a, e.g., 10000 -> bit_length=14 (since 2^13=8192, bit_length of 8192 is 14? Actually 8192 in binary is 1 followed by 13 zeros -> bit_length=14. 10000 also bit_length=14). So L = max_a.bit_length() yields 14. Good. So we can compute L = max(1, max_a.bit_length())? But need to consider k could be up to 14, but if max_a bit_length is smaller, say 4, but k=5, our method with L = bit_length may not include enough bits to represent popcount differences in higher bits? Let's examine: Suppose max_a = 7 (binary 111). Then L = 3 (since 7 bit_length=3). But then we only consider bits 0,1,2. However, Hamming distance is defined on binary representation without leading zeros? For numbers 0 (000) and 8? 8 is not in input because max is 7. But consider two numbers: 0 (000) and 0? Actually if we only consider 3 bits, flipping bits beyond bit 2 would create numbers that are not present. But if k=5, is it possible to have two numbers with Hamming distance 5? That would require the XOR to have 5 bits set. Since the numbers themselves only have bits 0..2 (3 bits), the XOR can only have bits 0..2 set (max popcount 3). So no pairs. So it's okay to restrict to L = bit_length of max_a. However, we need to consider that the XOR result might require bits beyond L? No, because if both numbers have 0 in bits beyond L-1, then XOR also has 0. So it's safe. But careful: Could there be numbers that have different lengths in binary representation if we don't pad? For example, 4 (100) and 1 (1). The XOR is 101 (5), popcount=2. If we take L=3 (since max_a=4 => bit_length=3?), Actually max_a=4, bit_length=3 (since 4=100, needs 3 bits). So L=3 covers bits 0,1,2. Then XOR 5 = 101 has bits 0 and 2 set, popcount=2. So fine. If max_a=8, bit_length=4, includes bit 3. So ok.
But what about k up to 14? If max_a bit_length is smaller, like 3, then there will be no pairs for k>3. So conv sum will be zero. So we can set L = max( max_a.bit_length(), k )? Not necessary, because for k > max_bit_length, answer is zero anyway. But if we set L = max(max_a.bit_length(), 1) maybe 1, but to perform FWHT we need N a power of two. The size could be as small as 2^3=8 for max_a=7, which is even faster. But we must ensure that the XOR values we need to consider for popcount = k may involve bits beyond max_a.bit_length() if k > max_bit_length? But those bits are zero for all numbers, so XOR will never have those bits set, so no contribution. So we can set L = max_a.bit_length(). However, note that if max_a is 0, then all numbers are 0. Then max_a.bit_length() returns 0? In Python, (0).bit_length() returns 0. But we need at least L=1 to have N=1? Actually if all numbers are zero, we still need to count pairs (i,j) with k=0? For k>0, answer=0. For k=0, answer = C(n,2). For L=0, we can't have array size 1<<0 =1? That's 1, that could work? Actually if L=0, then N=1, and the only index is 0. Then f[0]=n. FWHT with N=1 is trivial. conv[0] = n^2. For k=0, count_ordered = conv[0] = n^2. Then answer = (n^2 - n)/2 = C(n,2). That works. But careful: if k>0, then we sum over z with popcount(z)=k, but there are no z because N=1 only index 0. So sum=0, answer=0. So L=0 works. However, we need to handle L=0 as a special case? We can just set L = max(1, max_a.bit_length())? Actually we need N >= max value + 1. If max_a=0, N=1 is fine. So we can compute L = max_a.bit_length(). If max_a=0, L=0, N=1, it's okay. But in our FWHT implementation, we need to handle N=1 as a trivial case (no loops). It should work because while step < n: step starts at 1, and 1 < 1 false, so no transform. Then after squaring, etc., conv[0] = f[0]^2? Let's test: f[0]=n. After forward transform? Since no transform, A = [n]. Square => n^2. Inverse transform does nothing, divide by N=1 => n^2. That matches conv[0] = Σ_i f[i] f[i^0] = Σ_i f[i]^2 = n^2. Good. So L=0 is fine. However, Python's bit_length for 0 is 0, so N = 1 << 0 = 1. So we can just set L = max_a.bit_length().
But is it always sufficient? Consider max_a = 10000, L=14. That's fine.
Now, we need to compute popcount for each z from 0 to N-1. We can precompute popcounts using built-in bit_count (Python 3.8+? Actually Python 3.10+ has int.bit_count(), in 3.8 maybe? I'm using Codeforces environment which is Python 3.8? Actually Codeforces uses Python 3.8.2? It might have int.bit_count()? I'm not 100% sure; in Python 3.8, int.bit_count() was introduced in 3.8? Wait, bit_count was added in Python 3.8? I think it was added in Python 3.8? Actually PEP 552? Let me check: Python 3.8 introduced int.to_bytes changes? I'm not sure. However, I know that Python 3.10 definitely has bit_count. Codeforces uses Python 3.8? Many Codeforces participants use bin(x).count('1') which is slower but for N <= 16384 it's fine. We can precompute popcounts for all numbers up to N-1 using a simple loop: popcounts = [0]*N; for i in range(1,N): popcounts[i] = popcounts[i>>1] + (i&1). That's fast.
Thus algorithm steps:
- Read n, k.
- Read list a.
- Find max_a = max(a) if n>0 else 0.
- Set L = max_a.bit_length() (if max_a==0, L=0). But careful: k may be > L? That's fine.
- N = 1 << L (if L=0, N=1).
- Initialize freq array of size N with zeros.
- For each x in a: freq[x] += 1.
- Perform FWHT convolution to get conv array (size N):
- a = freq[:] (list copy)
- fwht(a) (forward transform)
- for i in range(N): a[i] = a[i] * a[i]
- fwht(a) (forward transform again, which acts as inverse due to no scaling)
- for i in range(N): a[i] //= N # now a[z] = conv[z] = Σ_i freq[i] * freq[i^z]
- Compute count_ordered:
- if k == 0: count = a[0] (since only z=0 has popcount 0)
- else: count = sum(a[z] for z in range(N) if popcount(z) == k)
- Answer = (count - (n if k == 0 else 0)) // 2
- Print answer.
Check edge cases:
- n=2, k=0, a=[5,5]: freq[5]=2. max_a=5, L=3 (since 5 bit_length=3), N=8. conv[0] = Σ f[i]^2 = 2^2=4? Actually f[5] only; conv[0] = f[5]^2 + zeros =4. count=4. answer=(4-2)/2=1. That's correct (one pair).
- n=2, k=1, a=[5,6] (5=101,6=110; xor=3 popcount=2). So answer 0. freq[5]=1,freq[6]=1. conv[z] where popcount(z)=1: z=1,2,4? Actually in N=8? Let's compute: conv[1] = f[0]f[1]+... but f[5] and f[6] only. i^j=5^6=3 (011) popcount=2, not 1. So sum over popcount=1 is 0. count=0, answer=0. Good.
- n=2, k=2, a=[5,6] -> XOR=3 popcount=2. conv[3] = f[5]f[6]+f[6]f[5]=2. So count=2? Actually ordered pairs: (5,6) and (6,5) -> 2. count=2. answer = (2-0)/2=1. Good.
Now we need to ensure that conv[z] for z with popcount(z)=k includes all ordered pairs. In the case where some numbers appear multiple times, conv[z] counts each ordered pair of occurrences. So that's fine.
Now, we must verify that the transform works for large n and N=16384. freq values up to 1e5, after transform values may become large. But Python int can handle.
Complexities: O(N log N) for FWHT, where N <= 16384, so ~230k operations, plus O(N) for sum. Very fast.
Let's test with a random case by implementing.
But we need to be careful: The transform as described uses nested loops; it's O(N log N). With N=16384, log2(N)=14, so step loops: for each step size (1,2,4,...,8192), we have N/ (2step) groups? Actually for each step, we loop i from 0 to N-1 with step 2step, and inner j loops step times. So total operations per step is N. So total ~ N * log2(N) = 16384 * 14 = 229376 operations. Each operation does addition/subtraction. So very fast.
Now we must confirm that dividing by N after the second transform yields integer. Since we are using integer division, but it should be exact. However, because of negative values? In the intermediate transform, values can be negative? For example, after first transform we could have negative numbers. Then squaring yields positive. Then second transform may produce negative numbers? Actually after squaring, the array has nonnegative numbers (since squares of integers). But the transform uses addition/subtraction, so it may produce negative numbers? Let's test with simple example: a = [1,2], after first fwht: [3,-1] (negative). After squaring: [9,1] (nonnegative). Second fwht: [10,8] (positive). So no negative. In general, after squaring, all entries are non-negative, and the transform is linear with integer coefficients, so the result should be non-negative. However, because of the subtraction, some intermediate values could become negative during the second transform, but final result after division should be non-negative integer. So integer division is fine.
Edge case: If N is not a power of two? We set N = 1<<L, so power of two.
Now, we need to handle the case where L = 0, N = 1. The fwht function should handle N=1 without issues (while loop condition step < n fails immediately). So no problem.
Now, we need to compute popcount for each z. We can precompute popcnt array of size N using simple method:
popcnt = [0]*N
for i in range(1,N):
popcnt[i] = popcnt[i>>1] + (i&1)
Alternatively, use built-in bit_count.
Now, one more nuance: The maximum XOR of two numbers may require bits up to L, but if L = max_a.bit_length(), is it possible that the XOR value has a bit set at position L? For example, max_a = 7 (111), L=3, then max XOR could be 7 (111) which fits in 3 bits. However, consider numbers 4 (100) and 3 (011). XOR = 111 = 7, fits. Good. But what about numbers 0 and 7? XOR=7. So fine.
But consider max_a = 8 (1000). L = 4 (since 8 bit_length=4). Numbers: 8 (1000) and 7 (0111) both ≤8? 7 is ≤8. XOR = 15 (1111) which is 4 bits, fits. So fine.
General: For any two numbers a,b < 2^L, a ^ b < 2^L. Because XOR operates bitwise and the highest possible bit is at most the max of their highest set bits, which is < 2^L. Actually if a and b are in [0,2^L-1], then a^b is also in [0,2^L-1]. So using L = max_a.bit_length() ensures all numbers are < 2^L (since max_a < 2^L if max_a's bit_length = L? Wait: If max_a = 2^L - 1, then max_a.bit_length() = L, because e.g., 7 (111) bit_length=3, and 2^3 =8, so max_a < 2^L. So indeed max_a < 2^L. So all numbers are < 2^L. Then XOR of any two is < 2^L. So conv array size N = 2^L covers all possible XOR results.
Thus this is correct.
Now, we need to ensure that if k > L, then answer will be 0, as there is no z with popcount = k because maximum popcount is L (since z < 2^L). So we could early exit if k > L, answer = 0. But the conv sum would be 0 anyway (since no z has popcount=k). However careful: if k > L, there might still be pairs? Since XOR can have at most L bits set, so if k > L, no pairs. So we could return 0 directly without any computation. That might be a micro-optimization, but not necessary.
But there is a nuance: Suppose k > L, but what about numbers that have bits beyond L? Since L = max_a.bit_length(), max_a < 2^L, so all numbers have zeros in bits >= L. So XOR also zeros there. So max popcount = number of bits up to L-1? Actually maximum popcount of XOR can be up to L (if XOR = 2^L -1). That's exactly L. So if k > L, answer 0. So we can check: if k > L: print(0) and return. But wait: k can be up to 14, L could be 14 if max_a >=8192. So it's fine.
Now, let's test with the provided examples.
Example1:
n=4, k=1, a=[0,3,2,1]
max_a=3, bit_length=2? Actually 3 in binary is 11, bit_length=2. So L=2, N=4.
freq: indices 0..3: f[0]=1,f[1]=1,f[2]=1,f[3]=1.
Perform FWHT:
a = [1,1,1,1]? Actually freq[0]=1,1? Wait mapping: index 0: value 0 ->1; index 1: value 1 ->1; index 2: value 2 ->1; index 3: value 3 ->1.
Now fwht:
step=1:
i=0: j=0: x=a[0]=1, y=a[1]=1 => a[0]=2, a[1]=0
i=2: j=2: x=a[2]=1, y=a[3]=1 => a[2]=2, a[3]=0
Now a = [2,0,2,0]
step=2:
i=0: j in range(0,2): j=0: x=a[0]=2, y=a[2]=2 => a[0]=4, a[2]=0; j=1: x=a[1]=0, y=a[3]=0 => a[1]=0, a[3]=0
After step=2: a=[4,0,0,0]
Squaring: a = [16,0,0,0]
Second fwht:
step=1:
i=0: j=0: x=16, y=0 => a[0]=16, a[1]=16
i=2: j=2: x=0, y=0 => a[2]=0, a[3]=0
a=[16,16,0,0]
step=2:
i=0: j=0: x=16, y=0 => a[0]=16, a[2]=16; j=1: x=16, y=0 => a[1]=16, a[3]=16
After: a=[16,16,16,16]
Divide by N=4: [4,4,4,4] -> conv[0]=4, conv[1]=4, conv[2]=4, conv[3]=4? Actually conv[z] = sum_i f[i] f[i^z]. Let's compute manually:
z=0: sum f[i]^2 = 4 -> conv[0]=4
z=1: i^1: (0,1),(1,0),(2,3),(3,2) each f=1 -> 4 -> conv[1]=4
z=2: similarly 4
z=3: similarly 4? Actually i^3: 0^3=3,1^3=2,2^3=1,3^3=0 => each product 1 -> sum=4. So conv[3]=4.
So conv = [4,4,4,4].
Now k=1, sum over z with popcount(z)=1: which z have popcount=1? In 2-bit numbers: z=1 (01) popcount=1, z=2 (10) popcount=1. So sum = 4+4=8. count_ordered=8. answer=(8-0)/2=4. Good.
Example2:
n=6, k=0, a=[200,100,100,100,200,200]
max_a=200, bit_length? 200 binary 11001000 -> 8 bits? Actually 200 = 128+64+8 = 0b11001000, that's 8 bits (bit_length=8). So L=8, N=256. freq: only indices 100 and 200. Let's compute conv[0] = f[100]^2 + f[200]^2 = 9+9=18. So count_ordered=18, answer=(18-6)/2=6. Works.
Thus algorithm is correct.
Now, we must implement FWHT carefully to handle large integer values. We'll implement a function that modifies list in place.
Potential pitfalls:
- We should copy freq to a new list for transform, not modify original if needed later (we don't need original after conv).
- The forward transform as described uses integer operations. Since values can be large (after squaring, they can be up to (sum f)^2 * N maybe?), but Python handles big ints.
- Division after second transform: use integer division // N. Since conv values are integers, it's fine.
But we must ensure that the second fwht is applied on the squared array. In code:
def fwht(a):
n = len(a)
step = 1
while step < n:
for i in range(0, n, step*2):
for j in range(i, i+step):
x = a[j]
y = a[j+step]
a[j] = x + y
a[j+step] = x - y
step <<= 1
Then:
a = freq[:]
fwht(a)
for i in range(N):
a[i] *= a[i]
fwht(a)
for i in range(N):
a[i] //= N
Now conv = a.
But note: after the first fwht, a contains the transformed values, which may be negative. Squaring makes them nonnegative.
Now, we must compute popcount for each z. Precompute popcnt array.
Potential micro-optimizations: Since N is at most 16384, we can compute popcnt for all numbers quickly.
Now edge case: If n is large and max_a is 0, L=0, N=1. Then fwht does nothing. After squaring and dividing, conv[0] = n^2. For k=0, answer = (n^2 - n)/2. For k>0, answer=0. That's fine.
Now, let's test with some random small cases by brute force to ensure correctness.
I'll do mental check for a few.
Case: n=3, a=[1,2,3], k=1.
List: 1(001),2(010),3(011). Compute ordered pairs with popcount=1:
1^2=3 popcount=2
1^3=2 popcount=1 -> (1,3)
2^1=3 popcount=2
2^3=1 popcount=1 -> (2,3)
3^1=2 popcount=1 -> (3,1)
3^2=1 popcount=1 -> (3,2)
So ordered = (1,3),(2,3),(3,1),(3,2) = 4. Answer = 2.
Our algorithm:
max_a=3, L=2? Actually 3 bit_length=2? 3 in binary 11 => bit_length=2, N=4. freq: f[1]=1,f[2]=1,f[3]=1. conv as earlier? Actually with indices: 1,2,3. Let's compute conv for N=4:
f = [f0=0, f1=1, f2=1, f3=1]
Compute conv[z] = Σ_i f[i] f[i^z].
Compute manually:
z=0: Σ f[i]^2 = 0+1+1+1=3.
z=1: i=0: f0f1=0; i=1: f1f0=0; i=2: f2f3=11=1; i=3: f3f2=11=1 => total 2.
z=2: i=0: f0f2=0; i=1: f1f3=11=1; i=2: f2f0=0; i=3: f3f1=11=1 => total 2.
z=3: i=0: f0f3=0; i=1: f1f2=11=1; i=2: f2f1=11=1; i=3: f3f0=0 => total 2.
So conv = [3,2,2,2].
popcount(1)=1, popcount(2)=1, popcount(3)=2? Actually 3=11 popcount=2. So sum over z with popcount=1: conv[1]+conv[2] = 2+2=4. count_ordered=4. answer=(4-0)/2=2. Good.
Case: k=2: sum over popcount=2: only z=3 -> conv[3]=2, count_ordered=2, answer=1. Indeed unordered pairs with popcount=2: (1,2) only? Actually 1^2=3 popcount=2 -> (1,2) and (2,1) ordered=2 -> unordered=1. Good.
Case: same value multiple times: n=4, a=[5,5,5,6], k=1. Compute frequencies: f[5]=3, f[6]=1. Need pairs with XOR popcount=1. XOR(5,6)=3 (011) popcount=2, so not. Actually 5=101,6=110, XOR=011=3 popcount=2. So no pairs? Wait, what about 5 and 5? XOR=0 popcount=0. So answer should be 0. But are there any other numbers? Only 5 and 6. So indeed 0. However, if we consider k=2, then pairs (5,6) have popcount=2. So unordered pairs: between 5 and 6, 31 = 3 pairs? Actually number of unordered pairs where one is 5 and other 6: 31=3. So answer should be 3 for k=2. Let's test with algorithm: max_a=6, bit_length=3 (since 6=110), N=8. f[5]=3, f[6]=1, others 0.
Compute conv[z] where popcount(z)=2. Which z have popcount=2 within 0..7? z=3(011),5(101),6(110). Also possibly? 3,5,6. So conv[3] = Σ_i f[i] f[i^3]. i^3: compute contributions:
i=5: i^3 = 6, f[5]f[6]=31=3; i=6: i^3 = 5, f[6]f[5]=13=3; i=0? f0=0; i=1? etc. So conv[3]=6.
conv[5]: i=5 -> i^5=0 => f5f0=0; i=0? etc; i=3? f3? maybe; i=6 -> i^5=3 => f6f3=0; so conv[5]=0? Actually also i=2? no. So likely 0.
conv[6]: i=5 -> i^6=3 => f5*f3=0; i=6->i^6=0 =>0; So conv[6]=0. So sum =6. count_ordered=6, answer=(6-0)/2=3. Good.
Thus algorithm works.
Now we must handle k = 0 separately? In our formula we used if k==0 then count = a[0], else sum over popcount(z)==k. But note: For k=0, popcount(z)=0 only when z=0. So we can just use the same sum: count = sum_{z: popcount(z)==0} a[z] = a[0]. So we can unify: count = sum_{z: popcount(z)==k} a[z]. Because if k==0, that includes only z=0. So we don't need special case. However, we still need to subtract n if k==0 in answer step. So we can compute count = sum_{z} a[z] if popcount(z)==k. That works.
Now, complexity: O(N log N + N) ~ O(2^L * L). For L=14, fine.
Now, we must consider memory: freq array of size up to 16384, conv similar. That's trivial.
Now, what about the case where n is up to 1e5, but the values may be up to 10000, which is fine.
Now, confirm the algorithm on the second example using L=8. Let's compute quickly: N=256, f[100]=3, f[200]=3. After FWHT and convolution, conv[0] = 18, others maybe some values but we only need popcount=0? For k=0, count = conv[0]=18, answer= (18-6)/2=6. Good.
Now, I want to double-check that the conv computed via FWHT indeed equals Σ_i f[i] f[i^z]. Yes.
Now, we need to be careful: The transform described (addition/subtraction) is for XOR convolution. However, there is an alternative normalization: If we use transform without scaling and then apply again and divide by N, we get convolution. So we are good.
Now, test with a random large case using mental? Not needed.
Now, potential pitfalls: If L is large, like 14, fine. If L is 0, N=1, the fwht function should handle step < n condition, step=1, 1<1 false, so nothing.
Now, we also need to consider that the input numbers might be up to 10^4, but what about negative numbers? No, non-negative.
Now, we need to implement reading input efficiently: use sys.stdin.read().
Now, I'll write code.
Pseudo-code:
import sys
def fwht(a):
n = len(a)
step = 1
while step < n:
for i in range(0, n, step*2):
for j in range(i, i+step):
x = a[j]
y = a[j+step]
a[j] = x + y
a[j+step] = x - y
step <<= 1
def solve():
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
n = int(next(it))
k = int(next(it))
a = [int(next(it)) for _ in range(n)]
if n == 0:
print(0)
return
max_a = max(a)
L = max_a.bit_length() # may be 0
# if k > L, we could return 0 early to avoid work, but still need to compute freq? We can early exit.
# But careful: even if k > L, it's possible that there are pairs? No, because XOR can have at most L bits set, so answer 0.
# However, if L==0, then all numbers are 0, so only k=0 gives answer. So early exit:
if k > L:
print(0)
return
N = 1 << L
freq = [0] * N
for x in a:
freq[x] += 1
# perform convolution
f = freq[:] # copy
fwht(f)
for i in range(N):
f[i] *= f[i]
fwht(f)
for i in range(N):
f[i] //= N # now f[z] = conv[z]
# precompute popcounts if needed
# Actually we only need to sum over z where popcount(z)==k.
# Since N is small, we can compute on the fly using built-in bit_count or precomputed.
# We'll precompute popcnt for all N.
popcnt = [0] * N
for i in range(1, N):
popcnt[i] = popcnt[i >> 1] + (i & 1)
count_ordered = 0
for z in range(N):
if popcnt[z] == k:
count_ordered += f[z]
# subtract self pairs if k==0
ans = (count_ordered - (n if k == 0 else 0)) // 2
print(ans)
if name == "main":
solve()
Now, test with given examples.
But wait: In the case where L=0, N=1, popcnt array size 1, popcnt[0]=0. f[0] = n^2. count_ordered = f[0] if k==0 else 0 (since only z=0, popcnt[0]=0). Then ans = (count_ordered - (n if k==0 else 0)) // 2 = (n^2 - n)//2 if k=0 else (0-0)//2=0. Good.
Now, we need to ensure that when L=0, the early exit condition if k > L: if k > 0 and L=0, then k>0> L? Actually L=0, so if k > 0, then k > L, we would early return 0. That's correct because there can't be any pairs with k>0 if all numbers are 0. So we can early exit.
Now, but we need to be careful: In the early exit we did "if k > L: print(0); return". However, is it always true that answer is 0 when k > L? As argued, maximum popcount of XOR is L because XOR values are < 2^L. But is it always exactly L maximum? For example, if all numbers are 0, L=0, max popcount is 0. So yes. So early exit is safe.
But consider scenario: max_a = 3, L=2. The XOR of two numbers both ≤ 3 can be at most 3 (binary 11) popcount 2 = L. So max popcount = L. So k > L => impossible. So early exit is fine.
Thus we can include that optimization.
Now, also note: If L is 0, then N = 1. The fwht function should handle N=1. But if we early exit for k>0, we don't need to compute for that case. For k=0, we would not early exit. So we need to handle L=0. That's fine.
Now, potential issue: The convolution we computed is Σ_i f[i] f[i^z]. But note that for z != 0, this includes both i and j such that i^j = z, which counts each unordered pair twice. That's what we want for ordered pairs. So it's fine.
Now, but there is one more nuance: In the case where we have same value pairs (i.e., z=0) and k=0, we count ordered pairs including i=j. That's also correct for count_ordered. So we subtract n for self-pairs later.
Now, test with a case where there are many duplicate numbers: n=100000, all numbers = 123, k=0. Then max_a=123, L=7 (since 123<128), N=128. freq[123]=100000. conv[0] = 100000^2 = 10^10. count_ordered=10^10. ans = (10^10 - 100000)/2 = (10^10 - 1e5)/2 ≈ 5e9 - 5e4, which fits in Python int. That's fine.
Now, test with k=1 and all numbers same 123. Then any pair has XOR=0, popcount=0, so no pairs with k=1. Our conv for z where popcount(z)=1 will be something? Let's compute: freq only at 123. conv[z] = Σ_i f[i] f[i^z] = f[123] * f[123^z]. For z != 0, 123^z is different from 123, and since f is zero there, conv[z]=0. So count_ordered=0. ans=0. Good.
Now, test with two distinct values: f[0]=50000, f[16383]=50000? But 16383 > 10000, not allowed. So not.
But we should test with numbers near 10000.
Now, about L: we used max_a.bit_length(). However, consider scenario where max_a = 8192 (2^13). Its bit_length = 14? Actually 8192 = 2^13, binary 1 followed by 13 zeros, bit_length = 14? Let's compute: In Python, (8192).bit_length() -> 14? Because 2^13 = 8192, the highest bit index is 13, so bit_length = 14 (since it counts the number of bits needed to represent the number in binary without a sign, i.e., floor(log2(x)) + 1). For 8192, floor(log2(8192))=13, +1 =14. So L=14, N=16384. That's fine. For max_a=8191, bit_length=13? 8191 = 2^13 -1 = 13 bits all ones, so bit_length=13. So N=8192. That's enough because max XOR could be up to 8191? Actually 8191 XOR 8191 = 0, but two numbers 8191 and 0 gives XOR=8191 (13 bits), which is < 8192. So N=8192 is enough. So we are safe.
Now, consider max_a=8192, L=14, N=16384. The maximum XOR could be 8192 ^ 8191 = 16383? Actually 8192 (10000000000000) and 8191 (01111111111111) -> XOR = 16383 (11111111111111) which is 14 bits all ones. That's within N=16384? 16383 < 16384. So N must be at least 16384. So L=14 is needed. So our bit_length computation yields L=14 for max_a=8192, correctly covering all XORs.
Thus the method is sound.
Now, we need to ensure that our FWHT can handle N up to 16384 (2^14) easily.
Now, test with example: n=4, k=1, we already did.
Now, there is also possibility to use the mask enumeration method, but FWHT is simpler and faster.
One more nuance: The FWHT as implemented uses nested loops that might be a bit slower in pure Python due to inner loops in Python. But with N=16384, step up to 8192, the inner loops will have many iterations, but overall ~229k operations, each operation is simple addition/subtraction of Python ints. That should be very fast (like < 0.1 sec). However, note that the inner loop goes over j in range(i, i+step). That's Python-level loop; but with step being small at the early steps? Actually when step=1, there are N/2 = 8192 iterations of the innermost loop? Let's count operations: For step=1, we have i from 0 to N-1 with step 2, so i takes N/2 values = 8192. For each i, we do j in range(i, i+1): that's exactly one iteration per i (since step=1, the inner loop runs step times = 1). So for step=1, we have 8192 inner iterations. For step=2, i takes N/4 = 4096, inner loop runs step=2, so 40962 = 8192 iterations. Similarly, for each step size, total inner iterations = N. Since there are log2(N) steps, total = N log2(N) ≈ 1638414 = 229,376 iterations. Each iteration does two assignments and addition/subtraction. That is definitely fine. Even with Python, 230k ops is trivial.
Now, we also have the squaring loop: N iterations.
Thus overall runtime dominated by reading input.
Thus solution is efficient.
Now, we need to ensure that we use integer division // for negative? But we argued no negative after second transform? Actually after second transform, we might have negative values if the squared array had some pattern? Let's think: The second transform is applied to the squared array which is non-negative. But the transform involves subtractions, so intermediate values could become negative. However, the final result after the whole transform (including dividing by N) should be non-negative because it equals the convolution sum which is sum of products of non-negative frequencies. So the final result is non-negative. However, due to Python's integer division for negative numbers, if any f[z] were negative, // N would floor towards negative infinity, potentially giving wrong result. But we argue it shouldn't be negative. Let's test with a simple case: f = [0,1,1,0]? Actually we need a case where after squaring, some values might cause negative final? Let's test with f = [1,0,0,1] (frequencies at 0 and 3). Compute expected conv? But we can test our code.
f = [1,0,0,1], N=4.
First fwht:
step=1: i=0: x=1,y=0 => a[0]=1,a[1]=1; i=2: x=0,y=1 => a[2]=1,a[3]=-1 => a=[1,1,1,-1]
step=2: i=0: j in 0..1: j=0: x=1,y=1 => a[0]=2,a[2]=0; j=1: x=1,y=-1 => a[1]=0,a[3]=2 => a=[2,0,0,2]
Now square: a=[4,0,0,4]
Second fwht:
step=1: i=0: x=4,y=0 => a[0]=4,a[1]=4; i=2: x=0,y=4 => a[2]=4,a[3]=-4 => a=[4,4,4,-4]
step=2: i=0: j=0: x=4,y=4 => a[0]=8,a[2]=0; j=1: x=4,y=-4 => a[1]=0,a[3]=8 => a=[8,0,0,8]
Divide by 4: [2,0,0,2] => conv[0]=2, conv[3]=2? Actually z=3 corresponds to index 3? conv[3]=2. Check manually: f[0]=1,f[3]=1. conv[0] = f0^2+f3^2=1+1=2, conv[3] = f0f3 + f3f0 = 1+1=2. So conv[3]=2 matches. No negatives.
Thus fine.
Now, edge case: When N is large (16384) and frequencies are large, the transform values could become huge, but Python ints can handle.
Now, one more nuance: In the convolution using FWHT, we squared the transformed array, but we didn't apply any modulus; it's exact.
Now, we need to consider memory usage: freq and conv lists of length up to 16384, each element Python int, memory negligible.
Now, answer can be up to C(n,2) ≈ 5e9, fits in 64-bit but Python int fine.
Now, final step: Write code.
Now, test with some random brute-force for small n to verify.
We'll do a mental test for n=5, a=[0,1,2,3,4], k=2. Let's compute expected answer using brute force:
Numbers: 0(000),1(001),2(010),3(011),4(100). Compute all unordered pairs i<j:
(0,1): XOR=1 popcount=1
(0,2): XOR=2 popcount=1
(0,3): XOR=3 popcount=2 -> count
(0,4): XOR=4 popcount=1
(1,2): XOR=3 popcount=2 -> count
(1,3): XOR=2 popcount=1
(1,4): XOR=5 (101) popcount=2 -> count
(2,3): XOR=1 popcount=1
(2,4): XOR=6 (110) popcount=2 -> count
(3,4): XOR=7 (111) popcount=3? Actually 3=011,4=100 -> XOR=111=7 popcount=3 -> not count
Thus pairs: (0,3),(1,2),(1,4),(2,4) => 4 pairs.
Now our algorithm: max_a=4, bit_length=3 (since 4=100, bit_length=3), N=8. freq: f[0]=1,f[1]=1,f[2]=1,f[3]=1,f[4]=1. Need conv for popcount=2. Which z have popcount=2? For 3-bit numbers (0-7): z=3(011),5(101),6(110). Also maybe? 7=111 popcount=3. So only 3,5,6.
Compute conv[3] = Σ_i f[i] f[i^3]:
i=0: i^3=3 -> f0f3=11=1
i=1: 1^3=2 -> f1f2=11=1
i=2: 2^3=1 -> f2f1=1
i=3: 3^3=0 -> f3f0=1
i=4: 4^3=7 -> f4f7=10=0
i=5: 5^3=6 -> f5*f6=0
i=6:6^3=5 ->0
i=7:7^3=4 ->0
Sum = 4
conv[5] = Σ_i f[i] f[i^5]:
i=0:0^5=5 ->0
i=1:1^5=4 -> f1f4=11=1
i=2:2^5=7 ->0
i=3:3^5=6 ->0
i=4:4^5=1 -> f4f1=1
i=5:5^5=0 -> f5f0=0
i=6:6^5=3 -> f6*f3=0? f6=0
i=7:7^5=2 ->0
Sum=2
conv[6] = Σ_i f[i] f[i^6]:
i=0:0^6=6 ->0
i=1:1^6=7->0
i=2:2^6=4 -> f2f4=1
i=3:3^6=5 ->0
i=4:4^6=2 -> f4f2=1
i=5:5^6=3 ->0
i=6:6^6=0 -> f6*f0=0
i=7:7^6=1->0
Sum=2
Total count_ordered = 4+2+2=8. answer = 8/2=4. Good.
So algorithm works.
Now, we need to consider the possibility of negative frequencies? No.
Now, implement.
But one more nuance: The FWHT we wrote uses addition and subtraction, which may produce odd numbers? But that's fine.
Now, to further optimize, we could use list comprehension for squaring, but fine.
Now, we might want to handle the case where L is 0 separately to avoid creating an array of size 1? It's fine.
Now, test with sample input.
Sample 1:
4 1
0 3 2 1
max_a=3, L=2, N=4. Should output 4.
Sample 2:
6 0
200 100 100 100 200 200
max_a=200, L=8? 200 bit_length=8, N=256. Should output 6.
Now, we also need to think about reading input: The second line contains n integers. Use sys.stdin.read.
Now, produce final answer.
Potential pitfalls:
-
When max_a is 0 and k=0, we early exit? No, we only early exit if k > L. L=0, so if k=0 not >0, we proceed. Good.
-
When max_a=0 and k>0, we early exit (k>0> L? 0? Actually L=0, k>0 => k>L true, so we print 0 and return. That's correct.
-
When n is large, but max_a small, L small, N small. So performance great.
Now, I'll write final code.
But wait: There is an alternative approach: we could also use combinatorial enumeration of masks; but FWHT is fine.
Now, I'll double-check the FWHT implementation correctness for convolution: Many online resources use the transform where after forward transform, you multiply, then inverse transform, and then divide by N. Our second fwht call is the same as forward because we didn't have a separate inverse. Since forward transform applied twice yields original times N, it's fine. But note: Some implementations use a different ordering: they might use the transform with addition/subtraction and then scaling factor 1/√N? But as we did, it's standard.
Let's confirm with another test: n=2, a=[5,6], k=2. max_a=6, bit_length=3, N=8. freq[5]=1,freq[6]=1. Compute conv[3] = 2? Let's compute via code mentally:
freq = [0]*8; freq[5]=1;freq[6]=1.
First fwht: We'll compute quickly. Actually we can compute conv via FWHT result: Should get conv[3]=2. Let's test:
f = [0,0,0,0,0,1,1,0]? Actually indices:0,1,2,3,4,5,6,7. So f = [0,0,0,0,0,1,1,0]
First fwht:
We'll compute step=1:
i=0: j=0: x=f[0]=0,y=f[1]=0 => a0=0,a1=0
i=2: j=2: x=f[2]=0,y=f[3]=0 => a2=0,a3=0
i=4: j=4: x=f[4]=0,y=f[5]=1 => a4=1,a5=-1
i=6: j=6: x=f[6]=1,y=f[7]=0 => a6=1,a7=1? Wait: y = f[7]=0 => a6 = x+y =1, a7 = x-y =1.
So after step=1, a = [0,0,0,0,1,-1,1,1]
Step=2:
Now step=2, we have pairs (0,2), (4,6) etc.
For i=0: j in 0..1:
j=0: x=a[0]=0, y=a[2]=0 => a[0]=0, a[2]=0
j=1: x=a[1]=0, y=a[3]=0 => a[1]=0, a[3]=0
For i=4: j in 4..5:
j=4: x=a[4]=1, y=a[6]=1 => a[4]=2, a[6]=0
j=5: x=a[5]=-1, y=a[7]=1 => a[5]=0, a[7]=-2
After step=2: a = [0,0,0,0,2,0,0,-2]? Wait: after j=5, a[5] becomes x+y = -1+1=0, a[7]= x-y = -1-1 = -2. So a = [0,0,0,0,2,0,0,-2].
Step=4:
Now step=4, i=0 only (since 0 to N-1 step 8). j in 0..3:
j=0: x=a[0]=0, y=a[4]=2 => a[0]=2, a[4]=-2
j=1: x=a[1]=0, y=a[5]=0 => a[1]=0, a[5]=0
j=2: x=a[2]=0, y=a[6]=0 => a[2]=0, a[6]=0
j=3: x=a[3]=0, y=a[7]=-2 => a[3]=-2, a[7]=2
After step=4: a = [2,0,0,-2,-2,0,0,2].
So after first fwht, a = [2,0,0,-2,-2,0,0,2].
Now square: a = [4,0,0,4,4,0,0,4].
Second fwht:
step=1:
i=0: j=0: x=4,y=0 => a0=4,a1=4
i=2: j=2: x=0,y=4? Actually a[2]=0, a[3]=4 => a2=4,a3=-4? Wait: careful: at start of second fwht, a is [4,0,0,4,4,0,0,4]. Let's apply step=1:
For i=0: j=0: x=a[0]=4, y=a[1]=0 => a[0]=4, a[1]=4.
For i=2: j=2: x=a[2]=0, y=a[3]=4 => a[2]=4, a[3]=-4.
For i=4: j=4: x=a[4]=4, y=a[5]=0 => a[4]=4, a[5]=4.
For i=6: j=6: x=a[6]=0, y=a[7]=4 => a[6]=4, a[7]=-4.
After step=1: a = [4,4,4,-4,4,4,4,-4].
step=2:
Now step=2, i=0 and i=4.
i=0: j in 0..1:
j=0: x=a[0]=4, y=a[2]=4 => a[0]=8, a[2]=0
j=1: x=a[1]=4, y=a[3]=-4 => a[1]=0, a[3]=8
i=4: j in 4..5:
j=4: x=a[4]=4, y=a[6]=4 => a[4]=8, a[6]=0
j=5: x=a[5]=4, y=a[7]=-4 => a[5]=0, a[7]=8
After step=2: a = [8,0,0,8,8,0,0,8].
step=4:
i=0 only: j in 0..3:
j=0: x=a[0]=8, y=a[4]=8 => a[0]=16, a[4]=0
j=1: x=a[1]=0, y=a[5]=0 => a[1]=0, a[5]=0
j=2: x=a[2]=0, y=a[6]=0 => a[2]=0, a[6]=0
j=3: x=a[3]=8, y=a[7]=8 => a[3]=16, a[7]=0
After step=4: a = [16,0,0,16,0,0,0,0]? Actually a[4] became 0, a[7] became 0. So a = [16,0,0,16,0,0,0,0].
Now divide by N=8: [2,0,0,2,0,0,0,0].
Thus conv[0]=2, conv[3]=2, others 0. So count_ordered for popcount=2: z=3 => 2. Answer = (2-0)/2=1. Good.
Now, note: After second fwht, we got conv[3]=2 as expected.
Now, check conv[5] and conv[6] are zero. Good.
Now, the algorithm works.
One more potential issue: When L is large (14) and n is large, the values in the transform may become huge. But Python can handle big integers. The maximum magnitude after first transform? Each element is sum of frequencies with signs. At worst, each element could be as large as n (since sum of absolute values?). Actually the transform is linear: each output is a sum of all inputs with coefficients +1 or -1. So each transformed value is at most n in absolute value (since frequencies are nonnegative and sum to n, but with signs it could be up to n). So after first transform, values are O(n). Then squaring gives O(n^2). Then second transform: each output is sum of squares with signs, so magnitude up to N * n^2? Actually worst-case: each squared value could be up to n^2, and we sum up to N of them with signs, so up to N * n^2. With N=16384, n=1e5, n^2 = 1e10, product = 1.6e14, which fits within Python int (which is arbitrary precision). So fine.
Now, note that dividing by N after second transform yields integer of order up to n^2, which is okay.
Thus implementation is safe.
Now, we could also implement popcnt using bin(z).count('1') but precomputing is fine.
Now, check edge: If k > L, we early return 0. But there is also the case where L = 0 and k = 0: we don't early return. Good.
Now, consider L = 0, N = 1, we need to compute popcnt array of size 1, popcnt[0] = 0. In the sum loop, we iterate z in range(1)? Actually range(N) is range(1) => only z=0. So popcnt[0]==k? if k=0, then yes. So count_ordered = f[0] = n^2. Then answer = (n^2 - n)/2. That's correct. If k>0, early exit, so we don't get to that loop.
Now, ensure that the fwht function works when N=1: step=1, while step < n: step=1, n=1 => condition false, so no loop. So no issues.
Now, final code.
Now, we need to ensure that we use fast I/O. Use sys.stdin.buffer.read.
Now, we also need to be careful about the input size: n up to 1e5, reading with read().split() is fine.
Now, we should test with extreme values:
- n=100000, all numbers random between 0 and 10000. L ~ 14, N=16384. The algorithm will run quickly.
Now, confirm that the answer fits within 64-bit? At worst n=100k, pairs = ~5e9, which fits in 64-bit signed? 5e9 < 2^31? Actually 5e9 > 2^31-1 (2.147e9), so might exceed 32-bit signed but 64-bit signed can hold up to 9e18, so fine. Python int anyway.
Now, one more nuance: The problem statement says k ≤ 14. So we can safely assume popcount(z) ≤ 14 if L=14. But if L is smaller, max popcount = L, but that's fine.
Now, code.
I'll also add an optimization: If k == 0, answer = sum(C(f[x],2)), which we could compute directly without transform. But we already have transform, and it's fast, so fine.
Now, also note: In early exit, we need to compute max_a, which requires scanning the array. That's O(n). That's fine.
Now, write final solution.
Now, produce final answer.
But we must ensure we use integer division for answer.
Now, think about potential issues with fwht for very large numbers: Might be slower due to big ints. However, n=1e5, n^2=1e10, N=16384, product 1.6e14, which is still not huge for Python big int operations (addition/subtraction on numbers with up to 48 bits? Actually 1.6e14 < 2^48, so about 48 bits, which is fine). So performance should be good.
Now, produce final code.
But also note: For safety, we could use bit_count if available: popcnt[z] = z.bit_count(). Since Python 3.8? I'm not 100% sure but I think int.bit_count() was introduced in Python 3.8? Actually I recall that bit_count came in Python 3.8? Let's verify: Python 3.8 added int.to_bytes? The method int.bit_count() was added in Python 3.8? Wait, I think it was added in Python 3.8? I remember that in Python 3.10, there is int.bit_count(). Actually I recall that PEP 604, but I'm not sure. I know that in Codeforces, many Python solutions use bin(x).count('1') because bit_count may not be available in older versions. But Codeforces currently uses Python 3.8.2, I think bit_count was introduced in Python 3.8? Let's check: Python 3.8 release notes: "Added int.to_bytes()" but I don't see bit_count. I think int.bit_count() was added in Python 3.8? Actually I found online: "Python 3.8 introduced int.to_bytes with ...". Another source: "int.bit_count() new in Python 3.8?" I'm not entirely sure. I'll search memory: In Python 3.9, there is int.bit_count(). I think it was introduced in Python 3.8? Actually I recall using .bit_count() in Python 3.10. Let's not rely; we can precompute popcnt as described, which is simple and fast for N <= 16384. So we'll use precomputed array.
Now, final code.
One more thought: Could we have a situation where L is less than needed for k? For example, k=14, but max_a=1000 (L=10). Then our early exit: k > L -> print 0 and return. But is it always zero? As argued, XOR can have at most 10 bits set because the numbers are up to 1023? Actually 1000 < 1024, but numbers could be up to 1000, but the XOR of two numbers can have bits up to the highest bit of the numbers. The highest bit of max_a is 9 (since 2^9=512, 2^10=1024). So max popcount is at most 10. So indeed k=14 impossible. So early exit correct.
But what about k=14 and max_a=8192 (L=14)? Then k == L, possible.
Now, code.
We'll implement solve() function.
Now, finalize.
But we also need to consider the possibility that k is not an integer? It's integer.
Now, final answer.
Now, I'll produce the solution.
Also, we might want to avoid the second fwht if k > L? Already early return.
Now, the final code:
import sys
def fwht(a):
n = len(a)
step = 1
while step < n:
for i in range(0, n, step*2):
for j in range(i, i+step):
x = a[j]
y = a[j+step]
a[j] = x + y
a[j+step] = x - y
step <<= 1
def solve():
import sys
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
k = int(next(it))
a = [int(next(it)) for _ in range(n)]
if n < 2:
print(0)
return
max_a = max(a)
L = max_a.bit_length()
if k > L:
print(0)
return
N = 1 << L
freq = [0] * N
for x in a:
freq[x] += 1
# FWHT for XOR convolution
f = freq[:] # copy
fwht(f)
for i in range(N):
f[i] *= f[i]
fwht(f)
for i in range(N):
f[i] //= N
# precompute popcounts
popcnt = [0] * N
for i in range(1, N):
popcnt[i] = popcnt[i >> 1] + (i & 1)
count_ordered = 0
for z in range(N):
if popcnt[z] == k:
count_ordered += f[z]
ans = (count_ordered - (n if k == 0 else 0)) // 2
print(ans)
if name == "main":
solve()
Now, check for n=1 (should output 0). We added an early return for n<2? Actually we can handle but it's not necessary because if n=1, there are no pairs. But the input constraints say n>=2, so we can ignore. But we'll keep it.
Now, test with sample input.
Now, finalize.
Potential bug: In the early exit if n<2, but n is at least 2 by problem statement, so fine.
Now, we should test the code mentally with a case where L=0, k=0, n=2, a=[0,0]. Then max_a=0, L=0, k>L? 0>0 false. N=1. freq=[2]. f = [2], fwht no change, square => [4], fwht => [4], //1 => [4]. popcnt[0]=0 == k? yes. count_ordered=4. ans = (4 - 2)//2 = 1. Correct.
Now, if L=0, k>0 early exit => 0.
Now, we should also test with large numbers where max_a=10000, L=14, N=16384. Should be fine.
Now, final answer.
I'll produce final output.
One more nuance: In the FWHT, we used while step < n. If n=1, step=1, condition false, so no loop. Good.
Now, maybe we can further micro-opt: Use local variables for list accesses, but not needed.
Now, we produce final code.
I think the solution is ready.
Let's also consider the possibility of using numpy for faster operations, but not allowed.
Now, I'll produce final answer. ```python
import sys
def fwht(a):
"""In-place Walsh-Hadamard Transform for XOR convolution."""
n = len(a)
step = 1
while step < n:
for i in range(0, n, step * 2):
for j in range(i, i + step):
x = a[j]
y = a[j + step]
a[j] = x + y
a[j + step] = x - y
step <<= 1
def solve() -> None:
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
k = int(next(it))
a = [int(next(it)) for _ in range(n)]
# No pairs possible if n < 2 (though problem guarantees n ≥ 2)
if n < 2:
print(0)
return
max_a = max(a)
L = max_a.bit_length() # enough bits to hold all numbers
if k > L: # Hamming distance cannot exceed L
print(0)
return
N = 1 << L # size of the transform (power of two)
freq = [0] * N
for x in a:
freq[x] += 1
# XOR convolution of freq with itself using FWHT
f = freq[:] # copy
fwht(f) # forward transform
for i in range(N):
f[i] *= f[i] # pointwise square
fwht(f) # inverse transform (same as forward)
for i in range(N):
f[i] //= N # scale
# precompute popcounts for all numbers 0 .. N-1
popcnt = [0] * N
for i in range(1, N):
popcnt[i] = popcnt[i >> 1] + (i & 1)
# total ordered pairs (i,j) with popcount(ai^aj) == k
count_ordered = 0
for z in range(N):
if popcnt[z] == k:
count_ordered += f[z]
# subtract the n self‑pairs when k == 0, then take unordered pairs
ans = (count_ordered - (n if k == 0 else 0)) // 2
print(ans)
if name == "main":
solve()