Pagini recente » Cod sursa (job #3294277) | Cod sursa (job #213477) | Cod sursa (job #170674) | Cod sursa (job #3286613) | Cod sursa (job #758023)
Cod sursa(job #758023)
#include <stack>
#include <queue>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <iterator>
#include <algorithm>
using namespace std;
const int N_MAX=100011;
stack<int> S;
vector<int> G[N_MAX], r;
vector<int>::const_iterator it, iend;
bool canHaveE(int N)
{
int i, count;
queue<int> Q;
bool was[N_MAX]={false};
for(i=1; i <= N; ++i)
if(G[i].size()&1)
return false;
was[1]=true;
for(Q.push(1), count=N-1; !Q.empty(); Q.pop())
{
i=Q.front();
for(it=G[i].begin(), iend=G[i].end(); it < iend; ++it)
if(false == was[*it])
{
--count;
if(0 == count)
return true;
was[*it]=true;
Q.push(*it);
}
}
return false;
}
void Euler(int x)
{
int y;
while(!G[x].empty())
{
y=G[x].back();
G[x].pop_back();
G[y].erase(find(G[y].begin(), G[y].end(), x));
x=y;
S.push(y);
}
}
int main()
{
int N, M, x, y;
ifstream in("ciclueuler.in");
ofstream out("ciclueuler.out");
for(in>>N>>M; M; --M)
{
in>>x>>y;
G[x].push_back(y);
G[y].push_back(x);
}
if(!canHaveE(N))
{
out<<"-1\n";
return EXIT_SUCCESS;
}
x=1;
do {
Euler(x);
r.push_back(S.top()); S.pop();
}while(!S.empty());
copy(r.begin(), r.end(), ostream_iterator<int>(out, " "));
out<<'\n';
return EXIT_SUCCESS;
}