An established group of scientists are working on finding solution to NP hard problems.…
- User
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 < 1000Output 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
pythondef subset_sum(): import sys input = sys.stdin.read().split() idx = 0 T = int(input[idx]) idx += 1 for _ in range(T): N, K = int(input[idx]), int(input[idx+1]) idx +=2 S = list(map(int, input[idx:idx+N])) idx +=N if K in S: print(1) continue filtered = [x for x in S if x < K and x != 0] sum_filtered = sum(filtered) if sum_filtered < K: print(0) continue dp = [False]*(K+1) dp[0] = True for num in filtered: for j in range(K, num-1, -1): if dp[j - num]: dp[j] = True if dp[K]: break print(1 if dp[K] else 0) subset_sum()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.