Cod sursa(job #3207382)

Utilizator KarinaDKarina Dumitrescu KarinaD Data 26 februarie 2024 02:00:52
Problema Ciclu Eulerian Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream fin ( "ciclueuler.in" );
ofstream fout ( "ciclueuler.out" );

const int N = 1e5;

struct edge {
    int x, y, viz = 0;
} v[5 * N + 10];

vector <int> g[N + 10];
vector <int> path;

int euler () {
    
    stack <int> st;
    st.push (1);
    
    while ( !st.empty() ) {
        
        int node = st.top();
        int ok = 0;
        
        while ( g[node].size() != 0 ) {
            
            int i = g[node].back();
            
            g[node].pop_back();
            
            if ( v[i].viz == 0 ) {
                
                v[i].viz = 1;
                ok = 1;

                int x = v[i].x;
                int y = v[i].y;
                
                if ( x != node )
                    st.push(x);
                else 
                    st.push(y);
                
                break;
            }
        }
        
        if ( ok == 0 ) {
            path.push_back (node);
            st.pop();
        }
    }
    
    return 0;
}

int main () {
    
    int n, m, x, y;
    
    fin >> n >> m;
    
    for ( int i = 0; i < m; i++ ) {
        
        fin >> x >> y;
        
        v[i].x = x;
        v[i].y = y;
        
        g[x].push_back (i);
        g[y].push_back (i);
    }
    
    int ok = 0;
    for ( int i = 1; i <= n; i++ )
        if ( g[i].size() % 2 == 0 )
            ok = 1;
    
    if ( ok == 1 )
        fout << "-1";
    
    else {
        euler ();
        
        if( path.size() != m + 1 )
            fout << "-1";
        
        else
            for ( int i = 0; i < path.size() - 1; i++ )
                fout << path[i] << " ";
    }
    
    return 0;
}