最短路径 dj 迪杰斯特拉dijkstra

本文介绍了一个关于寻找牛Bessie从牧场返回谷仓的最短路径的问题,并提供了一段C++代码实现。该算法利用了Dijkstra算法来解决带有权重的无向图中的最短路径问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

DJ

直接看题:

Til the Cows Come Home

Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible.

Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.

Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.

Input

* Line 1: Two integers: T and N

* Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.

Output

* Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.

Sample Input

5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

Sample Output

90

Hint

INPUT DETAILS:

There are five landmarks.

OUTPUT DETAILS:

Bessie can get home by following trails 4, 3, 2, and 1.

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 2005;
const int INF = (1 << 31) - 1;

typedef pair<int, int> pii;
priority_queue<pii, vector<pii>, greater<pii> >q;

int edge[MAXN][MAXN];
int d[MAXN];
int n, m;//n 条边 , m 个顶点

int Dj(int start) {
    bool used[MAXN] = {0};
    for (int i = 1; i <= n; i++) {
        d[i] = (i == start ? 0 : INF);
    }
    q.push(make_pair(d[start], start));
    while (!q.empty()) {
        pii u = q.top();
        q.pop();
        int x = u.second;
        if (used[x]) {
            continue;
        }
        used[x] = true;
        for (int j = 1; j <= n; j++) {
            if (!used[j] && edge[x][j] < INF && d[j] > d[x] + edge[x][j]) {
                d[j] = d[x] + edge[x][j];
                q.push(make_pair(d[j], j));
            }
        }
    }
    return d[n];
}

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (i == j) {
                edge[i][j] == 0;
            }
            else {
                edge[i][j] = INF;
            }
        }
    }
    int u, v, w;
    for (int i = 1; i <= m; i++) {
        cin >> u >> v >> w;
        if (w < edge[u][v]) {
            edge[u][v] = w;
            edge[v][u] = w;
        }
    }
//    cout << "下面是打印邻接矩阵:\n";
//    for (int i = 1; i <= n; i++) {
//        for (int j = 1; j <= n; j++) {
//            if (edge[i][j] == INF) {
//                cout << "∞\t";
//            }
//            else {
//                cout << edge[i][j] << "\t";
//            }
//        }
//        cout << "\n\n";
//    }
    cout << Dj(1) << endl;
    return 0;
}

 

迪杰斯特拉(Dijkstra's Algorithm)是一种用于寻找有向图或无向图中最短路径的经典算法,通常用于单源最短路径问题。在C++中实现迪杰斯特拉,我们可以按照以下几个步骤: 1. **定义数据结构**: - 使用`std::priority_queue`来管理未处理的顶点及其距离估计。 - 定义一个辅助数组`dist`来记录每个顶点到已知源点的距离,初始时除了源点外全部设置为无穷大(通常用INT_MAX)。 - 可能还需要一个布尔数组`visited`来标记哪些顶点已被访问过。 2. **函数原型**: ```cpp void dijkstra(std::vector<std::pair<int, int>>& graph, int src, std::vector<int>& dist, std::vector<bool>& visited); ``` 其中`graph`是一个二维数组或邻接表,表示图的连接;`src`是源点的索引;`dist`和`visited`分别是距离数组和访问标志数组。 3. **核心算法流程**: - 将源点加入优先队列,初始距离设为0。 - 循环直到优先队列为空: a. 弹出优先队列中距离最小的未访问顶点u。 b. 更新其相邻顶点v的距离,如果通过u到v的距离小于当前已知距离,则更新`dist[v]`。 c. 标记顶点u为已访问。 - 结果会在`dist`数组中,`dist[i]`就是源点到顶点i的最短距离。 4. **示例代码片段**: ```cpp while(!pq.empty()) { int u = pq.top().second; // 获取下标 pq.pop(); visited[u] = true; // 更新相邻顶点v的距离 for (auto &edge : graph[u]) { int v = edge.first; int weight = edge.second; if (!visited[v] && dist[u] + weight < dist[v]) { dist[v] = dist[u] + weight; pq.push({dist[v], v}); } } } ``` 5. **输出结果**: 仅当`dist`数组完整计算完成后,可以遍历数组,获取从源点到所有其他顶点的最短距离。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值