Pagini recente » Cod sursa (job #2463391) | Cod sursa (job #2102221) | Cod sursa (job #1393745) | Cod sursa (job #1454398) | Cod sursa (job #2228239)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
struct Node
{
int val;
Node* next;
Node( int val)
{
this->val = val;
next = nullptr;
}
};
static vector<Node*> v;
static vector<int> answ;
static vector<bool> vis;
static ifstream in("sortaret.in");
static ofstream out("sortaret.out");
static bool test = false;
static void dfs(int start)
{
vis[start] = true;
if (test)
out << start << " ";
if (v[start] == nullptr)
{
answ.push_back(start);
return;
}
stack<int> s;
s.push(start);
while (!s.empty())
{
int crt = s.top();
Node* node;
for (node = v[crt]; node != nullptr; node = node->next)
if (!vis[node->val])
{
if (test)
out << node->val << " ";
s.push(node->val);
vis[node->val] = true;
break;
}
if (node == nullptr)
{
s.pop();
answ.push_back(crt);
}
}
}
int main()
{
int n, m;
in >> n >> m;
v.resize(n + 1, nullptr);
vis.resize(n + 1, false);
answ.reserve(n);
for (int i = 0; i < m; ++i)
{
int u, w;
in >> u >> w;
if (u > w)
{
int aux = w;
w = u;
w = aux;
}
Node* node = new Node(w);
node->next = v[u];
v[u] = node;
// node = new Node(u);
// node->next = v[w];
// v[w] = node;
}
int comp = 0;
for (int i = 1; i <= n; ++i)
{
if (vis[i])
continue;
comp++;
dfs(i);
if (test)
out << "\n----------------\n";
}
for ( int i = answ.size() - 1; i >= 0; --i )
{
out << answ[i] << " ";
}
out << "\n";
return 0;
}