Cod sursa(job #3162244)

Utilizator robertapopescuPopescu Roberta Andreea robertapopescu Data 28 octombrie 2023 17:49:36
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;


ifstream fin("sortaret.in");
ofstream fout("sortaret.out");

const int MAXN = 50005;

int N, M;
vector<int> graph[MAXN];
int in_degree[MAXN];

void topologicalSort() {
    queue<int> q;
    vector<int> result;

    for (int i = 1; i <= N; ++i) {
        if (in_degree[i] == 0) {
            q.push(i);
        }
    }

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

        for (int neighbor : graph[node]) {
            in_degree[neighbor]--;
            if (in_degree[neighbor] == 0) {
                q.push(neighbor);
            }
        }
    }

    // Afisarea sortarii topologice
    for (int node : result) {
        cout << node << ' ';
    }
    cout << '\n';
}

int main() {
    ifstream fin("sortaret.in");
    fin >> N >> M;

    for (int i = 0; i < M; ++i) {
        int X, Y;
        fin >> X >> Y;
        graph[X].push_back(Y);
        in_degree[Y]++;
    }
    fin.close();

    topologicalSort();

    return 0;
}