Cod sursa(job #2926967)

Utilizator AswVwsACamburu Luca AswVwsA Data 18 octombrie 2022 23:58:17
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
//solutie cu 2 stive
#include <fstream>
#include <vector>
#include <set>
#include <stack>
using namespace std;
const int NMAX = 100001;

multiset <int> g[NMAX];
vector <int> sol;
stack <int> stiva;
int grad[NMAX];

int cnt;
bool viz[NMAX];
void dfs(int nod)
{
    viz[nod] = 1;
    cnt++;
    for (int x : g[nod])
        if (!viz[x])
            dfs(x);
}


int main()
{
    ifstream cin("ciclueuler.in");
    ofstream cout("ciclueuler.out");
    ios_base :: sync_with_stdio(0);
    cin.tie(0);
    int n, m, i;
    cin >> n >> m;
    while (m--)
    {
        int a, b;
        cin >> a >> b;
        g[a].insert(b);
        g[b].insert(a);
        grad[a]++;
        grad[b]++;
    }
    //dfs(1);
    bool ok = 0;
    cnt = n;
    for (i = 1; i <= n; i++)
        if (grad[i] & 1)
        {
            ok = 1;
            break;
        }
    if (cnt != n or ok)
    {
        cout << -1;
        return 0;
    }
    stiva.push(1);
    while (!stiva.empty())
    {
        int f = stiva.top();
        if (!g[f].empty())
        {
            int x = *g[f].begin();
            g[f].erase(g[f].begin());
            g[x].erase(g[x].find(f));
            stiva.push(x);
        }
        else
        {
            stiva.pop();
            sol.push_back(f);
        }
    }
    for (i = sol.size() - 1; i > 0; i--)
        cout << sol[i] << ' ';
}