0

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;
}
nngm
  • 129
  • 1
  • 1
  • 8
  • 1
    Please don't use competition sites as teaching or learning resources. All they teach are how to write ***bad*** code that isn't usable anywhere else. The code in your question show-cases *way* to many bad habits. If you try to try to submit code like that on an interview then it would be rejected immediately. – Some programmer dude Oct 05 '20 at 06:15
  • `using ll = long long;` -- There is now something in C++ called `int64_t`. There is no need for crazy aliases like this. Then `vector< Edge > edges[10001];` -- 10001 vectors? It looks like you should be using `std::map Edges`. – PaulMcKenzie Oct 05 '20 at 06:17
  • @Someprogrammerdude that's surprising, then where should I study to write a good code? – nngm Oct 05 '20 at 06:20
  • 1
    [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Evg Oct 05 '20 at 06:32

1 Answers1

1

I think you should be used m instead of n.

for (int i = 0; i < m; i++) {
    int a, b, c;
    cin >> a >> b >> c;
    edges[a].push_back(Edge(b, c));
}