Cod sursa(job #2924286)

Utilizator CiuiGinjoveanu Dragos Ciui Data 28 septembrie 2022 20:01:51
Problema Ciclu Eulerian Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.29 kb
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <algorithm>
#include <utility>
#include <cmath>
#include <map>
#include <deque>
#include <vector>
#include <set>
#include <queue>
#include <bitset>
#include <limits.h>
using namespace std;

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

const int MAX_SIZE = 100005;
vector<int> graph[MAX_SIZE];
int costs[MAX_SIZE];
int degree[MAX_SIZE];

void BFS() {
    costs[1] = 1;
    queue<int> positions;
    positions.push(1);
    while (!positions.empty()) {
        int current = positions.front();
        positions.pop();
        for (int next : graph[current]) {
            if (costs[next] == 0) {
                costs[next] = costs[current] + 1;
                positions.push(next);
            }
        }
    }
}

void findCycle() {
    queue<int> positions;
    positions.push(1);
    int prev = 0;
    while (!positions.empty()) {
        int current = positions.front();
        fout << current << " ";
        positions.pop();
        int maxPointCost = 0;
        int maxPoint = -1;
        int cnt = 0;
        for (int next : graph[current]) {
            if (next != current && degree[next] > 0 && costs[next] > maxPointCost) {
                maxPointCost = costs[next];
                maxPoint = next;
            }
            if (next == current) { // daca avem o muchie care duce spre ea insasi
                ++cnt;
            }
        }
        for (int i = 1; i <= cnt / 2; ++i) {
            fout << current << " ";
            degree[current] -= 2;
        }
        if (maxPoint != -1) {
            --degree[current];
            --degree[maxPoint];
            positions.push(maxPoint);
        }
        prev = current;
    }
}

int main() {
    int n, noEdges;
    fin >> n >> noEdges;
    for (int i = 1; i <= noEdges; ++i) {
        int start, end;
        fin >> start >> end;
        graph[start].push_back(end);
        graph[end].push_back(start);
        ++degree[start];
        ++degree[end];
    }
    for (int i = 1; i <= n; ++i) {
        if (degree[i] % 2 != 0) {
            fout << -1;
            return 0;
        }
    }
    BFS(); // pentru a afla ciclul eurelian
    findCycle();
}

/*

 
 7 12
 1 2
 2 3
 3 3
 3 3
 3 4
 4 5
 5 4
 4 5
 5 4
 4 6
 6 7
 7 1
 -> 1 2 3 3 3 4 5 4 5 4 6 7 1
 
 */