Pagini recente » Cod sursa (job #2423469) | Monitorul de evaluare | Cod sursa (job #1480343) | Cod sursa (job #2214654) | Cod sursa (job #1691175)
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <fstream>
using namespace std;
ifstream f("sortaret.in");
ofstream g("sortaret.out");
int n,m,i,j;
vector <vector <int> > graph(100000);
vector <bool> visited (100000,false);
queue<int> q;
void dfs(int vertex)
{ if(vertex<0||vertex>n-1)
return;
stack <int> s;
int element,i;
bool found;
s.push(vertex);
q.push(vertex+1);
visited[vertex]=true;
while(!s.empty())
{ element=s.top();
found=false;
for(i=0;i<graph[element].size()&&(!found);i++)
if(!visited[graph[element][i]])
found=true;
if(found)
{ i--;
s.push(graph[element][i]);
q.push(s.top()+1);
visited[graph[element][i]]=true;
}
else s.pop();
}
}
int main()
{ int x,y;
f>>n>>m;
for(i=0;i<m;i++)
{ f>>x>>y;
x--; y--;
graph[x].push_back(y);
}
for(i=0;i<n;i++)
if(!visited[i])
dfs(i);
while(!q.empty())
{ g<<q.front()<<" ";
q.pop();
}
return 0;
}