Cod sursa(job #997717)

Utilizator Cosmin1490Balan Radu Cosmin Cosmin1490 Data 14 septembrie 2013 19:40:10
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
using namespace std;

const string file = "sortaret";

const string infile = file + ".in";
const string outfile = file + ".out";

const int INF = 0x3f3f3f3f;


vector<vector<int> > G;
int N, M;
vector<int> sorted;
vector<bool> uz;
void TopSort(int x)
{
	uz[x] = true;
	for(vector<int>::iterator itr = G[x].begin();
		itr != G[x].end();
		itr++)
	{
		if(uz[*itr] == false)
		{
			TopSort(*itr);
		}
	}
	sorted.push_back(x);
}

int main()
{
	fstream fin(infile.c_str(), ios::in);
	fin >> N;
	fin >> M;
	sorted.reserve(N);
	uz.resize(N + 1);
	G.resize(N + 1);
	for(int i = 0; i < M; i++)
	{
		int x, y;
		fin >> x >> y;
		G[x].push_back(y);
	}
	fin.close();

	for(int i = 1; i <= N; i++)
	{
		if(uz[i] == false)
		{
			TopSort(i);
		}
	}

	fstream fout(outfile.c_str(), ios::out);

	for(vector<int>::reverse_iterator itr = sorted.rbegin();
		itr != sorted.rend();
		itr++)
	{
		fout << *itr << " ";
	}
	fout << "\n";

	fout.close();
}