Cod sursa(job #2790711)

Utilizator DananauStefanRazvanDananau Stefan-Razvan DananauStefanRazvan Data 29 octombrie 2021 13:20:23
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.85 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

class Graph {
    private:
        int n;
        int m;
        int start;
        vector<vector<int>> adjList;
        vector<int> dist;
        queue<int> q;
        bool vis[100001] = {false};
        vector<int> topSorted;
    public:
        Graph() {};
        void directedGraph();
        void undirectedGraph();
        void directedGraphTopSort();
        void bfs();
        void dfs(int start);
        void noConnComp();
        void dfsTopSort(int start);
        void topSort();
};

void Graph :: directedGraph() {
    ifstream fin("bfs.in");

    fin >> n >> m >> start;

    adjList.resize(n + 1);

    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        adjList[x].push_back(y);
    }

    fin.close();
}

void Graph :: undirectedGraph() {
    ifstream fin("dfs.in");

    fin >> n >> m;

    adjList.resize(n + 1);

    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        adjList[x].push_back(y);
        adjList[y].push_back(x);
    }

    fin.close();
}

void Graph :: directedGraphTopSort() {
    ifstream fin("sortaret.in");

    fin >> n >> m;

    adjList.resize(n + 1);
    topSorted.resize(n - 8);

    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        adjList[x].push_back(y);
    }

    fin.close();
}

void Graph :: bfs() {
    ofstream fout("bfs.out");

    q.push(start);

    dist.resize(n + 1);
    for (int i = 1; i <= n; i++)
        dist[i] = -1;
    dist[start] = 0;

    while (!q.empty()) {
        int nod = q.front();
        q.pop();
        for (auto i : adjList[nod])
            if (dist[i] == -1) {
                dist[i] = dist[nod] + 1;
                q.push(i);
            }
    }

    for (int i = 1; i <= n; i++)
        fout << dist[i] << " ";

    fout.close();
}

void Graph :: dfs(int start) {
    vis[start] = true;

    for (auto x : adjList[start])
        if (!vis[x])
            dfs(x);
}

void Graph :: noConnComp() {
    ofstream fout("dfs.out");

    int c = 0;

    for (int i = 1; i <= n; i++)
        if (!vis[i]) {
            dfs(i);
            c++;
        }

    fout << c;

    fout.close();
}

void Graph :: dfsTopSort(int start) {
    vis[start] = true;

    for (auto x : adjList[start])
        if (!vis[x])
            dfsTopSort(x);

    topSorted.push_back(start);
}

void Graph :: topSort() {
    ofstream fout("sortaret.out");

    for (int i = 1; i <= n; i++)
        if (!vis[i])
            dfsTopSort(i);

    for (int i = n; i >= 1; i--)
        fout << topSorted[i] << " ";

    fout.close();
}

int main()
{
    Graph X;
    X.directedGraphTopSort();
    X.topSort();
    return 0;
}