Grok 4.1 Fast· xai
Frontier Reasoning Traces
Implement an efficient solution for the traveling salesman problem using dynamic…
- User
Implement an efficient solution for the traveling salesman problem using dynamic programming.
- Assistant
import sys INF = float('inf') def tsp_dp(dist): n = len(dist) if n == 0: return 0 # dp[mask][pos] = min cost to visit subset mask, ending at pos (starting from 0) dp = [[INF] * n for _ in range(1 << n)] dp[1][0] = 0 # Start at city 0, mask with only 0 visited # Fill DP table for mask in range(1 << n): for u in range(n): if dp[mask][u] == INF: continue for v in range(n): if mask & (1 << v): continue # v already visited new_mask = mask | (1 << v) dp[new_mask][v] = min(dp[new_mask][v], dp[mask][u] + dist[u][v]) # Find min cost to return to 0 from full mask full_mask = (1 << n) - 1 min_cost = INF for u in range(1, n): # End at any city except 0 if dp[full_mask][u] != INF: min_cost = min(min_cost, dp[full_mask][u] + dist[u][0]) return min_cost if min_cost != INF else -1 # Read input input = sys.stdin.read data = input().split() n = int(data[0]) index = 1 dist = [] for i in range(n): row = [int(data[index + j]) for j in range(n)] dist.append(row) index += n # Compute and output result = tsp_dp(dist) print(result)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.