Guest User

Untitled

a guest
Jul 7th, 2024
407
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. from collections import defaultdict, deque import random
  2. def generate_random_subset_sum(num_elements, target_sum_range): elements = [random.randint(1, 1000) for _ in range(num_elements)] target_sum = random.randint(1, target_sum_range)
  3. return elements, target_sum
  4. def build_graph(elements, target_sum): graph = defaultdict(list)
  5. for u in range(target_sum + 1):
  6. for e in elements:
  7. if u + e <= target_sum:
  8. graph[u].append(u + e) return graph
  9. def tarjan_scc(graph, n): index = 0
  10. indices = [-1] * (n + 1) lowlink = [-1] * (n + 1) on_stack = [False] * (n + 1) stack = []
  11. sccs = []
  12. def strong_connect(v): nonlocal index indices[v] = index lowlink[v] = index index += 1 stack.append(v) on_stack[v] = True
  13. for w in graph[v]:
  14. if indices[w] == -1:
  15. strong_connect(w)
  16. lowlink[v] = min(lowlink[v], lowlink[w]) elif on_stack[w]:
  17. lowlink[v] = min(lowlink[v], indices[w])
  18. if lowlink[v] == indices[v]: scc = []
  19. while True:
  20. w = stack.pop() on_stack[w] = False scc.append(w)
  21. if w == v:
  22. break sccs.append(scc)
  23. for v in range(n + 1): if indices[v] == -1:
  24. strong_connect(v) return sccs
  25.  
  26. def solve_subset_sum(elements, target_sum): graph = build_graph(elements, target_sum) sccs = tarjan_scc(graph, target_sum)
  27. print("Graph constructed:") for u in sorted(graph.keys()):
  28. print(f"{u}: {graph[u]}")
  29. reachable = [False] * (target_sum + 1)
  30. reachable[0] = True # Base case: sum of 0 is always reachable
  31. for scc in sccs:
  32. if any(reachable[v] for v in scc):
  33. for v in scc: reachable[v] = True
  34. print("Reachable sums after processing SCCs:") for i, r in enumerate(reachable):
  35. if r:
  36. print(i, end=' ')
  37. print()
  38. return reachable[target_sum]
  39. def main():
  40. elements = [713, 635, 466, 911, 568, 579, 820, 259, 529, 370, 785, 495, 748, 823, 702, 825, 723, 822,
  41. 142, 926, 896, 449, 292, 901, 397, 911, 146, 952, 723, 438, 537, 892, 899, 837, 75, 867, 696, 173, 834, 433, 451, 999, 986, 786, 124, 287, 758, 901, 457, 289, 3, 991, 452, 702, 134, 260, 376, 426, 764, 563, 7, 510, 341, 214, 354, 442, 467, 281, 756, 715, 482, 731, 648, 48, 998, 924, 315, 697, 209, 898, 185, 442, 52, 128, 528, 771, 308, 582, 925, 664, 605, 519, 836, 189, 597, 247, 233, 220, 147, 739]
  42. target_sum = 4122
  43. print(f"Elements: {elements}") print(f"Target Sum: {target_sum}")
  44. result = solve_subset_sum(elements, target_sum) print(f"Result: {'Subset exists' if result else 'No subset exists'}")
  45. if __name__ == "__main__": main()
Advertisement
Add Comment
Please, Sign In to add comment