Pagini recente » Cod sursa (job #1281311) | Cod sursa (job #1727652) | Cod sursa (job #296522) | Cod sursa (job #441237) | Cod sursa (job #1161962)
// Ciclu eulerian - O(N+M) - ITERATIV
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>
#define Nmax 100009
#define pb push_back
using namespace std;
ifstream f("ciclueuler.in");
ofstream g("ciclueuler.out");
int N,M,x,y;
vector < int > G[Nmax],Cycle;
stack < int > st;
inline int IsEulerian()
{
for(int i=1;i<=N;++i)
if(G[i].size()&1)return 0;
return 1;
}
inline void GetCycle(int S)
{
for( st.push(S); !st.empty(); )
{
int node=st.top();
if(G[node].size())
{
int last=G[node].back();
st.push(last);
G[node].pop_back();
G[last].erase(find(G[last].begin(),G[last].end(),node));
}
else
{
st.pop();
Cycle.pb(node);
}
}
}
int main()
{
f>>N>>M;
for(int i=1;i<=M;++i)
f>>x>>y , G[x].pb(y), G[y].pb(x);
if(IsEulerian())
{
GetCycle(1);
for(vector< int > ::iterator it=Cycle.begin();it!=Cycle.end();++it)
g<<*it<<' ';
g<<'\n';
}
else g<<-1<<'\n';
f.close();g.close();
return 0;
}