dijkstra求调全RE

P4779 【模板】单源最短路径(标准版)

Chen_Three @ 2024-07-24 21:30:57

#include<bits/stdc++.h>
using namespace std;
#define ll long long
struct edge {
    int to, weight;
    edge(int to, int weight) : to(to), weight(weight) {}
};
int n, m;
vector<vector<edge> > graph(n, vector<edge>());
vector<int> Dist(n,0);
vector<int> Prev(n,0);

void dijkstra(int source) {
    int n = graph.size();
    vector<bool> s(n, false);
    fill(Dist.begin(), Dist.end(), INT_MAX);
    fill(Prev.begin(), Prev.end(), -1);
    Dist[source] = 0;
    for (int i = 1; i <= n; i++) {
        int u = -1;
        for(int j = 1; j <= n; j++){
            if(!s[j] && (u == -1 || Dist[j] < Dist[u])){
                u = j;
            }
        }
        s[u] = 1;
        for(edge e:graph[u]){
            if(!s[u] && Dist[e.to] > Dist[u] + e.weight){
                Dist[e.to] = Dist[u] + e.weight;
                Prev[e.to] = u;
            }
        }
    }
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    int source;
    cin >> source;
    for(int i = 1; i <= m; i++){
        int u, v, w;
        cin >> u >> v >> w;
        graph[u].push_back(edge(v, w));
    }
    dijkstra(source);
    for(int i = 1; i <= n; i++){
        cout << Dist[i];
    }
    return 0;
}

by crh_ @ 2024-07-29 00:22:29

@Chen_Three 你这是不是写挂了,我dev跑不动


by crh_ @ 2024-07-29 00:33:59

@crh_ 然后捏那个,dijikatra函数内,我觉得老师可能理解错了,要不去看看题解...?


by crh_ @ 2024-07-29 00:39:22

呃呃我没太看懂老师的for int j = 1那个循环 然后下面

for(edge e:graph[u]){
    if(!s[u] && Dist[e.to] > Dist[u] + e.weight){
      //这里老师判断了!s[u]之后是不是也应该把标记打回去
      //!s[]这里下标是不是错了,应该不是u
        Dist[e.to] = Dist[u] + e.weight;
        Prev[e.to] = u;
    }
}

by crh_ @ 2024-07-29 00:41:16

要不老师再理理思路? 当然也可能是我太菜了看不懂

我改了一下发现问题有点点多.......嘿嘿


by Chen_Three @ 2024-07-29 11:15:12

@crh_ 啊抱歉我不太会写dijkstra,上网搜的,我去看看题解吧


by crh_ @ 2024-07-29 14:12:33

@Chen_Three 嗯嗯


|