Cod sursa(job #2668798)

Utilizator Alex_tz307Lorintz Alexandru Alex_tz307 Data 5 noiembrie 2020 13:51:11
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>

using namespace std;

class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;
	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}
	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};

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

int main() {
    int N, M;
    fin >> N >> M;
    vector < vector < int > > G(N + 1);
    for(int i = 0; i < M; ++i) {
        int u, v;
        fin >> u >> v;
        G[u].emplace_back(v);
        G[v].emplace_back(u);
    }
    for(int i = 1; i <= N; ++i)
        if(G[i].size() & 1) {
            fout << -1;
            return 0;
        }
    vector < int > sol;
    stack < int > S;
    S.emplace(1);
    while(!S.empty()) {
        int node = S.top();
        if(!G[node].empty()) {
            int next = G[node].back();
            G[node].pop_back();
            G[next].erase(find(G[next].begin(), G[next].end(), node));
            S.emplace(next);
        }
        else {
            S.pop();
            sol.emplace_back(node);
        }
    }
    sol.pop_back();
    for(int node : sol)
        fout << node << ' ';
}