Cod sursa(job #2942359)

Utilizator TeodoraMaria123Serban Teodora Maria TeodoraMaria123 Data 19 noiembrie 2022 16:44:41
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.52 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>

using namespace std;

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

#define MAX_VERTICES 100000
#define MAX_EDGES 500000

struct edge
{
    int otherVertex;
    int id;
};

int n, m, startingNode;
vector <int> eulerCycle;
stack <int> cycle;
vector < vector <edge> > graph;
bitset <MAX_EDGES + 1> visited;
bitset <MAX_VERTICES + 1> marked;

void readGraph()
{
    in >> n >> m;
    graph.resize(n + 1);
    for(int i = 1; i <= m; i++)
    {
        int a, b;
        in >> a >> b;
        graph[a].push_back({b,i});
        graph[b].push_back({a,i});
    }
}

void dfs(int node)
{
    marked[node] = 1;
    for(auto newEdge : graph[node])
    {
        int neighbour = newEdge.otherVertex;
        if(!marked[neighbour])
            dfs(neighbour);
    }
}

bool isConnected()
{
    startingNode = 1;
    while(startingNode <= n  &&  graph[startingNode].empty())
        startingNode ++;

    if(startingNode == n + 1)
        return 1;

    dfs(startingNode);

    int node = startingNode;
    while(node <= n  &&  (graph[node].empty() ||  marked[node]== 1))
        node ++;

    return node == (n + 1);
}

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

void euler()
{
    cycle.push(startingNode);
    while(!cycle.empty())
    {
        int node = cycle.top(), foundEdge = 0;
        if(!graph[node].empty())
        {
            auto neighbour = graph[node].back();
            graph[node].pop_back();
            if(!visited[neighbour.id])
            {
                cycle.push(neighbour.otherVertex);
                visited[neighbour.id] = 1;
            }
        }
        else
        {
            eulerCycle.push_back(node);
            cycle.pop();
        }
    }

    vector <int> :: reverse_iterator it;
    for(it = eulerCycle.rbegin(); it < eulerCycle.rend() - 1; it++)
        out << *it << " ";
}

//void euler(int node)
//{
////        out << node << "\n";
//    for(auto neighbour : graph[node])
//    {
//        if(!visited[neighbour.id])
//        {
//            visited[neighbour.id] = 1;
//            euler(neighbour.otherVertex);
//        }
//    }
//    eulerCycle.push_back(node);
//}

int main()
{
    readGraph();

    if(isConnected() &&  evenDegrees())
    {
        euler();
    }
    else
    {
        out << -1;
    }
    return 0;
}