Cod sursa(job #3266225)

Utilizator Simon2712Simon Slanina Simon2712 Data 6 ianuarie 2025 17:18:06
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <fstream>
#include <vector>

using namespace std;
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");
const int N = 1e5, M = 5e5;
vector<int> mat[N + 1];
int grad[N + 1];
bool viz[N + 1];
struct ura{
    int x, y;
} v[M + 1];
int n, m;
void read()
{
    fin>>n>>m;
    for(int i = 1; i <= m; i++)
    {
        fin>>v[i].x>>v[i].y;
        grad[v[i].x]++;
        grad[v[i].y]++;
        mat[v[i].x].push_back(i);
        mat[v[i].y].push_back(i);
    }
}

void dfs(int nod)
{
    viz[nod] = 1;
    for(auto muchie:mat[nod])
    {
        int nod2 = v[muchie].x + v[muchie].y - nod;
        if(!viz[nod2])
            dfs(nod2);
    }
}

bool is_conex(){
    dfs(1);
    for(int i = 1; i <= n; i++)
        if(!viz[i])
            return 0;
    return 1;
}

bool check(){
    for(int i = 1; i <= n; i++)
    {
        if(grad[i] & 1)
            return 0;
    }
    return is_conex();
}

int stiv[M + 1];
bool viz_muchie[M + 1];
int vsol[M + 5];
int len = 0;
void find_sol(){
    int sz = 1;
    stiv[1] = 1;
    while(sz)
    {
        int nod = stiv[sz];
        if(!mat[nod].empty())
        {
            int muchie = mat[nod].back();
            if(!viz_muchie[muchie])
            {
                viz_muchie[muchie] = true;
                sz++;
                stiv[sz] = v[muchie].x + v[muchie].y - nod;
            }
            mat[nod].pop_back();

        }
        else{
            sz--;
            len++;
            vsol[len] = nod;
        }
    }
    for(int i = 1; i < len; i++)
        fout<<vsol[i]<< ' ';
}
int main()
{
    read();
    int is_euler = check();
    if(is_euler)
        find_sol();
    else
        fout<<-1;
    return 0;
}