Pagini recente » Cod sursa (job #2178010) | Cod sursa (job #2621074) | Cod sursa (job #1331097) | Cod sursa (job #2554948) | Cod sursa (job #1724020)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
ifstream fin ("ciclueuler.in");
ofstream fout ("ciclueuler.out");
int n, m;
vector<vector<int> > graph;
stack<int> s;
vector<int> eulerList;
bool check_connectivity (int x)
{
vector<bool> visited (n+1, false);
queue<int> q;
q.push(x);
while (!q.empty())
{
int y = q.front(); q.pop();
visited[y] = true;
for (int i = 0; i < graph[y].size(); ++i)
{
if (!visited[graph[y][i]])
{
q.push(graph[y][i]);
}
}
}
for (int i = 1; i <= n; i++)
if (!visited[i])
return false;
return true;
}
void sterge (int v, int w)
{
vector<int>::iterator it;
graph[v].erase(graph[v].begin());
for (it = graph[w].begin(); it != graph[w].end(); it++)
{
if ((*it) == v)
{
graph[w].erase(it);
break;
}
}
}
void euler (int v)
{
while (true)
{
if (graph[v].empty())
break;
int w = graph[v].front();
//cout<<"v: "<<v<<endl;
s.push(v);
sterge (v, w);
v = w;
}
}
void algo(int v)
{
do{
euler(v);
v = s.top();s.pop();
//cout<<"v: "<<v<<endl;
eulerList.push_back(v);
}while (!s.empty());
}
int main()
{
fin >> n >> m;
graph.resize(n+1);
int u, v;
vector<int> degree(n+1, 0);
for (int i = 0; i < m; i++)
{
fin>>u>>v;
graph[u].push_back(v);
graph[v].push_back(u);
degree[u]++;
degree[v]++;
}
for (int i = 1; i <= n; i++)
if (degree[i] % 2 == 1)
{
fout<<"-1";
return 0;
}
if (check_connectivity(1) == false)
{
fout<<"-1";
return 0;
}
algo(1);
//cout<<eulerList.size();
for (int i = 0; i < eulerList.size(); i++)
{
fout<<eulerList[i]<<" ";
}
return 0;
}