Cod sursa(job #3267918)

Utilizator MegaCoderMinoiu Teodor Mihai MegaCoder Data 12 ianuarie 2025 21:26:34
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include<fstream>
#include<vector>
#include<stack>
#include<bitset>
std::ifstream fin("ciclueuler.in");
std::ofstream fout("ciclueuler.out");
const int NMAX=100005, MMAX=500005;
std::vector<int>G[NMAX];
std::vector<int>degree(NMAX);
std::bitset<MMAX>used_edge;
std::vector<int>from(MMAX), to(MMAX);
int n, m;
void read()
{
    fin>>n>>m;
    for(int i=0; i<m; ++i)
    {
        int a, b;
        fin>>a>>b;
        G[a].push_back(i);
        G[b].push_back(i);
        ++degree[a];
        ++degree[b];
        from[i]=a;
        to[i]=b;
    }

}
bool eulerian()
{
    for(int i=1; i<=n; ++i)
        if(degree[i]%2)
            return false;
    return true;
}
void get_cycle()
{
    std::stack<int>curr_path;
    std::vector<int>sol;
    curr_path.push(1);
    while(!curr_path.empty())
    {
        int v=curr_path.top();
        if(!G[v].empty())
        {
            int e=G[v].back();
            G[v].pop_back();
            if(!used_edge[e])
            {
                used_edge[e]=true;
                int other_endpoint=to[e]^from[e]^v;
                curr_path.push(other_endpoint);
            }
        }
        else
        {
            sol.push_back(v);
            curr_path.pop();
        }
    }
    for(int i=0; i<sol.size()-1; ++i)
        fout<<sol[i]<<' ';
}
int main()
{
    read();
    if(eulerian())
        get_cycle();
    else
        fout<<"-1";
    return 0;
}