#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; }帮我解决这段代码segmentation fault的问题
时间: 2024-01-17 21:02:52 浏览: 70
在代码中,有一个数组 dis,它的大小是 n+1,但是在输入 n 的时候,没有考虑到 n 可能为 0 的情况,如果 n 为 0,那么 dis 数组的大小为 1,访问 dis 数组的时候就会出现越界访问,导致 segmentation fault 错误。
解决方法是,在输入 n 的时候,加入一个判断,如果 n 为 0,就直接输出 "No path",并结束程序。修改后的代码如下所示:
```
#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;
if (n == 0) {
cout << "No path" << endl;
return 0;
}
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;
}
```
阅读全文