Pagini recente » Monitorul de evaluare | Cod sursa (job #2912409) | Cod sursa (job #997286) | Cod sursa (job #2228166) | Cod sursa (job #3341601)
#include <fstream>
#include <vector>
#include <stack>
std::ifstream input ("sortaret.in");
std::ofstream output ("sortaret.out");
void dfs(std::vector<std::vector<int>>& graph, std::vector<int>& wasNodeVisited, int startNode){
std::stack<int> nodeStack;
nodeStack.push(startNode);
wasNodeVisited[startNode] = true;
while(!nodeStack.empty()){
int currentNode = nodeStack.top();
nodeStack.pop();
for(auto node : graph[currentNode]){
if(!wasNodeVisited[node]){
nodeStack.push(node);
wasNodeVisited[node] = true;
output << node << ' ';
}
}
}
}
int main () {
int n, m;
input >> n >> m;
std::vector<std::vector<int>> graph(n+1);
for(int i = 1; i <= m; i++){
int a, b;
input >> a >> b;
//a connects to b
graph[a].push_back(b);
}
std::vector<int> wasNodeVisited(n, false);
wasNodeVisited[0] = true;
for(int i = 1; i <= n; i++){
if(!wasNodeVisited[i]){
dfs(graph, wasNodeVisited, i);
}
}
return 0;
}