Advertisement
Iam_Sandeep

travelling sales man problem dp

Aug 7th, 2021
1,370
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. Given a matrix cost of size n where cost[i][j] denotes the cost of moving from city i to city j. Your task is to complete a tour from the city 0 (0 based index) to all other cities such that you visit each city atmost once and then at the end come back to city 0 in min cost.
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10. #User function Template for python3
  11. from functools import lru_cache
  12. import sys
  13. class Solution:
  14.     def total_cost(self, cost):
  15.         #Code here
  16.         n=len(cost)
  17.         v_all=(1<<n)-1
  18.         dp=[[-1 for i in range(n)] for j in range(1<<n)]
  19.         def compute(mask,pos):
  20.             if dp[mask][pos]!=-1:
  21.                 return dp[mask][pos]
  22.             if mask==v_all:
  23.                 return cost[pos][0]
  24.             else:
  25.                 ans=sys.maxsize
  26.                 for city in range(n):
  27.                     if (1<<city)&mask==0:
  28.                         temp=cost[pos][city]+compute((1<<city)|mask,city)
  29.                         ans=min([temp,ans])
  30.             dp[mask][pos]=ans
  31.             return ans
  32.         return compute(1,0)
  33.    
  34.                        
  35.            
  36.  
  37. #{
  38. #  Driver Code Starts
  39. #Initial Template for Python 3
  40.  
  41. if __name__ == '__main__':
  42.     T=int(input())
  43.     for i in range(T):
  44.         n = int(input())
  45.         cost = []
  46.         for _ in range(n):
  47.             cost.append(list(map(int, input().split())))
  48.         obj = Solution()
  49.         ans = obj.total_cost(cost)
  50.         print(ans)
  51.  
  52. # } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement