Cod sursa(job #2610519)

Utilizator _mirubMiruna-Elena Banu _mirub Data 4 mai 2020 22:58:14
Problema Sortare topologica Scor 100
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 2.64 kb
#include <bits/stdc++.h>
using namespace std;

const int kNmax = 100005;

class Task {
public:
    void solve() {
        read_input();
        print_output(get_result());
    }

private:
    int n;
    int m;
    vector<int> adj[kNmax];

    // Intern degree of the nodes
    vector<int> inDegree;

    void read_input() {
        ifstream fin("sortaret.in");
        fin >> n >> m;
        inDegree = vector<int>(n + 1, 0);
        for (int i = 1; i <= m; i++) {
            int x, y;
            fin >> x >> y;
            adj[x].push_back(y);
            ++inDegree[y]; // edge entering y
        }
        fin.close();
    }

    vector<int> computeBFS() {
        // Declare queue
        queue<int> q;

        // Initialize topsort
        vector<int> topsort;

        // Add to queue every 0 inDegree node
        for (int i = 1; i <= n; ++i) {
            if (inDegree[i] == 0) {
                q.push(i);
            }
        }

        // Do the BFS
        while (!q.empty()) {
            // Remove first node from queue
            int node = q.front();
            q.pop();

            // Add used element to the topsort
            topsort.push_back(node);

            // Parse the neighbours
            for (auto &it : adj[node]) {
                // Decrease the size of inDegree for it
                // to simulate the deletion of the edge
                --inDegree[it];

                // If the node has an inDegree of 0
                // add it to the queue
                if (inDegree[it] == 0) {
                    q.push(it);
                }
            }
        }

        // Verify that the topsort traversal is valid
        // meaning that there are no more edges in the graph
        // as in inDegree[i] == 0, i = 1..n
        bool isValid = true;
        for (int i = 1; i <= n; ++i) {
            if (inDegree[i] > 0) {
                isValid = false;
                break;
            }
        }

        if (isValid) {
            return topsort;
        } else {
            return {};
        }
    }

    vector<int> get_result() {
        vector<int> topsort;

        topsort = computeBFS();

        return topsort;
    }

    void print_output(vector<int> result) {
        ofstream fout("sortaret.out");
        for (int i = 0; i < int(result.size()); i++) {
            fout << result[i] << ' ';
        }
        fout << '\n';
        fout.close();
    }
};

// Please always keep this simple main function!
int main() {
    // Allocate a Task object on heap in order to be able to
    // declare huge static-allocated data structures inside the class.
    Task *task = new Task();
    task->solve();
    delete task;
    return 0;
}