#include <iostream> #include <cstring> using namespace std; const int MAXN = 1000000; const int INF = 0x3f3f3f3f; struct Edge { int to; int w; int next; } edges[MAXN]; int head[MAXN]; int cnt = 0; int n, m; int dis[MAXN]; bool vis[MAXN]; void addEdge(int u, int v, int w) { edges[cnt].to = v; edges[cnt].w = w; edges[cnt].next = head[u]; head[u] = cnt++; } void dijkstra(int start, int end) { memset(vis, 0, sizeof(vis)); for (int i = 1; i <= n; ++i) { dis[i] = INF; } dis[start] = 0; while (!vis[end]) { int min_dis = INF, min_pos = -1; for (int j = 1; j <= n; ++j) { if (!vis[j] && dis[j] < min_dis) { min_dis = dis[j]; min_pos = j; } } if (min_pos == -1) return; vis[min_pos] = true; for (int k = head[min_pos]; k != -1; k = edges[k].next) { int j = edges[k].to; if (!vis[j] && dis[j] > dis[min_pos] + edges[k].w) { dis[j] = dis[min_pos] + edges[k].w; } } } } int main() { int start, end ; memset(head, -1, sizeof(head)); cin >> n >> m>> start >> end; for (int i = 1; i <= m; ++i) { int u, v, w; cin >> u >> v >> w; addEdge(u, v, w); addEdge(v, u, w); } dijkstra(start, end); cout << dis[end] << endl; return 0; }帮我解决这段代码segmentation fault的问题
时间: 2023-07-31 09:03:52 浏览: 94
这段代码在使用 `memset` 函数时有一个问题:memset 函数的第二个参数应该是要初始化的字节数,而不是要初始化的元素个数。因此,在初始化 `vis` 数组时,应该传入 `sizeof(bool) * (n+1)`,而不是 `sizeof(vis)`。同样地,在初始化 `dis` 数组时,应该传入 `sizeof(int) * (n+1)`。
此外,在使用 `head` 数组时也可能出现问题。如果输入的图中有孤立节点,即没有与其他节点相连的节点,那么 `head` 数组中对应的位置就没有被赋值,此时访问该位置会出现未定义的行为。在使用 `head` 数组时,应该先初始化为 -1。
以下是修改后的代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 1000000;
const int INF = 0x3f3f3f3f;
struct Edge {
int to;
int w;
int next;
} edges[MAXN];
int head[MAXN];
int cnt = 0;
int n, m;
int dis[MAXN];
bool vis[MAXN];
void addEdge(int u, int v, int w) {
edges[cnt].to = v;
edges[cnt].w = w;
edges[cnt].next = head[u];
head[u] = cnt++;
}
void dijkstra(int start, int end) {
memset(vis, false, sizeof(bool) * (n+1));
memset(dis, INF, sizeof(int) * (n+1));
dis[start] = 0;
while (!vis[end]) {
int min_dis = INF, min_pos = -1;
for (int j = 1; j <= n; ++j) {
if (!vis[j] && dis[j] < min_dis) {
min_dis = dis[j];
min_pos = j;
}
}
if (min_pos == -1) return;
vis[min_pos] = true;
for (int k = head[min_pos]; k != -1; k = edges[k].next) {
int j = edges[k].to;
if (!vis[j] && dis[j] > dis[min_pos] + edges[k].w) {
dis[j] = dis[min_pos] + edges[k].w;
}
}
}
}
int main() {
int start, end;
memset(head, -1, sizeof(head));
cin >> n >> m >> start >> end;
for (int i = 1; i <= m; ++i) {
int u, v, w;
cin >> u >> v >> w;
addEdge(u, v, w);
addEdge(v, u, w);
}
dijkstra(start, end);
if (dis[end] == INF) {
cout << "No path" << endl;
} else {
cout << dis[end] << endl;
}
return 0;
}
```
阅读全文