Cod sursa(job #2699398)

Utilizator onescu.iancuOnescu Iancu onescu.iancu Data 24 ianuarie 2021 13:17:18
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>

using namespace std;

int n, m;
vector<vector<int>> graph;
vector<int> cycle;

void ReadGraph(){
    ifstream fin("ciclueuler.in");

    fin >> n >> m;
    graph.resize(n+1);

    int x, y;
    for(int i=0; i<m; ++i){
        fin >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }
}

void DFS(int node, vector<bool> &visited){
    visited[node] = true;

    for(auto it: graph[node])
        if(!visited[it])
            DFS(it, visited);
}

bool GraphIsConexTest(){
    vector<bool> visited(n+1, false);

    int i;
    for(i=1; i<=n; ++i)
        if(graph[i].size() != 0)
            break;

    if(i == n)
        return true;

    DFS(i, visited);

    for(i=1; i<=n; i++)
        if(!visited[i] && graph[i].size())
            return false;
    return true;
}

bool InitialTest(){
    for(int i=1; i<=n; ++i)
        if(graph[i].size() % 2)
            return false;
    return GraphIsConexTest();
}

void GetCycle(int node){
    while(graph[node].size()){
        int next = graph[node].back();
        //delete uv
        graph[node].pop_back();
        //delete vu -> find is always != graph[next].end() because we had uv so now we must have vu
        graph[next].erase(find(graph[next].begin(), graph[next].end(), node));
        GetCycle(next);
    }
    cycle.push_back(node);
}

int main()
{
    ofstream fout("ciclueuler.out");
    ReadGraph();
    if(InitialTest()){
        GetCycle(1);
        for(auto it=cycle.begin(); it!=cycle.end()-1; it++)
            fout << *it << " ";
    }
    else fout << "-1";
    return 0;
}