Pagini recente » Cod sursa (job #1498609) | Cod sursa (job #2676303) | Clasament lsp_11_12 | Cod sursa (job #2220790) | Cod sursa (job #2604933)
//#include <bits/stdc++.h)
#include <iostream>
#include <fstream>
#include <vector>
const int NMAX = 100000, MMAX = 500000;
using namespace std;
ifstream in("ciclueuler.in");
ofstream out("ciclueuler.out");
struct edge {
int node1; //if negative then the edge is visited
int node2;
};
edge ei;
vector<int> sol; //solution
vector<edge> e; //edges
vector<int> g[1 + NMAX]; //graph nodes - vector of adjacent lists
int main()
{
int n, m, n1, n2;
in >> n >> m;
ei.node1 = 0; ei.node1 = 0;
e.push_back(ei); //make the edges vector 1-based, so put something at position ZERO
for (int i = 0; i < m; i++) {
in >> n1 >> n2; //n1 and n2 are the ends of the edge
ei.node1 = n1;
ei.node2 = n2;
e.push_back(ei); //store the edge in edge vector
if (g[n1].empty()) g[n1].push_back(0); //put number of edges at position 0 of adjacent list for src node
if (g[n2].empty()) g[n2].push_back(0); //put number of edges at position 0 of adjacent list for dest node
g[n1].at(0)++; //increase the soure node degree
g[n2].at(0)++; //increase the destination node degree
g[n1].push_back(i + 1); //store the edge number in the adjacent list of source node(1-based index)
g[n2].push_back(i + 1); //store the edge number in the adjacent list of destnation node
}
//check whether g is eulerian graph
for (int i = 0; i < n; i++) {
if (g[i + 1].at(0) & 1) { //odd number of edges, reject it!
out << -1 << endl;
return 0;
}
}
//search the graph for an eulerian cycle
vector<int> stk; //stack
stk.push_back(1);
while (!stk.empty()) {
int nod = stk.back();
if (g[nod].at(0) > 0) { //there are more unprocessed edges adjacent to this node
int next_e = g[nod].at(g[nod].at(0)); //next edge from nod's adjacency list
g[nod].at(0)--; //delete this edge from nod's adjacency list
if (e[next_e].node1 > 0) { //if this edge is unvisited ...
int next_nod = nod == e[next_e].node1 ? e[next_e].node2 : e[next_e].node1; //get the other end of the edge ...
e[next_e].node1 = -1; //... mark the edge as visited
stk.push_back(next_nod); //... and put it on the stack
}
} //no more unvisited edges for this node
else {
sol.push_back(nod); //put the node into the solution cycle
stk.pop_back(); //delete the node from the stack
}
}
//print the solution.The last node is the start node so do not print it
for (int i = 0; i < sol.size() - 1; i++) out << sol[i] << ' ';
in.close(); //close input filestream
out.close(); //close the output stream
}