Python实现Pat 1028. List Sorting (25)

水深无声 2022-06-04 08:14 292阅读 0赞

题目

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

  1. #树或者图的遍历。注意Python里list的list的初始化,避免浅复制
  2. def dfs(s,dist,cost):
  3. global D,path,minD,minP,minC
  4. if s==D:
  5. if dist<minD or (dist==minD and cost<minC) :
  6. minD=dist
  7. minC=cost
  8. minP=path[:]
  9. return
  10. elif dist>minD:
  11. return
  12. else:
  13. for p in tree[s]:
  14. if visit[p]==False:
  15. visit[p]=True
  16. path.append(p)
  17. dfs(p,dist+dists[s][p],cost+costs[s][p])
  18. visit[p]=False
  19. path.pop()
  20. return
  21. MAX=10000
  22. N,M,S,D=[int(x) for x in input().split(' ')]
  23. visit=[False]*(N)
  24. tree={}
  25. dists=[]
  26. costs=[]
  27. tmp=[MAX]*N
  28. for i in range(M):
  29. dists.append(tmp[:])
  30. costs.append(tmp[:])
  31. for i in range(N):
  32. tree[i]=[]
  33. for i in range(M):
  34. a,b,c,d=[int(x) for x in input().split(' ')]
  35. tree[a].append(b)
  36. tree[b].append(a)
  37. dists[a][b]=c
  38. dists[b][a]=c
  39. costs[a][b]=d
  40. costs[b][a]=d
  41. path=[]
  42. minP=[]
  43. cost=0
  44. dist=0
  45. minC=MAX
  46. minD=MAX
  47. visit[S]=True
  48. path.append(S)
  49. dfs(S,dist,cost)
  50. for p in minP:
  51. print(p,end=' ')
  52. print (minD,minC)

这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,292人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PAT乙级1028

    1028 人口普查 (20 分) 某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。 这里确保每个输入的日期都是合法的,但不一定是合理的