Pagini recente » Cod sursa (job #3213628) | Cod sursa (job #137261) | Cod sursa (job #1293761) | Cod sursa (job #1543706) | Cod sursa (job #1922894)
#include <fstream>
#include <vector>
#include <list>
#include <stack>
using namespace std ;
ifstream f ("ciclueuler.in") ;
ofstream g ("ciclueuler.out") ;
int N, M;
vector <int> Viz, Deg;
list <int> G[100005], L;
stack <int> S;
void dfs(int nod)
{
Viz[nod] = 1 ;
for (const int & x : G[nod])
if (Viz[x] == 0)
dfs (x) ;
}
int conex ()
{
dfs ( 1 ) ;
for (int cnt = 1; cnt <= N; ++cnt)
if (Viz[cnt] == 0)
return 0 ;
return 1;
}
int euler ()
{
if ( conex () == 0 )
return 0;
for (int cnt = 1; cnt <= N; ++cnt)
if (Deg[cnt] % 2 == 1)
return 0;
return 1;
}
void sterge(int v, int w)
{
--Deg[v], --Deg[w];
G[v].pop_front();
for (list <int> :: iterator it = G[w].begin(); it != G[w].end(); ++it)
if(*it == v)
{
G[w].erase(it);
break ;
}
}
void euler(int v)
{
while(true)
{
if(G[v].empty())
break ;
int w = G[v].front();
S.push(v);
sterge(v, w);
v = w;
}
}
void cauta_ciclu_eulerian()
{
int nod = 1;
L.push_back(nod);
do {
euler(nod) ;
nod = S.top() ;
S.pop();
L.push_back(nod);
}while (!S.empty());
L.pop_back();
for (const int & x : L)
g << x << " ";
}
int main ()
{
f >> N >> M;
Viz = vector <int> (N + 1);
Deg = vector <int> (N + 1);
for ( int cnt = 1 ; cnt <= M ; ++cnt )
{
int x , y ;
f >> x >> y ;
G[x].push_back (y);
G[y].push_back (x);
++Deg[x], ++Deg[y];
}
if (euler() == 0)
g << "-1";
else
cauta_ciclu_eulerian ();
f.close();
g.close();
return 0;
}