Cod sursa(job #2644005)

Utilizator WholeGrainAndy N WholeGrain Data 22 august 2020 20:52:53
Problema Ciclu Eulerian Scor 0
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 = 1e5;

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

int n, m;

//Graph representation as list of nodes is the most used
//Graph representation as list of edges (this is what we use below):
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 << ' ';

    circuit.push(from);
}

int cntDfs = 0;

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

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

int main() {
    int 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;
    }

    return 0;
}