美文网首页
【PAT_1030】Travel Plan

【PAT_1030】Travel Plan

作者: 6J | 来源:发表于2018-07-31 14:50 被阅读0次

题目描述:

旅行者的地图给出了高速公路沿线城市之间的距离以及每条高速公路的成本。 写一个程序来帮助旅行者决定他/她的起始城市和目的地之间的最短路径。 如果这样的最短路径不是唯一的,那么应该输出具有最小成本的路径,这保证是唯一的。

输入:

第一行:N(城市数0~N-1),M(公路条数),S(出发点),D(目的地)

之后M行:City1 City2 Distance Cost

输出:

沿着从起点到目的地的最短路径沿城市打印一行,然后是总距离和路径的总成本。 数字必须用空格分隔,输出结尾必须没有多余的空格。

解题思路:

实际上还是求两点之间的最短路径问题,通过dfs遍历比较得到最优解

代码:

#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct Travel {
    int dis=-1, money;
};
int mincost = 100000000, mindis = 100000000;
vector<int>res;
void dfs(vector<vector<Travel> > &graph, vector<bool> &mark,vector<int>&path, int start, int destination,int n,int dis,int costs) {
    path.push_back(start);
    mark[start] = true;
    if (start == destination) {
        if (dis < mindis) {
            mindis = dis;
            res = path;
            mincost = costs;
        }
        else if (dis == mindis&&costs<mincost) {
            res = path;
            mincost = costs;
        }
    }
    else {
        for (int i = 0; i < n; i++) {
            if (graph[start][i].dis!=-1 && mark[i] == false) {
                dfs(graph, mark,path, i, destination, n,dis+ graph[start][i].dis,costs+ graph[start][i].money);
            }
        }
    }
    mark[start] = false;
    path.pop_back();
}
int main() {
    int n, m, s, d;
    cin >> n >> m >> s >> d;
    vector<vector<Travel> > graph(n,vector<Travel>(n));
    int a, b, p, c;
    Travel t;
    vector<bool> mark(n, false);
    for (int i = 0; i < m; i++) {
        cin >> a >> b >> p >> c;
        t.dis = p;
        t.money = c;
        graph[a][b] = t;
        graph[b][a] = t;
    }
    vector<int>path;
    dfs(graph, mark,path, s, d, n, 0, 0);
    for (int i = 0; i < res.size(); i++) {
        cout << res[i] << " ";
    }
    cout << mindis << " " << mincost << endl;
    return 0;
}
image.gif

相关文章

  • 【PAT_1030】Travel Plan

    题目描述: 旅行者的地图给出了高速公路沿线城市之间的距离以及每条高速公路的成本。 写一个程序来帮助旅行者决定他/她...

  • Travel Plan

    下午两点出发机场✈️ 乘坐三号线地铁,在两路口换乘一号线,在七星岗下车,从一号口出,顺导航走不到十分钟即可到达 入...

  • Travel plan

    USA 国家公园 9-12月 学期中 NBA TRIP:a. 波特兰开拓者b. 金州勇士c. 费城76人d. 波士...

  • Travel plan

    I think maybe everyone likes to travel to a place, And st...

  • My Travel plan

    I’m going to go hiking a mountain nearby my house, I d...

  • 大爱无痕,践行自我

    LNT原则: 1)户外的行前准备Plan ahead and prepare2)户外行走与露营Travel and...

  • PAT-1030-Travel Plan

    A traveler's map gives the distances between cities along...

  • Travel in GuangZhou♡ Plan&Expen

    12.27 从南京禄口机场飞往广州新白云机场 12.28 多宝路&沙面岛&上下九步行街 12.29 北京路&文明路...

  • 黄姚:一份宁静,寻梦千年古镇

    左小子的背包 旅行|计划|音乐|网文 旅行计划 Travel Plan 广西第二站,贺州。 贺州位居广西东部,是...

  • 梧州,一座古老的城

    旅行计划 travel plan 广西第一站,梧州。 梧州位于广西东部,其历史久远,文化积淀深厚,是一座拥有40...

网友评论

      本文标题:【PAT_1030】Travel Plan

      本文链接:https://www.haomeiwen.com/subject/lhkhvftx.html