Cod sursa(job #2346315)

Utilizator petru.ciocirlanPetru Ciocirlan petru.ciocirlan Data 17 februarie 2019 15:37:35
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>
using namespace std;

#define FILE_NAME "ciclueuler"
ifstream fin (FILE_NAME".in");
ofstream fout(FILE_NAME".out");

const int MAXN = 100000 + 16;
const int MAXM = 500000 + 16;
vector < pair < int, int > > Edge[MAXN];
bitset < MAXM > VizEdge;
int N, M;

int main()
{
    fin >> N >> M;
    for(int i = 1; i <= M; ++i)
    {
        int x, y;
        fin >> x >> y;
        Edge[x].push_back(make_pair(y, i));
        Edge[y].push_back(make_pair(x, i));
    }

    for(int i = 1; i <= N; ++i)
        if(Edge[i].size()&1)
        {
            fout << "-1\n";
            return 0;
        }

    stack < int > ST;
    vector < int > Sol;
    ST.push(1);
    while(!ST.empty())
    {
        int nod = ST.top();

        while(!Edge[nod].empty() && VizEdge.test(Edge[nod].back().second))
            Edge[nod].pop_back();

        if(Edge[nod].empty())
        {
            Sol.push_back(nod);
            ST.pop();
        }
        else
        {
            int next = Edge[nod].back().first;
            VizEdge.set(Edge[nod].back().second);
            Edge[nod].pop_back();
            ST.push(next);
        }
    }
    Sol.pop_back();

    if(Sol.size() != (unsigned)M)
    {
        fout << "-1\n";
        return 0;
    }

    for(unsigned int i = 0; i < Sol.size(); ++i)
        fout << Sol[i] << ' ';

    return 0;
}