#include #include #include #include #include #include #include using namespace std; int outList[2000000]; // max number of output ints int l; // undirected acyclic graph class Graph { int V; list *adjList; public: Graph(int V) { this->V = V; adjList = new list[V]; } ~Graph() { delete [] adjList; } void addEdge(int u, int v); void removeEdge(int u, int v); int reachableVertexes(int v, bool visited[]); bool checkNextEdge(int u, int v); void eulerTour(int s); }; // adding edges to adjList of nodes u and v void Graph::addEdge(int u, int v) { adjList[u].push_back(v); adjList[v].push_back(u); } // removing edge from list void Graph::removeEdge(int u, int v) { list::iterator iv = find(adjList[u].begin(), adjList[u].end(), v); *iv = -1; list::iterator iu = find(adjList[v].begin(), adjList[v].end(), u); *iu = -1; } // finding all vertexes that u can reach using a DFS exploration of the list int Graph::reachableVertexes(int u, bool visited[]) { visited[u] = true; int count = 1; list::iterator it; for (it = adjList[u].begin(); it != adjList[u].end(); ++it) if (*it != -1 && !visited[*it]) count += reachableVertexes(*it, visited); return count; } // checking if edge u-v is a proper one for the tour bool Graph::checkNextEdge(int u, int v) { int count = 0; bool visited[V]; list::iterator it; for (it = adjList[u].begin(); it != adjList[u].end(); ++it) if (*it != -1) count++; // u-v is the only edge available if (count == 1) return true; memset(visited, false, V); int count1 = reachableVertexes(u, visited); removeEdge(u, v); memset(visited, false, V); int count2 = reachableVertexes(u, visited); addEdge(u, v); // if the number of reachable vertexes is reduced after deleting u-v, this is not a proper vertex return (count1 > count2)? false: true; } // recursive function to compute euler's tour void Graph::eulerTour(int u) { list::iterator it; for (it = adjList[u].begin(); it != adjList[u].end(); ++it) { int v = *it; if (v != -1 && checkNextEdge(u, v)) { outList[l++] = v; outList[l++] = u; removeEdge(u, v); eulerTour(v); } } } int main(int argc, char**argv) { ifstream inFile("input.txt"); assert(inFile); ofstream outFile("output.txt"); assert(outFile); int nodes, edges, start, end; int u, v; inFile >> nodes >> edges >> start >> end; Graph G(edges); for(int i = 0; i < edges; ++i) { inFile >> u >> v; G.addEdge(u, v); } inFile.close(); G.eulerTour(start); int i = 0; while(outList[i] != 0) { outFile << outList[i++] << " " << outList[i++] << endl; } outFile.close(); return 0; }