Cod sursa(job #2645871)

Utilizator WholeGrainAndy N WholeGrain Data 29 august 2020 19:57:12
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

int const CAP = 1e6;

struct Edge {
    int node1;
    int node2;
    int del;
};

int n, m;
vector<Edge> edges; //This is the only place where the state changes
vector<int> g[CAP]; //g[i][j] is not a node, it's an Edge
int visited[CAP];
stack<int> circuit;

void euler(int from) {
    while(!g[from].empty()) {
        int i = g[from].back();  //i = the index of an Edge
        g[from].pop_back();
        if (edges[i].del == 0) {  //Correct and O(m)
            edges[i].del = 1;
            int to = edges[i].node2;
            if(to == from) {
                to = edges[i].node1;
            }
            euler(to);
        }
    }
    out << from + 1<< ' ';
    circuit.push(from);
}

int cntDfs = 0;
void dfs(int from) {
    if (visited[from]) {
        return;
    }
    cntDfs++;
    visited[from] = true;
    for (int i = 0; i < g[from].size(); i++) {
        int to = edges[g[from][i]].node1;
        if(to == from) {
            to = edges[g[from][i]].node2;
        }
        dfs(to);
    }
}

bool hasSolution() {
    for (int i = 0; i < n; i++) {
        if (g[i].size() % 2 != 0) {
            return false;
        }
    }
    dfs(0);

    return (cntDfs == n);
}

int main() {
    in >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y;
        in >> x >> y;
        x--;
        y--;
        edges.push_back({x, y, 0}); //i-th edge inserted

        g[x].push_back(i);
        g[y].push_back(i);
    }
    if (!hasSolution()) {
        out << -1 << '\n';
        return 0;
    }
    euler(0);
    return 0;
}