Python实现Pat 1030. Travel Plan (30)

来源:互联网 发布:ubuntu ssh安装 编辑:程序博客网 时间:2024/06/06 04:11

题目

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()    returnMAX=10000N,M,S,D=[int(x) for x in input().split(' ')]visit=[False]*(N)tree={}dists=[]costs=[]tmp=[MAX]*Nfor 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]=dpath=[]minP=[]cost=0dist=0minC=MAXminD=MAXvisit[S]=Truepath.append(S)dfs(S,dist,cost)for p in minP:    print(p,end=' ')print (minD,minC)

这里写图片描述

原创粉丝点击