PAT 1030 Travel Plan(30 分)

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

思路:DFS即可。

程序:

#include 
#include 
using namespace std;
int edge[501][501];
int cost[501][501];
int vis[501];
int minCost = 100000001;
int nowCost = 0;
int minDist = 100000001;
int nowDist = 0;
vector ans;
vector temp;
int n,m,s,d;
void dfs(int start)
{
  if(start == d)
  {
    if(nowDist < minDist)
    {
      minDist = nowDist;
      ans = temp;
      minCost = nowCost;
    }
    else if(nowDist == minDist)
    {
      if(nowCost < minCost)
      {
        ans = temp;
        minCost = nowCost;
      }
    }
    return;
  }
  for(int i = 0; i < n; i++)
  {
    if(edge[start][i] && vis[i] == 0)
    {
      nowDist += edge[start][i];
      vis[i] = 1;
      nowCost += cost[start][i];
      temp.push_back(i);
      dfs(i);
      nowDist -= edge[start][i];
      vis[i] = 0;
      nowCost -= cost[start][i];
      temp.pop_back();
    }
  }
}
int main()
{
  scanf("%d%d%d%d",&n,&m,&s,&d);
  for(int i = 0; i < m; i++)
  {
    int city1,city2,distance,Cost;
    scanf("%d%d%d%d",&city1,&city2,&distance,&Cost);
    edge[city1][city2] = edge[city2][city1] = distance;
    cost[city1][city2] = cost[city2][city1] = Cost;
  }
  vis[s] = 1;
  dfs(s);
  printf("%d ",s);
  for(int i = 0; i < ans.size(); i++)
  {
    printf("%d ",ans[i]);
  }
  printf("%d %d\n",minDist,minCost);
  return 0;
}

 

你可能感兴趣的:(PAT 1030 Travel Plan(30 分))