Cod sursa(job #2931574)

Utilizator CiuiGinjoveanu Dragos Ciui Data 31 octombrie 2022 15:45:53
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
using namespace std;

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

const int MAX_ARCHES = 500000;

vector<int> graph[MAX_ARCHES + 1];
pair<int, int> arches[MAX_ARCHES + 1];
bitset<MAX_ARCHES + 1> isInGraph;

void findEuler() {
    vector<int> eulerPeaks, stack;
    stack.push_back(1);
    while (!stack.empty()) {
        int curPeak = stack.back();
        if (!graph[curPeak].empty()) {
            int archNr = graph[curPeak].back();
            graph[curPeak].pop_back();
            if (isInGraph[archNr] == 0) {
                isInGraph[archNr] = 1;
                if (arches[archNr].first == curPeak) {
                    stack.push_back(arches[archNr].second);
                } else {
                    stack.push_back(arches[archNr].first);
                }
            }
        } else {
            stack.pop_back();
            eulerPeaks.push_back(curPeak);
        }
    }
    for (int i = 0; i < eulerPeaks.size() - 1; ++i) {
        fout << eulerPeaks[i] << " ";
    }
}

int main() {
    int peaks, noArches;
    fin >> peaks >> noArches;
    for (int i = 1; i <= noArches; ++i) {
        int start, end;
        fin >> start >> end;
        graph[start].push_back(i);
        graph[end].push_back(i);
        arches[i] = make_pair(start, end);
    }
    for (int i = 1; i <= peaks; ++i) {
        if (graph[i].size() % 2 != 0) {
            fout << -1;
            return 0;
        }
    }
    findEuler();
    return 0;
}