为什么这个 Dijkstra 不适用于有向图

Why is this Dijkstra not working on directed graph

此 dijkstra 代码不适用于有向图

例如这个测试用例:

4 
2 
1
7
1 2 1
1 3 1
2 1 1
2 4 1
3 1 1
3 4 1
4 3 1

Click to view Graph diagram for above testcase

边 2 -> 4 只是一种方式,而算法的行为就好像它是 2 向的。 4 到 2 之间的最短路径应为 3,而以下代码给出 1 输出:

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

const int N = 1e5+10;
const int INF = 1e9+10;
vector<pair<int,int>> g[N];
vector<int> vis(N,0);
vector<int> dist(N, INF);


void bfs(int source){

    set<pair<int,int>> st;

    st.insert({0,source});
    dist[source] = 0;

    while(st.size()>0){
        auto curr = *st.begin();
        int wt_v = curr.first;
        int v = curr.second;
        st.erase(st.begin());

        if(vis[v]) continue;
        vis[v] = 1;
        
        for(auto child:g[v]){

            int child_v = child.first;
            int wt = child.second;

            if(dist[v] + wt < dist[child_v]){
                dist[child_v] = dist[v] + wt;
                st.insert({dist[child_v],child_v});
            }
        }
    }
}


int main(){
    int n; cin>>n;
    int e; cin>>e;
    int t; cin>>t;
    int m; cin>>m;

    for (int i = 0; i < m; ++i){
        int v1,v2,wt; cin>>v1>>v2>>wt;
        g[v1].push_back({v2,wt});
    }

    bfs(e);

    for (int i = 1; i <= n; ++i){
        cout<<dist[i]<<endl;
    }
}

如果你想要4比2,那么你必须改变你的输入。第二行应该是 4

照原样,您的输出很难理解。让我们这样做

bfs(e);

for (int i = 1; i <= n; ++i){
    cout<<"dist from " << e << " to " <<i 
        << " is " <<dist[i]<<endl;

所以现在,输入这个

4 
4
1
7
1 2 1
1 3 1
2 1 1
2 4 1
3 1 1
3 4 1
4 3 1

输出是

dist from 4 to 1 is 2
dist from 4 to 2 is 3
dist from 4 to 3 is 1
dist from 4 to 4 is 0