使用 std::cin 时,我的 C++ 代码出现分段错误
I get segmentation fault in my C++ code while using std::cin
我正在解决一个算法问题(这是一个关于拓扑排序的问题,并且是韩语http://boj.kr/1948)并且在测试示例输入时,我在输入中间出现分段错误
7
9
1 2 4
1 3 2
1 4 3
2 6 3
2 7 5
3 5 1
4 6 4
5 6 2 // here when I input 6, I get segmentation fault
6 7 5
1 7
我发现 cin 导致了这个错误,但我不知道为什么会出错以及如何修复它。
这是我的全部代码:
#include <bits/stdc++.h>
#define FOR(i, n) for (int i = 0; i < (n); i++)
using ll = long long;
using pii = std::pair<int, int>;
using namespace std;
struct Edge {
int end, weight;
Edge(int e, int w): end(e), weight(w) {}
};
struct State {
int node, time, cnt;
bool operator<( State &rhs ) const {
return time < rhs.time;
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int n, m, start, end;
vector< State > last;
vector< Edge > edges[10001];
queue< State > q;
cin >> n >> m;
for (int i = 0; i < n; i++) {
int a, b, c;
cin >> a >> b >> c;
edges[a].push_back(Edge(b, c));
}
cin >> start >> end;
q.push({start, 0, 0});
while (!q.empty()) {
State cur = q.front(); q.pop();
for (Edge e: edges[cur.node])
q.push({e.end, cur.time + e.weight, cur.cnt + 1});
if (cur.node == end)
last.push_back(cur);
}
sort(last.begin(), last.end());
cout << last.back().time << endl << last.back().cnt;
return 0;
}
我认为你应该使用 m
而不是 n
。
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
edges[a].push_back(Edge(b, c));
}
我正在解决一个算法问题(这是一个关于拓扑排序的问题,并且是韩语http://boj.kr/1948)并且在测试示例输入时,我在输入中间出现分段错误
7
9
1 2 4
1 3 2
1 4 3
2 6 3
2 7 5
3 5 1
4 6 4
5 6 2 // here when I input 6, I get segmentation fault
6 7 5
1 7
我发现 cin 导致了这个错误,但我不知道为什么会出错以及如何修复它。 这是我的全部代码:
#include <bits/stdc++.h>
#define FOR(i, n) for (int i = 0; i < (n); i++)
using ll = long long;
using pii = std::pair<int, int>;
using namespace std;
struct Edge {
int end, weight;
Edge(int e, int w): end(e), weight(w) {}
};
struct State {
int node, time, cnt;
bool operator<( State &rhs ) const {
return time < rhs.time;
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int n, m, start, end;
vector< State > last;
vector< Edge > edges[10001];
queue< State > q;
cin >> n >> m;
for (int i = 0; i < n; i++) {
int a, b, c;
cin >> a >> b >> c;
edges[a].push_back(Edge(b, c));
}
cin >> start >> end;
q.push({start, 0, 0});
while (!q.empty()) {
State cur = q.front(); q.pop();
for (Edge e: edges[cur.node])
q.push({e.end, cur.time + e.weight, cur.cnt + 1});
if (cur.node == end)
last.push_back(cur);
}
sort(last.begin(), last.end());
cout << last.back().time << endl << last.back().cnt;
return 0;
}
我认为你应该使用 m
而不是 n
。
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
edges[a].push_back(Edge(b, c));
}