Cod sursa(job #2767677)

Utilizator SabailaCalinSabaila Calin SabailaCalin Data 7 august 2021 13:18:40
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream f ("ciclueuler.in");
ofstream g ("ciclueuler.out");

const int N = 100001, M = 500001;

int n, m;
int from[M], to[M];
bool visited[M];
vector <int> V[N];
vector <int> path;
stack <int> S;

bool IsCycle()
{
    for (int i = 1; i <= n; i++)
    {
        if (V[i].size() % 2 == 1)
        {
            return false;
        }
    }
    return true;
}

void Read()
{
    f >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        f >> x >> y;
        V[x].push_back(i);
        V[y].push_back(i);
        from[i] = x;
        to[i] = y;
    }
}

void Print()
{
    for (int i = 0; i < path.size()-1; i++)
    {
        g << path[i] << " ";
    }
}

void Euler(int startNode)
{
    S.push(startNode);
    while (S.empty() == false)
    {
        int node = S.top();
        if (V[node].empty() == false)
        {
            int edge = V[node].back();
            V[node].pop_back();
            if (visited[edge] == false)
            {
                visited[edge] = true;
                if (to[edge] != node)
                {
                    S.push(to[edge]);
                }
                else
                {
                    S.push(from[edge]);
                }
            }
        }
        else
        {
            path.push_back(node);
            S.pop();
        }
    }
}

int main()
{
    Read();
    if (IsCycle() == false)
    {
        g << "-1";
        return 0;
    }
    Euler(1);
    Print();
}