Cod sursa(job #3333756)

Utilizator ThatScode24Mihai Focsa ThatScode24 Data 15 ianuarie 2026 02:23:31
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>
#include <vector>
#include <queue>

std::ifstream fin("topsort.in");
std::ofstream fout("topsort.out");

class Graph{
private:
    int V;
    std::vector<std::vector<int>>adj;
    std::vector<int>in_degree;
public:
    Graph(int v) {
        V = v;
        adj.resize(V+1);
    }

    void addEdges(int x, int y) {
        adj[x].push_back(y);
        in_degree[y]++;
    }

    void kahn() {
        
        std::priority_queue<int>pq;

        for(int i=1;i<=V;++i) {
            if(!in_degree[i]) {
                pq.push(i);
            }
        }

        while(!pq.empty()) {
            int c = pq.top();
            fout << c << " ";
            pq.pop();

            for(auto& vecin : adj[c]) {
                in_degree[vecin]--;
                if(!in_degree[vecin]) {
                    pq.push(vecin);
                }
            }
        }
    }

};



int main(void) {
    int m, n;
    fin >> n>> m;
    Graph g(n);
    int x1, x2;

    for(int i=0;i<m;++i) {
        fin >> x1 >> x2;
        g.addEdges(x1, x2);
    }

    g.kahn();
    
    return 0;
}