1 条题解

  • 1
    @ 2024-7-25 13:41:35

    参考答案:

    #include<iostream>
    #include<queue>
    #include<cstring>
    
    using namespace std;
    
    const int N = 200010;
    int e[N], ne[N], h[N], w[N], idx;
    int dis[N];
    int st[N];
    int n, m;
    
    void add(int a, int b, int c)
    {
        e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
    }
    
    void spfa()
    {
        memset(dis, 0x3f, sizeof(dis));
        dis[1] = 0;
        queue<int > q;
        q.push(1);
    
        while (q.size())
        {
            int t = q.front();
            q.pop();
            st[t] = 0;
            for (int i = h[t]; i != -1; i = ne[i])
            {
                int j = e[i];
                if (dis[j] > dis[t] + w[i])
                {
                    dis[j] = dis[t] + w[i];
                    if (!st[j])
                    {
                        q.push(j);
                        st[j] = 1;
                    }
                }
            }
        }
    }
    int main()
    {
        cin >> n >> m;
        memset(h, -1, sizeof(h));
    
        for (int i = 1; i <= m; ++i)
        {
            int a, b, c;
            cin >> a >> b >> c;
            add(a, b, c);
        }
    
        spfa();
    
        if (dis[n] == 0x3f3f3f3f) cout << "No path";
        else cout << dis[n];
    
        return 0;
    }
    
    • 1

    信息

    ID
    98
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    4
    已通过
    1
    上传者