选择最佳线路( 最短路)

有一天,琪琪想乘坐公交车去拜访她的一位朋友。

由于琪琪非常容易晕车,所以她想尽快到达朋友家。

现在给定你一张城市交通路线图,上面包含城市的公交站台以及公交线路的具体分布。

已知城市中共包含 n 个车站(编号1~n)以及 m 条公交线路。

每条公交线路都是 单向的,从一个车站出发直接到达另一个车站,两个车站之间可能存在多条公交线路。

琪琪的朋友住在 s 号车站附近。

琪琪可以在任何车站选择换乘其它公共汽车。

请找出琪琪到达她的朋友家(附近的公交车站)需要花费的最少时间。

输入格式
输入包含多组测试数据。

每组测试数据第一行包含三个整数 n,m,s,分别表示车站数量,公交线路数量以及朋友家附近车站的编号。

接下来 m 行,每行包含三个整数 p,q,t,表示存在一条线路从车站 p 到达车站 q,用时为 t。

接下来一行,包含一个整数 w,表示琪琪家附近共有 w 个车站,她可以在这 w 个车站中选择一个车站作为始发站。

再一行,包含 w 个整数,表示琪琪家附近的 w 个车站的编号。

输出格式
每个测试数据输出一个整数作为结果,表示所需花费的最少时间。

如果无法达到朋友家的车站,则输出 -1。

每个结果占一行。

数据范围
n≤1000,m≤20000,
1≤s≤n,
0<w<n,
0<t≤1000
输入样例:
5 8 5
1 2 2
1 5 3
1 3 4
2 4 7
2 5 6
2 3 5
3 5 1
4 5 1
2
2 3
4 3 4
1 2 3
1 3 4
2 3 2
1
1
输出样例:
1
-1

在这里插入图片描述

原问题:从每个起点出发,到达任意终点的所有路线的距离的最小值

加上虚拟源点之后的问题:从虚拟源点出发,到达任意终点的所有路线
的距离的最小值

其中虚拟源点到起点的权值为0
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1010, M = 30010, INF = 0x3f3f3f3f;

int n, m, T;
int h[N], e[M], w[M], ne[M], idx;
int dist[N], q[N];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

int spfa()
{

    memset(dist, 0x3f, sizeof dist);

    dist[0]=0;
    int hh = 0, tt = 1;
    q[0] = 0;
   
    while (hh != tt)
    {
        int t = q[hh ++ ];
        if (hh == N) hh = 0;

        st[t] = false;
        for (int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > dist[t] + w[i])
            {
                dist[j] = dist[t] + w[i];
                if (!st[j])
                {
                    q[tt ++ ] = j;
                    if (tt == N) tt = 0;
                    st[j] = true;
                }
            }
        }
    }
    if (dist[T] == INF) return -1;
    return dist[T];
}

int main()
{
    while (cin>>n>>m>>T)
    {
        memset(h, -1, sizeof h);//初始化邻接表
        idx = 0;

        while (m -- )
        {
            int a, b, c;
            scanf("%d%d%d", &a, &b, &c);
            add(a, b, c);
        }
        int scnt;
        scanf("%d", &scnt);
        
        while (scnt -- ){
        int u;
        scanf("%d", &u);
        add(0,u,0);//建立虚拟原点0
      }

        cout<<spfa()<<endl;
    }

    return 0;
}

思路2:从终点出发反向做一次最短路,然后在所有能选的起点中选min
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1010, M = 30010, INF = 0x3f3f3f3f;

int n, m, T;
int h[N], e[M], w[M], ne[M], idx;
int dist[N], q[N];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

void spfa()
{

    memset(dist, 0x3f, sizeof dist);

    dist[T]=0;
    int hh = 0, tt = 1;
    q[0] = T;
    
    while (hh != tt)
    {
        int t = q[hh ++ ];
        if (hh == N) hh = 0;

        st[t] = false;
        for (int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > dist[t] + w[i])
            {
                dist[j] = dist[t] + w[i];
                if (!st[j])
                {
                    q[tt ++ ] = j;
                    if (tt == N) tt = 0;
                    st[j] = true;
                }
            }
        }
    }
    
}

int main()
{
    while (cin>>n>>m>>T)
    {
        memset(h, -1, sizeof h);//初始化邻接表
        idx = 0;

        while (m -- )
        {
            int a, b, c;
            scanf("%d%d%d", &a, &b, &c);
            add(b, a, c);//反向建立边
        }
        spfa();
        
        int scnt;
        scanf("%d", &scnt);
        int  res=INF;
        while (scnt -- ){
        int u;
        scanf("%d", &u);
        res=min(res,dist[u]);
      }
        if(res==INF)res=-1;
        cout<<res<<endl;
    }

    return 0;
}

