Cod sursa(job #3261981)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 8 decembrie 2024 01:55:17
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <fstream>
#include <vector>
using namespace std;
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;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long 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;
	}
};

InParser inn("sortaret.in");
ofstream out("sortaret.out");
using pii = pair<int,int>;
const int nmax = 5e4 + 1 , mmax = 1e5 + 1;
int l = 0 , r = -1 , qu[nmax+69];
int start[nmax] , finish[nmax] , n , m , a , b;
pii balls[mmax];
int in[nmax];
signed main()
{
    inn >> n >> m;
    for(int i = 1 ; i <= m ; ++i){
        inn >> a >> b;
        in[b]++;
        balls[i].first = b;
        if(finish[a]) balls[finish[a]].second = i;
        finish[a] = i;
        if(!start[a]) start[a] = i;
    }
    for(int i = 1 ; i <= n ; ++i) if(!in[i]) qu[++r] = i;
    while(l<=r){
        a = qu[l++] , out << a << ' ';
        for(int i = start[a] ; ; i = balls[i].second){
            if(!(--in[balls[i].first])) qu[++r] =  balls[i].first;
            if(balls[i].second == 0) break;
        }
    }
    return 0;
}