Cod sursa(job #2711916)

Utilizator MagnvsDaniel Constantin Anghel Magnvs Data 24 februarie 2021 21:17:41
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <fstream>
#include <string>
#include <vector>
#include <stack>

using namespace std;

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

string::iterator fi;

void read_uint( int &x ) {
    while ( *fi < '0' || *fi > '9' ) {
        ++ fi;
    }
    x = 0;
    while ( *fi >= '0' && *fi <= '9' ) {
        x = x*10+(*fi-'0');
        ++ fi;
    }
}

const int nmax = 100000;
const int mmax = 500000;

vector <int> g[nmax+1];
bool u[nmax+1];

void dfs( int x ) {
    u[x] = 1;
    for ( int i = 0; i < int(g[x].size()); ++i ) {
        int xn = g[x][i];
        if ( u[xn] == 0 ) {
            dfs(xn);
        }
    }
}

stack <int> s;

int main( ) {
    string fs;
    getline(fin, fs, char(0));
    fi = fs.begin();

    int n, m;
    read_uint(n);
    read_uint(m);
    fin >> n >> m;
    for ( int i = 1; i <= m; ++ i ) {
        int x, y;
        read_uint(x);
        read_uint(y);
        g[x].push_back(y);
        g[y].push_back(x);
    }

    int ok = 1;
    dfs(1);
    for ( int i = 1; i <= n; ++ i ) {
        if ( g[i].size()%2 == 1 || u[i] == 0 ) {
            ok = 0;
        }
    }

    if ( ok == 1 ) {
        s.push(1);
        for ( int i = 1; i <= m; ++ i ) {
            int x = s.top();
            while ( g[x].size() > 0 ) {
                int y = g[x].back();
                g[x].pop_back();
                int j = 0;
                while ( g[y][j] != x ) {
                    ++ j;
                }
                g[y][j] = g[y].back();
                g[y].pop_back();
                x = y;
                s.push(x);
            }
            fout << x << " ";
            s.pop();
        }
    } else {
        fout << "-1\n";
    }

    return 0;
}