Cod sursa(job #3239021)

Utilizator nistor_dora_valentinaNistor Dora Valentina nistor_dora_valentina Data 1 august 2024 14:15:43
Problema Ciclu Eulerian Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");
int n, m, i, x, y, gr[100005], ans[100005], k, it, viz[100005];
vector <pair<int, int>> v[100005];
stack <int> st;
void eulerian_cycle(int nod)
{
    int nodv;
    st.push(nod);
    while(!st.empty())
    {
        nodv=st.top();
        if(v[nodv].size()==0)
        {
            ans[++k]=nodv;
            st.pop();
        }
        else
        {
            while(!v[nodv].empty() && viz[v[nodv].back().second]!=0)
                v[nodv].pop_back();
            if(!v[nodv].empty())
            {
                viz[v[nodv].back().second]=1;
                st.push(v[nodv].back().first);
                v[nodv].pop_back();
            }
        }
    }
}
int main()
{
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y;
        v[x].push_back(make_pair(y, i));
        v[y].push_back(make_pair(x, i));
    }
    for(i=1; i<=n; i++)
    {
        if(v[i].size()%2)
        {
            fout<<-1;
            return 0;
        }
    }
    eulerian_cycle(1);
    for(i=1; i<k; i++)
        fout<<ans[i]<<" ";

    return 0;
}