Cod sursa(job #3308909)

Utilizator alesiodemiriAlesio Demiri alesiodemiri Data 29 august 2025 22:40:12
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <string>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <iomanip>

using namespace std;

#define ll long long

int n, e;
vector<int> degree;
vector<vector<int>> graph;

void ReadData() {
    cin >> n >> e;
    graph.assign(n, vector<int>());
    degree.assign(n, 0);
    int a, b = 0;
    for(int i = 0; i < e; i++){
        cin >> a >> b;
        a--; b--;
        graph[a].push_back(b);
        degree[b]++;
    }
        
}

void Solve() {
    queue<int> starting;

    for (int i = 0; i < n; i++){
        if (degree[i] == 0){
            starting.push(i);
        }
    }

    while (!starting.empty()){
        int val = starting.front();
        starting.pop();
        cout << val + 1 << " ";
        for (int neighbour: graph[val]){
            degree[neighbour]--;
            if (degree[neighbour] == 0){
                starting.push(neighbour);
            }  
        } 
    }

    cout << "\n";
    return;  
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    freopen("sortaret.in", "r", stdin);
    freopen("sortaret.out", "w", stdout);

    int t = 1;
    // cin >> t; // Uncomment for multiple test cases
    while (t--) {
        ReadData();
        Solve();   
    }
    return 0;
}