Cod sursa(job #1015999)

Utilizator Cosmin1490Balan Radu Cosmin Cosmin1490 Data 25 octombrie 2013 15:55:06
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 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>
#include <iterator>
#include <assert.h>
using namespace std;

const string file = "sortaret";

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

const int INF = 0x3f3f3f3f;

int N, M;
vector<vector<int> > G;

vector<bool> used;
vector<int> sorted;
void topSort(int i)
{
	used[i] = true;
	for(vector<int>::iterator itr = G[i].begin();
		itr != G[i].end();
		itr++)
	{
		if(used[*itr] == false)
		{
			topSort(*itr);
		}
	}
	sorted.push_back(i);

}

int main()
{
	fstream fin(infile.c_str(), ios::in);
	fin >> N >> M;
	G.resize(N + 1);
	used.resize(N + 1);
	sorted.reserve(N);
	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(used[i] == false)
		{
			topSort(i);
		}
	}

	fstream fout(outfile.c_str(), ios::out);
	copy(sorted.rbegin(), sorted.rend(), ostream_iterator<int>(fout, " "));
	fout.close();
}