Alex_tz307

Eulerian circuit - DFS with Stack

Nov 5th, 2020 (edited)
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. ifstream fin("ciclueuler.in");
  6. ofstream fout("ciclueuler.out");
  7.  
  8. int main() {
  9.     int N, M;
  10.     fin >> N >> M;
  11.     vector < vector < pair < int , int > > > G(N + 1);
  12.     vector < bool > viz(M);
  13.     for(int i = 0; i < M; ++i) {
  14.         int u, v;
  15.         fin >> u >> v;
  16.         G[u].emplace_back(v, i);
  17.         G[v].emplace_back(u, i);
  18.     }
  19.     for(int i = 1; i <= N; ++i)
  20.         if(G[i].size() & 1) {
  21.             fout << -1;
  22.             return 0;
  23.         }
  24.     vector < int > sol;
  25.     stack < int > S;
  26.     S.emplace(1);
  27.     while(!S.empty()) {
  28.         int node = S.top();
  29.         if(!G[node].empty()) {
  30.             auto next = G[node].back();
  31.             G[node].pop_back();
  32.             if(!viz[next.second]) {
  33.                 viz[next.second] = true;
  34.                 S.emplace(next.first);
  35.             }
  36.         }
  37.         else {
  38.             S.pop();
  39.             sol.emplace_back(node);
  40.         }
  41.     }
  42.     sol.pop_back();
  43.     for(int node : sol)
  44.         fout << node << ' ';
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment