您的位置:首页 > 编程语言 > Python开发

Python实现Pat 1030. Travel Plan (30)

2017-12-08 17:52 274 查看

题目

A traveler’s map gives the distances between cities along the highways, together with the cost of each highway. Now you are supposed to write a program to help a traveler to decide the shortest path between his/her starting city and the destination. If such a shortest path is not unique, you are supposed to output the one with the minimum cost, which is guaranteed to be unique.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 4 positive integers N, M, S, and D, where N (<=500) is the number of cities (and hence the cities are numbered from 0 to N-1); M is the number of highways; S and D are the starting and the destination cities, respectively. Then M lines follow, each provides the information of a highway, in the format:

City1 City2 Distance Cost

where the numbers are all integers no more than 500, and are separated by a space.

Output Specification:

For each test case, print in one line the cities along the shortest path from the starting point to the destination, followed by the total distance and the total cost of the path. The numbers must be separated by a space and there must be no extra space at the end of output.

Sample Input

4 5 0 3

0 1 1 20

1 3 2 30

0 3 4 10

0 2 2 20

2 3 1 20

Sample Output

0 2 3 3 40

实现

#树的遍历。Python中注意list的list的初始化,避免浅复制
def dfs(s,dist,cost):
global D,path,minD,minP,minC
if s==D:
if dist<minD or (dist==minD and cost<minC) :
minD=dist
minC=cost
minP=path[:]
return
elif dist>minD:
return
else:
for p in tree[s]:
if visit[p]==False:
visit[p]=True
path.append(p)
dfs(p,dist+dists[s][p],cost+costs[s][p])
visit[p]=False
path.pop()
return

MAX=10000
N,M,S,D=[int(x) for x in input().split(' ')]
visit=[False]*(N)
tree={}
dists=[]
costs=[]
tmp=[MAX]*N
for i in range(M):
dists.append(tmp[:])
costs.append(tmp[:])
for i in range(N):
tree[i]=[]
for i in range(M):
a,b,c,d=[int(x) for x in input().split(' ')]
tree[a].append(b)
tree[b].append(a)
dists[a][b]=c
dists[b][a]=c
costs[a][b]=d
costs[b][a]=d
path=[]
minP=[]
cost=0
dist=0
minC=MAX
minD=MAX
visit[S]=True
path.append(S)
dfs(S,dist,cost)
for p in minP:
print(p,end=' ')
print (minD,minC)


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: