Cod sursa(job #3260492)

Utilizator schema_227Stefan Nicola schema_227 Data 2 decembrie 2024 16:22:16
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

ifstream cin("ciclueuler.in");
ofstream cout("ciclueuler.out");

const int MAX_NODES = 100005;
const int MAX_EDGES = 1000005;

vector<int> graph[MAX_NODES], eulerCycle;
bool usedEdge[MAX_EDGES], visitedNode[MAX_NODES];
int n, m;
int node1[MAX_EDGES], node2[MAX_EDGES];

void dfs(int node) {
    visitedNode[node] = true;
    for (auto edgeIdx : graph[node]) {
        int nextNode = node1[edgeIdx] + node2[edgeIdx] - node;
        if (!visitedNode[nextNode]) {
            dfs(nextNode);
        }
    }
}

bool isEulerian() {
    dfs(1);
    for (int i = 1; i <= n; ++i) {
        if (!visitedNode[i] || graph[i].size() % 2 != 0) {
            return false;
        }
    }
    return true;
}

void findEulerCycle(int node) {
    while (!graph[node].empty()) {
        int edgeIdx = graph[node].back();
        graph[node].pop_back();
        if (usedEdge[edgeIdx]) {
            continue;
        }
        usedEdge[edgeIdx] = true;
        int nextNode = node1[edgeIdx] + node2[edgeIdx] - node;
        findEulerCycle(nextNode);
    }
    eulerCycle.push_back(node);
}

int main() {
    cin >> n >> m;

    for (int i = 1; i <= m; ++i) {
        int a, b;
        cin >> a >> b;
        node1[i] = a;
        node2[i] = b;
        graph[a].push_back(i);
        graph[b].push_back(i);
    }

    if (!isEulerian()) {
        cout << "-1\n";
        return 0;
    }

    memset(usedEdge, 0, sizeof usedEdge);
    findEulerCycle(1);

    for (int i = 0; i < (int)eulerCycle.size() - 1; ++i) {
        cout << eulerCycle[i] << ' ';
    }
    cout << '\n';

    return 0;
}