### 单源短路径算法概述 单源短路径算法旨在计算从某个特定起点出发到达图中其他所有节点的短路径长度。这类算法适用于带权重的有向图或无向图,其中每条边都有一个非负或者可能为负的权重值[^1]。 #### 常见的单源短路径算法及其特性 以下是几种常见的单源短路径算法: 1. **Dijkstra算法** - Dijkstra算法基于贪心策略,通过逐步扩展当前已知的短路径来更新其他顶点的距离估计。该算法假设所有的边权均为非负数,因此不支持含有负权边的图结构[^2]。 - 它的主要特点是优先选择距离小的未访问节点进行扩展,并利用这些节点的信息进一步优化剩余节点的距离估计值[^4]。 2. **Bellman-Ford算法** - Bellman-Ford算法能够处理含负权边的图,甚至可以检测是否存在负环(即总权重为负的循环路径),这使得其适用范围更广[^3]。 - 此算法通过对每一条边重复执行松弛操作多 \(V-1\) 次(\(V\) 表示顶点数量),从而确保终得到的结果是优解。 3. **Floyd-Warshall算法** - 虽然严格意义上不属于单源短路径范畴,但它可以通过动态规划的方式高效地解决多对多之间的短路径问题,在某些场景下也可以间接服务于单源需求。 --- ### 算法实现详解 #### 1. Dijkstra算法 (Python 实现) 下面是一个简单的 Python 版本的 Dijkstra 算法实现,使用堆队列模块 `heapq` 来加速选取下一个要访问的节点过程: ```python import heapq def dijkstra(graph, start): distances = {node: float('inf') for node in graph} # 初始化所有节点距离为无穷大 distances[start] = 0 # 设置起始节点距离为零 priority_queue = [(0, start)] # 创建一个小根堆存储待探索节点 while priority_queue: current_distance, current_node = heapq.heappop(priority_queue) if current_distance > distances[current_node]: continue for neighbor, weight in graph[current_node].items(): distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(priority_queue, (distance, neighbor)) return distances ``` 此函数接受两个参数:一个是表示加权图的数据字典形式;另一个是指定的初始节点名称字符串。返回结果则是一张映射表记录着各个目标节点相对于原点的最佳可达成本。 #### 2. Bellman-Ford算法 (C++ 实现) 这里提供了一个 C++ 的贝尔曼福特算法模板代码片段供参考学习: ```cpp #include <bits/stdc++.h> using namespace std; struct Edge { int src, dest, weight; }; void bellmanFord(vector<Edge> edges, int V, int E, int source){ vector<int> dist(V, INT_MAX); dist[source] = 0; for(int i=0;i<V-1;i++){ for(auto edge : edges){ if(dist[edge.src]!=INT_MAX && dist[edge.src]+edge.weight<dist[edge.dest]){ dist[edge.dest]=dist[edge.src]+edge.weight; } } } // Check negative cycle bool hasNegativeCycle=false; for(auto edge : edges){ if(dist[edge.src]!=INT_MAX && dist[edge.src]+edge.weight<dist[edge.dest]){ cout << "Graph contains a negative-weight cycle"; hasNegativeCycle=true; break; } } if(!hasNegativeCycle){ for(int i=0;i<V;i++) printf("%d\t%d\n",i,dist[i]); } } ``` 上述程序定义了一种数据结构用来描述连接两结点间的弧线以及它们所携带的价值量度单位——重量。接着按照标准流程迭代调整直至收敛完成整个运算逻辑。 --- ### 总结对比分析 | 属性 | Dijkstra Algorithm | Bellman–Ford Algorithm | |-------------------|----------------------------|------------------------------| | 时间复杂度 | O((E+V)log⁡(V)) | O(VE) | | 是否允许负权 | 否 | 是 | | 应用领域 | 地理信息系统(GIS),路由协议等 | 计算机网络流量工程等领域 | 尽管两种技术都致力于寻找单一源头至目的地间优行走路线方案,但由于各自设计初衷不同导致实际表现有所差异。具体选用哪一种取决于应用场景的具体约束条件比如性能指标要求或是输入数据特征等因素影响下的综合考量[^1]. ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小王子y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值