Pagini recente » Cod sursa (job #583002) | Cod sursa (job #286357) | Cod sursa (job #983741) | Cod sursa (job #2592686) | Cod sursa (job #2821802)
#include <iostream>
#include <bits/stdc++.h>
#define MAX_N 100001
#define MAX_M 500001
using namespace std;
ifstream f("ciclueuler.in");
ofstream g("ciclueuler.out");
int n, m;
vector<bool> visited(MAX_N);
vector<int> grad(MAX_N);
vector<int> sters(MAX_M);
vector<pair<int,int>> adj[MAX_N]; ///forma x: (y, nr_muchie)
unordered_map<int,int> edge_count; ///nr de muchii dintr un nod
stack<int> stiva;
void DFS(int x)
{
visited[x] = true;
for (auto vecin: adj[x])
if (!visited[vecin.first])
DFS(vecin.first);
}
void euler(int x)
{
while (!adj[x].empty()) ///cat timp am muchii de la x
{
while (!adj[x].empty() && sters[adj[x].back().second]) { ///daca am fost deja pe aceasta muchie o sterg
adj[x].pop_back();
}
if (!adj[x].empty())
{
///retin ultimul vecin al lui x
int urm = adj[x].back().first;
int nrMuchie = adj[x].back().second;
sters[nrMuchie] = 1; ///marchez muchia ca stearsa
adj[x].pop_back(); ///sterg muchia
euler(urm);
}
}
stiva.push(x);
}
int main()
{
int first, second, nr_muchie = 0;
f>>n>>m;
for (int i = 1; i <= m; i++)
{
nr_muchie++;
f>>first>>second;
adj[first].push_back(make_pair(second, nr_muchie));
adj[second].push_back(make_pair(first, nr_muchie));
}
DFS(1);
for (int i = 1; i <= n; i++)
{
edge_count[i] = adj[i].size();
if (edge_count[i] % 2 != 0 || !visited[i]) ///verificam propr de graf eulerian: toate nodurile au grad par si ciclul contine toate nodurile
{
g<<-1;
return 0;
}
}
euler(1);
while (!stiva.empty())
{
if (stiva.size() > 1) /// la final ajung in primul nod, fiind ciclu, deci nu l afisez
g<<stiva.top()<<" ";
stiva.pop();
}
return 0;
}