Cod sursa(job #2931571)

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

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

const int MAX_ARCHES = 500005;
const int MAX_PEAKS = 100005;
vector<int> graph[MAX_ARCHES];

int from[MAX_ARCHES], to[MAX_ARCHES];
int isInGraph[MAX_ARCHES];

void findEuler(int curPeak) {
    vector<int> result;
    vector<int> stack;
    stack.push_back(curPeak);
    while (!stack.empty()) {
        curPeak = stack.back();
        if (!graph[curPeak].empty()) {
            int archNr = graph[curPeak].back();
            graph[curPeak].pop_back();
            if (isInGraph[archNr] == 0) {
                isInGraph[archNr] = 1;
                int start = from[archNr];
                int end = to[archNr];
                if (start == curPeak) {
                    stack.push_back(end);
                } else {
                    stack.push_back(start);
                }
            }
        } else {
            stack.pop_back();
            result.push_back(curPeak);
        }
    }
    for (int i = 0; i < result.size() - 1; ++i) {
        fout << result[i] << " ";
    }
}

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