Dijkstra求最短路 (图论基础 )

输入样例:
3 3
1 2 2
2 3 1
1 3 4
输出样例:
3

题解:

对于求解最短路径的最优方法当然是依次求得每个点的最短,然后遍历更新起点到所有点的最短路径,并储存在点里。

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector> 
#include <map>
#include <stack>
#include <queue>
#include <set>
using namespace std;
typedef long long ll;
const int maxx = 1000050;
ll n, m, t, now, l, r, c, b ,T ,k ;
const int INF = 0x3f3f3f3f;
const double pi = acos(-1.0);
int pie[] = {3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4,6,2,6,4,3,3,8,3,2,7,9,5,0,2,8,8,4,1,9,7,1,6,9,3,9,9,3,7,5,1,0};
ll ans;
int step[50][50][50];
int nx, ny, nz, ex, ey, ez;
int e[maxx];
int sum[20221199];
int w[510][510];
int  dp[225][225];
ll mod = 1e9 + 7;
bool  st[maxx];
int node()
{
    memset(e, 0x3f, sizeof(e));//由于是在求最小值所以将其都初始化为无穷
    e[1] = 0;//将第一步初始化为起点
    for (int i = 0; i < n; i++)//开始遍历
    {
        int t = -1;//没有确定最短路径的结点中距离原点最近的点
        for (int j = 1; j <= n; j++)//遍历e步数数组,找到没有确定最短路径的结点中距离原点最近的点t
        {
            if (!st[j] && (t == -1 || e[t] > e[j]))
            {
                t = j;
            }
        }
        st[t] = true;
        for (int j = 1; j <= n; j++)//遍历寻找最短路径
        {
            e[j] = min(e[j], e[t] + w[t][j]);
        }
    }
    if (e[n] == 0x3f3f3f3f)//如果没找到最短的路径甚至于到达不了
    {
        return -1;//返回-1
    }
    else//否则返回最短
    {
        return e[n];
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    memset(w, 0x3f, sizeof(w));
    for (int i = 1; i <= m; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        w[a][b] = min(w[a][b], c);
    }
    int num = node();
    cout << num << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Tang_7777777

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

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

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

打赏作者

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

抵扣说明:

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

余额充值