Cod sursa(job #2451420)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 26 august 2019 17:40:36
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

const int NMAX = 100000;
const int MMAX = 500000;

int N, M;
vector < pair <int, int> > g[NMAX + 5];
int deg[NMAX + 5];
bool d[MMAX + 5];

vector <int> res;

int main()
{
    fin >> N >> M;

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

    for(int i = 1; i <= N; i++)
        if(deg[i] % 2 == 1)
            {
                fout << -1 << '\n';
                return 0;
            }

    stack <int> s;
    s.push(1);

    while(!s.empty())
    {
        int nod = s.top();

        while(!g[nod].empty() && d[g[nod].back().second])
            g[nod].pop_back();

        if(!g[nod].empty())
        {
            int nxt = g[nod].back().first;
            s.push(nxt);

            d[g[nod].back().second] = 1;
            g[nod].pop_back();
        }
        else
            res.push_back(nod), s.pop();
    }

    for(int i = 1; i < res.size(); i++)
        fout << res[i] << ' ';

    return 0;
}