Cod sursa(job #2927957)

Utilizator Teodor94Teodor Plop Teodor94 Data 21 octombrie 2022 21:41:03
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <bits/stdc++.h>
using namespace std;

#define NO_NODES 100000
#define NO_EDGES 500000

struct Edge {
    int x, y;
    bool wasUsed;

    int getNeighbour(int node) { return x == node ? y : x; }
};

int noNodes, noEdges;
Edge edges[NO_EDGES];
vector<int> graph[NO_NODES];

vector<int> cycle;

void addEdge(int edgeIndex, int x, int y) {
    edges[edgeIndex] = {x, y};
    graph[x].push_back(edgeIndex);
    graph[y].push_back(edgeIndex);
}

bool checkDegrees() {
    int node;

    node = 0;
    while (node < noNodes && graph[node].size() % 2 == 0)
        ++node;
    
    return node == noNodes;
}

void euler(int node) {
    stack<int> recursion;
    int edgeIndex;

    recursion.push(node);
    while (recursion.size()) {
        node = recursion.top();

        if (graph[node].size()) {
            edgeIndex = graph[node].back();
            graph[node].pop_back();

            if (!edges[edgeIndex].wasUsed) {
                edges[edgeIndex].wasUsed = true;
                --noEdges;
                recursion.push(edges[edgeIndex].getNeighbour(node));
            }
        } else {
            cycle.push_back(node);
            recursion.pop();
        }
    }
}

int main() {
    FILE* fin = fopen("ciclueuler.in", "r");
    FILE* fout = fopen("ciclueuler.out", "w");

    int x, y, i;

    fscanf(fin, "%d%d", &noNodes, &noEdges);
    for (i = 0; i < noEdges; ++i) {
        fscanf(fin, "%d%d", &x, &y);
        addEdge(i, x - 1, y - 1);
    }

    if (checkDegrees()) {
        euler(0);

        if (noEdges == 0) {
            cycle.pop_back();
            for (int node : cycle)
                fprintf(fout, "%d ", node + 1);
        } else
            fprintf(fout, "-1\n");
    } else
        fprintf(fout, "-1\n");

    fclose(fin);
    fclose(fout);
    return 0;
}