Cod sursa(job #2715173)

Utilizator dimi999Dimitriu Andrei dimi999 Data 3 martie 2021 09:28:20
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
#pragma GCC target ("avx2")
#pragma GCC optimize ("O3")
#pragma GCC optimize ("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

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& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long 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;
	}
};

using namespace std;

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

struct Edge
{
    int dest, poz;
};

bool viz[500005];

vector <Edge> v[100005];

int main()
{
    InParser fin("ciclueuler.in");
    int N, M;

    fin >> N >> M;

    for(int i = 1; i <= M; i++)
    {
        int x, y;

        fin >> x >> y;

        v[x].push_back({y, i});
        v[y].push_back({x, i});
    }

    for(int i = 1; i <= N; i++)
        if(v[i].size() % 2 == 1)
    {
        fout << -1 << '\n';
        return 0;
    }

    vector <int> ans;
    stack <int> st;

    st.push(1);

    while(!st.empty())
    {
        int node = st.top();

        if(v[node].size() == 0)
            {
                st.pop();
                ans.push_back(node);
                continue;
            }

        int nextt = (*v[node].begin()).dest;
        int poz = (*v[node].begin()).poz;

        v[node].erase(v[node].begin());

        if(viz[poz])
            continue;

        viz[poz] = true;
        st.push(nextt);
    }

    reverse(ans.begin(), ans.end());

    for(int i = 0; i < ans.size() - 1; i++)
        fout << ans[i] << " ";

    return 0;
}