Lintcode 1891 · Travel Plan go

/**
1891 · Travel Plan
Algorithms
Medium
Accepted Rate
60%

DescriptionSolutionNotesDiscussLeaderboard
Description
There are n cities, and the adjacency matrix arr represents the distance between any two cities.arr[i][j] represents the distance from city i to city j .Alice made a travel plan on the weekend. She started from city 0, then she traveled other cities 1 ~ n-1, and finally returned to city 0. Alice wants to know the minimum distance she needs to walk to complete the travel plan. Return this minimum distance. Except for city 0, every city can only pass once, and city 0 can only be the starting point and destination. Alice can’t pass city 0 during travel.

n<=10
arr[i][j]<=10000

Example
Example 1:

Input:
[[0,1,2],[1,0,2],[2,1,0]]
Output:
4
Explanation:
There are two possible plans.
The first, city 0-> city 1-> city 2-> city 0, cost = 5.
The second, city 0-> city 2-> city 1-> city 0, cost = 4.
Return 4
Example 2:

Input:
[[0,10000,2],[5,0,10000],[10000,4,0]]
Output:
11
Tags

https://blog.csdn.net/qq_46105170/article/details/110155730

https://www.lintcode.com/problem/1891/
*/

const INT_MAX = int(^uint(0) >> 1)

/**
 * @param arr: the distance between any two cities
 * @return: the minimum distance Alice needs to walk to complete the travel plan
 */
func travelPlan(arr [][]int) int {
	// Write your code here.
	if arr == nil || len(arr) == 0 {
		return 0
	}
	var n int = len(arr)
	var dp = make([][]int, 1<<uint8(n))
	for i := 0; i < 1<<uint8(n); i++ {
		dp[i] = make([]int, n)
	}
	for i := 0; i < (1<<uint8(n)); i++ {
		for j := 0; j < n; j++ {
			dp[i][j] = INT_MAX - 10000
		}
	}
	dp[(1<<uint8(n))-1][0] = 0
	for s := 1<<uint8(n) - 2; s >= 0; s-- {
		for v := 0; v < n; v++ {
			for u := 0; u < n; u++ {
				if (s>>uint8(u))&1 == 0 {
					dp[s][v] = Min(dp[s][v], dp[s|(1<<uint8(u))][u]+arr[v][u])
				}
			}
		}
	}
	return dp[0][0]
}

func Min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值