Cod sursa(job #3233212)

Utilizator MirceaDonciuLicentaLicenta Mircea Donciu MirceaDonciuLicenta Data 2 iunie 2024 19:51:51
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

void topological_sort(int N, const vector<vector<int>>& adj, vector<int>& indegree, vector<int>& result) {
    queue<int> q;
    for (int i = 1; i <= N; ++i) {
        if (indegree[i] == 0) {
            q.push(i);
        }
    }

    while (!q.empty()) {
        int u = q.front();
        q.pop();
        result.push_back(u);

        for (int v : adj[u]) {
            indegree[v]--;
            if (indegree[v] == 0) {
                q.push(v);
            }
        }
    }
}

int main() {
    ifstream infile("sortaret.in");
    ofstream outfile("sortaret.out");

    if (!infile || !outfile) {
        cerr << "Error opening file" << endl;
        return 1;
    }

    int N, M;
    infile >> N >> M;

    vector<vector<int>> adj(N + 1);
    vector<int> indegree(N + 1, 0);

    for (int i = 0; i < M; ++i) {
        int x, y;
        infile >> x >> y;
        adj[x].push_back(y);
        indegree[y]++;
    }

    vector<int> result;
    topological_sort(N, adj, indegree, result);

    for (int i = 0; i < result.size(); ++i) {
        outfile << result[i] << " ";
    }
    outfile << endl;

    infile.close();
    outfile.close();

    return 0;
}