Cod sursa(job #2483608)

Utilizator uvIanisUrsu Ianis Vlad uvIanis Data 29 octombrie 2019 22:35:23
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
#define nmax 100001
#define mmax 500001
using namespace std;

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

int n, m;
vector<vector<pair<int, int>>> graph(nmax, vector<pair<int, int>>());

vector<bool> viz(mmax, false);

stack<int> answer;
stack<int> nodeStack;

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

    for(int i = 1; i <= n; ++i)
    {
        if(graph[i].size() % 2 == 1)
        {
            fout << - 1;
            return 0;
        }
    }

    nodeStack.push(1);

    while(!nodeStack.empty())
    {
        int node = nodeStack.top();

        if(graph[node].size() != 0)
        {
            int toNode = graph[node].back().first;
            int edgeNumber = graph[node].back().second;

            graph[node].pop_back();

            if(viz[edgeNumber] == false)
            {
                viz[edgeNumber] = true;

                nodeStack.push(toNode);
            }
        }
        else {
            nodeStack.pop();
            answer.push(node);
        }
    }

    answer.pop();

    while(!answer.empty())
    {
        fout << answer.top() << " ";
        answer.pop();
    }

}