Pagini recente » Cod sursa (job #2249962) | Cod sursa (job #1361651) | Cod sursa (job #2145304) | Cod sursa (job #2454408) | Cod sursa (job #2908352)
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
vector <int> degrees;
vector <bool> processed;
///v[4] = [(5, 1), (6, 2)] -> muchie 4, 5 cu indicele 1, etc
vector< vector <pair <int, int> > > adj;
stack <int> path;
void initializeVectors(int numberOfNodes, int numberOfEdges) {
degrees.resize(numberOfNodes + 1, 0);
processed.resize(numberOfEdges + 1, false);
adj.resize(numberOfNodes + 1);
}
bool hasEulerianCycle(int n) {
for(int i = 1; i <= n; ++i) {
if(degrees[i] % 2 != 0) {
return false;
}
//cout << "yes";
}
return true;
}
void eulerian(int startNode) {
for(unsigned int i = 0; i < adj[startNode].size(); ++i) {
//cout << startNode << " " << i << "\n";
int dest = adj[startNode][i].first;
int edgeIndex = adj[startNode][i].second;
if(!processed[edgeIndex]) {
processed[edgeIndex] = true;
eulerian(dest);
}
}
path.push(startNode);
}
int main()
{
ifstream f("ciclueuler.in");
ofstream g("ciclueuler.out");
int numberOfNodes, numberOfEdges;
f >> numberOfNodes >> numberOfEdges;
initializeVectors(numberOfNodes, numberOfEdges);
for(int i = 1; i <= numberOfEdges; ++i){
int src, dest;
f >> src >> dest;
adj[src].push_back(make_pair(dest, i));
adj[dest].push_back(make_pair(src, i));
degrees[src]++;
degrees[dest]++;
}
if(hasEulerianCycle(numberOfNodes)){
eulerian(1);
while(path.size() > 1) {
g << path.top() << " ";
path.pop();
}
} else {
g << -1;
}
f.close();
g.close();
return 0;
}