0
点赞
收藏
分享

微信扫一扫

acwing 851

晒大太阳了 2022-02-05 阅读 75

#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 100, M = 1e5 + 100;

int n, m;
int head[N], ver[M], w[M], e[M], tot;
int d[N];
int v[N];
queue<int> q;

void add(int x, int y, int z)
{
    ++ tot;
    ver[tot] = y;
    w[tot] = z;
    e[tot] = head[x];
    head[x] = tot;
}

int main()
{
    cin >> n >> m;
    for (int i = 1, x, y, z; i <= m; i ++) 
    {
        cin >> x >> y >> z;
        add(x, y, z);
        //add(y, x, z);
    }
    memset(d, 0x3f, sizeof d);
    memset(v, false, sizeof v);
    d[1] = 0;
    
    q.push(1);
    v[1] = true;
    while (q.size())
    {
        int x = q.front();
        q.pop(); v[x] = false;
        for (int i = head[x]; i; i = e[i])
        {
            int y = ver[i], z = w[i];
            if (d[y] > d[x] + z)
            {
                d[y] = d[x] + z;
                if (!v[y]) 
                {
                    q.push(y);
                    v[y] = true;
                }
            }
        }
    }
    if (d[n] >= 0x3f3f3f3f) cout << "impossible" << endl;
    else cout << d[n] << endl;
    return 0;
}

举报

相关推荐

851. spfa求最短路

acwing 122

传送AcWing

acwing 170

acwing 120

acwing 341

acwing 849

acwing 349

0 条评论