问题是来自于洛谷P3371 【模板】单源最短路径(弱化版)
是一道最短路的模板题
我在初始化d数组为无穷大时,用memset,就全wa
用for循环初始化的话就AC了,就算memset速度慢一些,也不至于全wa吧,求lao解答
下面是我的代码:
#include <bits/stdc++.h>
#define inf INT_MAX
using namespace std;
using ll = long long ;
const int N = 1e5 + 50;
int n,m,s;
struct edge {int v,w;};
vector<edge> g[N];
int d[N];
int vis[N];
void dijkstra(int s) {
for (int i = 0;i <= n; i++) d[i] = inf; // 将d初始化为无穷大
//memset(d,inf,sizeof d); // 不要用memset
d[s] = 0;
for (int i = 1;i < n; i++) {
int u = 0;
for (int j = 1;j <= n; j++) {
if (!vis[j] && d[j] < d[u]) u = j;
}
vis[u] = 1;
for (auto ed:g[u]) {
int v = ed.v,w = ed.w;
d[v] = min(d[v],d[u] + w);
}
}
}
int main() {
cin >> n >> m >> s;
for (int i = 1;i <= m; i++) {
int u,v,w; cin >> u >> v >> w;
g[u].push_back({v,w});
}
dijkstra(s);
for (int i = 1;i <= n ;i++) cout << d[i] << " ";
return 0;
}