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)
相关文章推荐
- 1030. Travel Plan (30)-PAT甲级真题
- PAT甲级1030. Travel Plan (30)
- pat甲级1030. Travel Plan (30)
- PAT 甲级 1030. Travel Plan (30)
- PAT 1030. Travel Plan (30)
- 1030. Travel Plan (30) PAT
- PAT (Advanced) 1030. Travel Plan (30)
- PAT甲级1030. Travel Plan(30)
- PAT (Advanced Level) 1030. Travel Plan (30)
- 1030. Travel Plan (30)-PAT甲级真题(Dijkstra + DFS,输出路径,边权)
- PAT (Advanced Level) 1030. Travel Plan (30) Dijkstra最短路径
- PAT - 甲级 - 1030. Travel Plan (30) (Dijkstra+DFS)
- PAT(A) - 1030. Travel Plan (30)
- 【PAT】1030. Travel Plan (30)
- PAT-A-1030. Travel Plan (30)
- PAT 甲级 1030. Travel Plan (30)
- PAT_A 1030. Travel Plan (30)
- Python实现Pat 1034. Head of a Gang (30)
- Python实现Pat 1049. Counting Ones (30)
- PAT 1030. Travel Plan (30)(Dijkstra,最短路径的同时计算最小奥cost)