Pagini recente » Cod sursa (job #1226721) | Cod sursa (job #1754515) | Cod sursa (job #1987759) | Cod sursa (job #1865246) | Cod sursa (job #672474)
Cod sursa(job #672474)
// http://infoarena.ro/problema/ciclueuler
#include <fstream>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
const int MAXSIZE = 100001;
ifstream in("ciclueuler.in");
ofstream out("ciclueuler.out");
int nodes,edges;
vector<int> graph[MAXSIZE];
stack<int> stk;
vector<int> solution;
void euler(int startNode);
bool eulerian();
int main() {
in >> nodes >> edges;
int from,to;
for(int i=1;i<=edges;i++) {
in >> from >> to;
graph[from].push_back(to);
graph[to].push_back(from);
}
in.close();
if(!eulerian())
out << "-1\n";
else {
euler(1);
solution.pop_back();
for(vector<int>::iterator it=solution.begin();it!=solution.end();++it)
out << *it << " ";
out << "\n";
}
out.close();
return (0);
}
void euler(int startNode) {
stk.push(startNode); // punem pe stiva nodul de start
while(!stk.empty()) { // cat timp stiva nu este goala
int node = stk.top(); // nodul din varful stivei
while(!graph[node].empty()) { // cat timp nu este izolat
int nextNode = *graph[node].begin(); // selectam un vecin
// stergem muchia dintre nodul curent si vecin (in ambele sensuri)
graph[nextNode].erase(find(graph[nextNode].begin(),graph[nextNode].end(),node));
graph[node].erase(graph[node].begin());
stk.push(nextNode); // putem vecinul pe stiva
node = nextNode; // vecinul devine nodul curent
}
// adaugam la ciclu nodul din varful stivei
solution.push_back(stk.top());
stk.pop(); // eliminat varful stivei
}
}
bool eulerian() { // un multigraf are ciclu eulerian daca gradul fiecarui nod este par
for(int i=1;i<=nodes;i++)
if((graph[i].size() %2))
return false;
return true;
}