Cod sursa(job #2431856)

Utilizator rd211Dinucu David rd211 Data 20 iunie 2019 22:50:29
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
int n,m;
ofstream fout("sortaret.out");
vector<int> graf[50005];
bool viz[50005];
void addMuchie(int x,int y)
{
    graf[x].push_back(y);
}

stack<int> stac;
void dfs(int x)
{
    viz[x]=true;
    for(int i = 0; i<graf[x].size(); i++){
        if(!viz[graf[x][i]]){
            dfs(graf[x][i]);
        }
    }
    stac.push(x);
}
void sortTop()
{
    for(int i = 1; i<=n; i++)
    {
        if(!viz[i])
        {
            dfs(i);
        }
    }
    while(stac.size())
    {
        fout<<stac.top()<<' ';
        stac.pop();
    }
}
class InParser
{

private:
    FILE *fin;
    char *buff;
    int sp;
    char read_ch()
    {
        ++sp;
        if (sp == 4096)
        {
            sp = 0;
            fread(buff, 1, 4096, fin);
        }
        return buff[sp];
    }
public:
    InParser(const char* nume)
    {
        fin = fopen(nume, "r");
        buff = new char[4096]();
        sp = 4095;
    }
    InParser& operator >> (int &n)
    {
        char c;
        while (!isdigit(c = read_ch()) && c != '-');
        int sgn = 1;
        if (c == '-')
        {
            n = 0;
            sgn = -1;
        }
        else
        {
            n = c - '0';
        }
        while (isdigit(c = read_ch()))
        {
            n = 10 * n + c - '0';
        }
        n *= sgn;
        return *this;
    }
};
int main()
{
    InParser fin("sortaret.in");
    int x,y;
    fin>>n>>m;
    while(m--)
    {
        fin>>x>>y;
        addMuchie(x,y);
    }
    sortTop();
    return 0;
}