I was solving an algorithm problem (it's a problem about topology sort, and is in Korean http://boj.kr/1948) and while testing example input, I get segmentation fault in the middle of input
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
I found out cin causes this error, but I have no idea why this makes an error and how to fix it. This is my whole code:
#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;
}