Pagini recente » Cod sursa (job #2706604) | Cod sursa (job #2546359) | Cod sursa (job #630493) | Cod sursa (job #1476696) | Cod sursa (job #3149818)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");
const int NODES_MAX = 1e5;
vector<int> edge[NODES_MAX];
vector<int> cycle;
bool marked[NODES_MAX];
inline void addEdge(int u, int v){
edge[u].push_back(v);
edge[v].push_back(u);
}
inline bool hasNeighbours(const int& node){
return !edge[node].empty();
}
inline int ChooseANeighbourAndErase(const int& node){
int neighbour = edge[node].back();
edge[node].pop_back();
int i = 0;
while(edge[neighbour][i] != node)
++i;
swap(edge[neighbour][i], edge[neighbour].back());
edge[neighbour].pop_back();
return neighbour;
}
void euler(const int& node){
while(hasNeighbours(node)){
int neighbour = ChooseANeighbourAndErase(node);
euler(neighbour);
}
cycle.push_back(node);
}
int dfs(int node){
int retval = 1;
marked[node] = true;
for(auto neighbour: edge[node])
if(!marked[neighbour])
retval += dfs(neighbour);
return retval;
}
inline bool isConex(int nodes){
return dfs(0) == nodes;
}
int main(){
int nodes, edges, u, v;
fin >> nodes >> edges;
for(int i = 0; i < edges; ++i){
fin >> u >> v;
addEdge(u - 1, v - 1);
}
if(isConex(nodes)){
u = 0;
euler(u);
cycle.pop_back();
for(auto x: cycle)
fout << x + 1 << ' ';
fout.put('\n');
}else
fout << "-1\n";
fin.close();
fout.close();
return 0;
}