An established group of scientists are working on finding solution to NP hard problems. They claim Subset Sum as an NP-hard problem. The problem is to determine whether there exists a subset of a given set S whose sum is a given number K.
You are a computer engineer and you claim to solve this problem given that all numbers in the set are non-negative. Given a set S of size N of non-negative integers, find whether there exists a subset whose sum is K.
Input
First line of input contains T, the number of test cases. T test cases follow.
Each test case contains 2 lines. First line contains two integers N and K. Next line contains N space separated non-negative integers (each less than 100000).
0 < T < 1000
0 < N < 1000
0 < K < 1000
Output
Output T lines, one for each test case. Every line should be either 0 or 1 depending on whether such a subset exists or not.
Example
Input:
2
5 10
3 4 6 1 9
3 2
1 3 4
Output:
1
0
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to solve subset sum problem with constraints: N up to 999? Actually N < 1000. K < 1000. Numbers are non-negative, each less than 100000. So K is relatively small. We can use DP: dp[j] = true if sum j can be formed using some subset. Since K <= 1000, we can do DP of size K+1. For each number, update from high to low. That's O(NK). With T up to 1000, worst-case total NK could be: 1000 * 1000 * 1000? Actually if each test case max N=1000 and K=1000, then per test O(1e6). T=1000 would be 1e9, too high. But we need to consider that total input size might be large. However constraints: N<1000, K<1000, T<1000, but total numbers sum? Could be up to 1e6. 1e6 * 1000? Actually each test has N numbers, so total numbers across test cases <= 1e6 (since TN max is 1000999=~1e6). For DP we need to process each number, for each we iterate K down to 0. So total operations ~ total numbers * K. K max 1000, total numbers max 1e6, so total operations ~ 1e9, which is borderline but maybe okay in C++? In Python it might be too slow. Need optimized approach.
But we can note that K < 1000 is small, but numbers can be huge. However we can early break if number > K (skip). Also we can use bitset DP: using Python's int as bitset. For each number x, we can do bitset = bitset | (bitset << x) and then mask to K bits. That is efficient because bitwise operations on Python ints are fast. bitset starts with bit 0 set. After processing all numbers, check bit K. This would be O(N * (K/word_size))? Actually shifting large ints: bitset size up to K, so bitset fits in ~K bits. Shifting an int of K bits is O(number of machine words) ~ O(K/word_size) but Python big ints shift is O(n) where n is number of limbs. For K=1000, that's about 16 limbs (since 64-bit limbs) so very fast. So total operations ~ N * (K/64) ~ 1000*16 = 16000 per test, times 1000 tests = 16 million, okay.
We can also use array of bools and update from high to low, but the bitset method is clean and efficient.
Implementation: For each test case, read N,K, then list of numbers. Initialize bitset = 1 (bit 0). For each x in numbers: if x <= K: bitset = bitset | (bitset << x). Then mask bitset to only first K+1 bits: bitset & ((1 << (K+1)) - 1) maybe needed to avoid expansion beyond needed bits. Actually we can keep mask = (1 << (K+1)) - 1, and after each OR, do bitset &= mask. Alternatively, we can just shift and OR without mask but bitset may grow, but it's fine as long as we keep it within reasonable bits; but K is up to 1000, so after many shifts it could become up to sum of numbers but we mask each time to keep it manageable. So better to mask.
After processing all numbers, check if (bitset >> K) & 1.
Edge cases: numbers can be zero? non-negative, so zero is possible. With zero, shift left by zero does nothing, and OR results same; so zero doesn't affect. But multiple zeros also fine.
Also note: K can be 0? The constraints: 0 < K < 1000, so K at least 1. But maybe in test cases they could have K=0? It says 0 < K < 1000, so not zero.
But subset sum includes empty set sum 0, but we only care about K>0.
Implement solve() to read from sys.stdin.
Input format: T first line. Then for each test case: line with N K, next line N numbers.
We need to output 1 or 0 per test.
Let's craft.
We need to be careful with Python's input reading speed; use sys.stdin.buffer.
We'll parse ints.
Pseudo:
def solve():
import sys
data = sys.stdin.buffer.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
n = int(next(it)); K = int(next(it))
bits = 1
mask = (1 << (K+1)) - 1
for i in range(n):
x = int(next(it))
if x <= K:
bits = bits | (bits << x)
bits &= mask
if bits >> K & 1:
out.append('1')
else:
out.append('0')
sys.stdout.write('\n'.join(out))
Test with example.
Edge cases: If K is large (999), mask fits.
This should be fast.
But wait: The DP using bitset is correct if numbers can be used at most once? Subset sum with each element used at most once: using bitset shift left and OR is indeed standard for 0/1 knapsack (each element exactly once). Because we start with bitset, and for each x we do bitset | (bitset << x) which adds new sums from previous sums plus x, but careful: This might allow using the same element multiple times? Actually in 0/1 knapsack, if we iterate over items and update bitset from high to low to avoid reuse. But if we use bitset operation in one go, it's like for each element, we set bits for sums achievable with that element included, but using the bitset that already includes previous items, we don't allow using same element more than once because we are OR-ing with shift of the bitset before including the current element, which hasn't yet considered the current element's addition. So it's correct for at most once. However if we do bitset = bitset | (bitset << x) and then mask, it might cause multiple use? Actually consider bitset initially has bit 0. After processing x=2: bitset = 1 | (1<<2) = bits representing {0,2}. Then after processing another x=2: bitset = {0,2} | ({0,2} << 2) = {0,2} | {2,4} = {0,2,4}. That's correct for two distinct 2's, each used at most once. However it could also produce using the same element twice? In the step for the second 2, we shift the set {0,2} which includes a sum 2 that came from using the first 2. So then adding 2 yields sum 4, which corresponds to using both 2's. That's allowed because we have two separate items. So it's correct. However if we had only one item with value 2, but we process it and then later process the same value again? That would be two items. So correct.
Therefore bitset method works.
Now regarding performance: For each test case we process N numbers. Each operation: shift (big int) and OR and mask. For K=1000, bitset length ~1000 bits ~ 16 64-bit words. Shifting is linear in length. So each operation O(K/word_size) ~ 16 operations. So total per test case ~ N * 16. For N=1000, 16000 operations, trivial. T=1000 gives 16 million, okay.
But we should also consider that building mask = (1 << (K+1)) - 1 for K up to 1000 is fine.
Potential issue: The shift left might create a very large integer if we don't mask. However we mask each time, so it stays bounded.
Thus solution is efficient.
Let's test manually:
Input:
2
5 10
3 4 6 1 9
3 2
1 3 4
Test case 1: N=5, K=10, numbers: 3,4,6,1,9.
Initialize bits=1 mask= (1<<11)-1 = 2047.
x=3: bits = 1 | (1<<3)=1|8=9 (binary ...1001) -> bits {0,3} -> 9.
x=4: bits = 9 | (9<<4)=9 | (144) = 9|144=153? 153 binary? 9=1001, 9<<4=10010000=144, OR=10011001=153. That yields bits {0,3,4,7}? 0,3,4,7. Actually 7=3+4, good.
x=6: bits = 153 | (153<<6)=153 | (15364=9792?) compute: 153 << 6 = 15364=9792. OR yields bits: include existing sums and sums+6. Eventually we check if bit 10 set. Should be set because 4+6=10? Actually we have 4 (from earlier) and 6, sum 10. So bits after all should have 10. Let's compute quickly: after 4 we had {0,3,4,7}. After 6: existing and existing+6 => {0,3,4,7}+6 => {6,9,10,13}. So combined {0,3,4,6,7,9,10,13}. Yes 10 present.
x=1: adds more but not needed.
x=9: adds.
So final bits will have 10. So output 1.
Second test: K=2, numbers 1,3,4. bits: after 1: {0,1}. after 3: {0,1,3,4}. after 4: {0,1,3,4,4,5,7,8}? Actually careful: after 3: {0,1,3,4}. after 4: shift {0,1,3,4} <<4 => {4,5,7,8}. OR yields {0,1,3,4,5,7,8}. No 2. Output 0.
Works.
Thus solution is correct.
Now we must output 0 or 1 per line.
Now consider the possibility that K can be 0? According to constraints 0<K, so ignore.
Also note: N can be 0? It says 0 < N < 1000, so N>=1.
But just in case: if N=0, but not possible.
Edge: numbers may be greater than K; we skip them (since they can't be used in subset to reach sum K if all numbers are non-negative, and subset sum only positive? Actually if numbers are greater than K, they cannot be part of a subset summing to K because all numbers non-negative, so they can be ignored. This is correct.
But careful: If we skip numbers > K, we must also consider numbers equal to 0: they don't affect sum, but we can still include them. However they don't affect reachable sums; so they can be ignored as well. For zero, if we shift by 0, it would be a no-op, so we can skip as well. But we may as well skip because they don't change bitset. So condition x <= K works: includes 0? 0 <= K, so includes zero. If x=0, then shift left 0 yields same bitset; OR yields same; no change. So we could skip them for efficiency: if x == 0 or x > K: skip, but we can just condition x <= K, which includes 0 and then the operation does nothing? Actually bits | (bits << 0) = bits | bits = bits, so no change, but we still do OR and mask, which is redundant. So we could skip if x==0, but not necessary. However for performance, it's fine.
Now we need to ensure that the mask is applied after each update to keep the bitset size bounded. Alternatively, we could apply mask only at the end? But after many shifts, bitset could become huge if we don't mask; e.g., numbers up to 100000, shifting left by 100000 would create a huge integer with many bits. Even though we later mask, Python would have to allocate huge intermediate integers, which could be costly. So we must mask after each update. So we do bitset &= mask after OR.
But careful: In bitset = bitset | (bitset << x), the shift left may produce bits beyond K. Then we mask, which discards those bits. However discarding bits beyond K could lose information for future sums? Because if we discard bits beyond K, sums greater than K are irrelevant because we only care about sum K. Indeed we only need to know if sum K can be formed, and sums > K cannot help form K (since all numbers are non-negative, adding more positive numbers only increases sum). So we can safely discard any sum > K. So masking is safe.
Thus algorithm is correct.
Now implement solve function accordingly.
We'll produce final answer.
But let's double-check constraints: T, N, K all < 1000. But K < 1000, not <=? It says 0 < K < 1000, so max 999. So mask = (1 << (K+1)) - 1; for K=999, 1<<1000 is a 1000-bit number, that's fine.
Now about memory and speed: reading all data at once using .read().split() may be heavy if total input size is large: T up to 1000, each N up to 1000, so total numbers up to 1e6, plus T*2 for N,K, total tokens up to ~1,002,000. That's about a few MB, manageable. So okay.
Alternative: streaming, but not needed.
Now think about potential pitfalls: The bitset technique uses Python integers which are immutable; each operation creates new integer. But that's okay.
Edge case: If K is large (say 999) and we have many numbers (1000), each operation on ~1000-bit integer is fast.
Now we can finalize.
But wait: The problem states "0 < N < 1000", so N could be as high as 999. K < 1000. So max N=999, K=999. That's fine.
Now test with some random:
All numbers zero: then only sum 0 achievable; K>0, so output 0.
One number equals K: then output 1.
Sum of all numbers < K: output 0.
Now consider that numbers can be up to 100000, but we ignore >K, but if K is small (say 10), we ignore many numbers, which speeds up.
Now also note: The problem description says "non-negative integers (each less than 100000)". That includes zero.
Now I'll produce final answer.
But before final, think about possible alternative DP with boolean array: For each test case we can create dp = [False](K+1), dp[0]=True. Then for each x <= K: for j in range(K, x-1, -1): dp[j] = dp[j] or dp[j-x]. This is O(NK) and with total 1e6 numbers and K=1000 gives 1e9 operations, which might be too slow in Python (1e9 operations ~ many seconds). But perhaps we could break early if dp[K] becomes True. That could reduce average, but worst-case still high. So bitset is better.
Thus we proceed.
Implementation details:
Use sys.stdin.buffer.read().split() to get all tokens as bytes, convert to ints.
Iterate.
Now one more nuance: The input line for each test case contains N and K, then next line contains N numbers. But they might be on multiple lines? The problem says "Next line contains N space separated non-negative integers", but in some inputs, numbers could be split across lines? Typically not, but reading tokens deals with any whitespace.
So code:
def main():
import sys
data = sys.stdin.buffer.read().split()
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it)); K = int(next(it))
bits = 1
mask = (1 << (K+1)) - 1
for i in range(n):
x = int(next(it))
if x <= K:
bits = (bits | (bits << x)) & mask
out_lines.append('1' if (bits >> K) & 1 else '0')
sys.stdout.write('\n'.join(out_lines))
if name == "main":
main()
That's it.
Now verify with sample:
Input:
2
5 10
3 4 6 1 9
3 2
1 3 4
Processing:
First test: n=5 K=10, numbers: 3,4,6,1,9.
bits start 1.
x=3 <=10: bits = (1 | (1<<3)) & mask = (1|8)=9 & mask (0b11111111111) =9.
x=4: bits = (9 | (9<<4)) & mask = (9|144)=153 & mask =153.
x=6: bits = (153 | (153<<6)) & mask. 153<<6=15364=9792 (binary?), 153|9792=9945? Actually 153+9792=9945. 9945 & 2047? 2047=0b11111111111 (11 bits). 9945 decimal binary? 9945 in binary: 10011011011001? Let's compute: 2^13=8192, remainder 1753; 2^10=1024 remainder 729; 2^9=512 remainder 217; 2^7=128 remainder 89; 2^6=64 remainder 25; 2^4=16 remainder 9; 2^3=8 remainder1; 2^0=1. So bits beyond 11 may be set. After masking, we keep only lower 11 bits. 9945 & 2047 =? 2047=0b11111111111. 9945 % 2048 = 9945 - 42048 = 9945-8192=1753. So 1753. So bits=1753. That represents sums achievable: we need to check if bit10 set. 1753 decimal: binary 11011011001? Actually compute: 1024+512=1536; remainder 217; +128=1664; remainder 89; +64=1728; remainder 25; +16=1744; remainder 9; +8=1752; remainder 1; +1=1753. So bits: positions: 10? 2^10=1024 present. So yes.
Then x=1: bits = (1753 | (1753<<1)) & mask. etc. Should stay having 10.
x=9: bits = ... finally check.
Second test: n=3 K=2, numbers:1,3,4.
mask=(1<<3)-1=7.
x=1 <=2: bits=(1|(1<<1))&7= (1|2)=3&7=3 (bits 0,1)
x=3>2 skip.
x=4>2 skip.
bits>>2 &1? 3>>2=0 => 0.
Works.
Now confirm that we correctly handle case where numbers may be exactly K: e.g., N=1 K=5, number 5. x=5<=5: bits=1| (1<<5) = 33, mask= (1<<6)-1=63, bits=33. Check bits>>5: 33>>5=1, so output 1.
Now confirm for numbers equal to 0: N=2 K=5, numbers 0,5. x=0 <=5: bits = 1|(1<<0)=1|1=1, no change. x=5: bits=1|(1<<5)=33, output 1. Works.
Now confirm for numbers exactly K but also larger numbers: fine.
Thus solution.
Now about time: For each test case we do for each x: if x<=K, then bits = (bits | (bits << x)) & mask. This involves shift left of bits by x (x up to K) and OR and AND. The shift operation may be O(len(bits)) which is O(K/word_size). Since K<1000, it's small.
Now final answer: Provide the code with solve() and main. We'll include docstring maybe.
One more: The problem says "Output T lines, one for each test case. Every line should be either 0 or 1". So we output as described.
Now produce final output.
But we must be careful about reading input: The first line contains T, then for each test case, line contains N and K, next line contains N numbers. However, it's possible that the numbers might be spread across multiple lines? Usually not, but using split is robust.
Edge: There might be blank lines? split will ignore.
Thus final.
Now let's think about any potential overflow or performance with mask creation: mask = (1 << (K+1)) - 1, for K up to 999, that's a 1000-bit integer, trivial.
Now consider alternative: We could use Python's built-in 'int.bit_length' but not needed.
Thus final answer is done.
But note: There's an alternative using DP with boolean array but bitset is fine.
Now we should provide explanation.
Now produce final answer: We'll include the code and brief explanation.
Given the instructions: "You are an AI assistant that responds to the user's request." The user asked: "Write Python code to solve the problem." So we provide final code.
We'll ensure we define a function solve() and call it.
Now final code:
import sys
def solve():
data = sys.stdin.buffer.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
n = int(next(it)); K = int(next(it))
bits = 1
mask = (1 << (K+1)) - 1
for i in range(n):
x = int(next(it))
if x <= K:
bits = (bits | (bits << x)) & mask
out.append('1' if (bits >> K) & 1 else '0')
sys.stdout.write('\n'.join(out))
if name == "main":
solve()
Add comment if needed.
But wait: There's a nuance: For subset sum, using bitset method as described works for 0/1 knapsack (each element at most once). Since we are to find subset (each element used at most once), that's correct.
Now check for cases where numbers can be zero: It works, but note that if there are many zeros, they don't affect reachable sums. However, the presence of zeros could cause infinite loops? No.
Now all good.
Now potential improvement: If K is 0? But constraint says >0, but we can handle: if K==0, answer is always 1 because empty subset sum 0. But not needed.
Now final answer.
We should also note that we skip numbers > K; this is safe.
Now think about correctness with mask: After each update, we AND with mask to discard sums > K. However, consider a scenario: we have numbers that sum to something > K, but we discard those sums; that's fine because we only care about exactly K. However, could a sum > K later be reduced by negative numbers? No, all numbers are non-negative, so sums only increase.
Thus safe.
Now I think it's good.
But one more thing: The bitset method using integer and shift is essentially the same as using Python's built-in 'int' as bitset. However, the order of updating from low to high in this one-step assignment is equivalent to doing the 0/1 knapsack update because we are using the old bitset for shift, not the updated one. That's correct.
Now I'll produce final answer with explanation.
Also note that the problem statement might have ambiguous requirement: "0 < T < 1000" etc. It's fine.
Now final. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
it = iter(data)
t = int(next(it))
out_lines = []
code
for _ in range(t):
n = int(next(it))
K = int(next(it))
# bit i is 1 if sum i can be formed
bits = 1
mask = (1 << (K + 1)) - 1 # keep only bits 0..K
for _ in range(n):
x = int(next(it))
if x <= K: # numbers larger than K can never help
bits = (bits | (bits << x)) & mask
out_lines.append('1' if (bits >> K) & 1 else '0')
sys.stdout.write('\n'.join(out_lines))