Pagini recente » Cod sursa (job #2448826) | Cod sursa (job #549038) | Cod sursa (job #71771) | Cod sursa (job #1087334) | Cod sursa (job #2425085)
#include <iostream>
#include <vector>
#include <stack>
#include <set>
#include <fstream>
#include <climits>
using namespace std;
int visited[50001];
int main()
{
ifstream fin;
ofstream fout;
fin.open("sortaret.in");
fout.open("sortaret.out");
int nodeCount, edgeCount;
vector<int> edges[50001];
fin >> nodeCount >> edgeCount;
for(int i=1;i<=edgeCount;i++)
{
int node1, node2;
fin >> node1 >> node2;
edges[node1].push_back(node2);
}
stack<int> st;
stack<int> sorted;
for (int i = 1; i <= nodeCount; i++)
{
if(visited[i])continue;
st.push(i);
while (!st.empty())
{
int thisNode = st.top();
int ok = 0;
for (auto nextNode : edges[thisNode])
{
if (!visited[nextNode])
{
visited[nextNode] = 1;
st.push(nextNode);
ok = 1;
}
}
if (ok == 0)
{
sorted.push(thisNode);
st.pop();
}
}
}
while(!sorted.empty())
{
fout << sorted.top()<<" ";
sorted.pop();
}
return 0;
}