Pagini recente » Cod sursa (job #2432926) | Cod sursa (job #1529241) | Cod sursa (job #3000652) | Cod sursa (job #1918072) | Cod sursa (job #3149819)
#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;
}
inline bool isEulerian(int nodes){
int odds = 0;
for(int node = 0; node < nodes; ++node)
odds += edge[node].size() & 1;
return !odds && isConex(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(isEulerian(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;
}