Pagini recente » Cod sursa (job #1003415) | Cod sursa (job #1063324) | Cod sursa (job #244752) | Rating Andrei Tanase (silverbabyyyy) | Cod sursa (job #2579498)
#include<fstream>
#include<vector>
#include<stack>
#include<algorithm>
#define NMAX 100005
//in-out
std::ifstream f("ciclueuler.in");
std::ofstream g("ciclueuler.out");
//data
std::stack<int> cycleStack;
std::vector<int> G[NMAX];
std::vector<int> cycle;
int n, m;
//read-data
void readData(){
f >> n >> m;
int x, y;
for(int i = 0; i<m; i++){
f >> x >> y;
G[x].push_back(y);
G[y].push_back(x);
}
}
//check if a graph has an euler cycle or path
bool isEuler(){
for(int i = 1; i<=n; i++){
if(G[i].size() % 2 != 0){
return false;
}
}
return true;
}
//construct cycle
void constructCycle(){
cycleStack.push(1);
while(!cycleStack.empty()){
int node = cycleStack.top();
if(G[node].size()){
int newNode = G[node].back();
G[node].pop_back();
cycleStack.push(newNode);
G[newNode].erase(std::find(G[newNode].begin(), G[newNode].end(), node));
}else{
cycle.push_back(node);
cycleStack.pop();
}
}
}
int main(){
readData();
if(!isEuler()){
g << -1;
return 0;
}
constructCycle();
cycle.pop_back();
for(const auto& elem : cycle){
g << elem << ' ';
}
return 0;
}