Cod sursa(job #1710897)

Utilizator Ionut228Ionut Calofir Ionut228 Data 29 mai 2016 22:42:47
Problema Ciclu Eulerian Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.34 kb
#include <fstream>
#include <vector>

using namespace std;

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

int N, M;
vector<int> V[100005], A[100005], I[100005];

void delete_nod(int now, int nod)
{
    int lg = V[now].size();
    for (int i = 0; i < lg; ++i)
        if (V[now][i] == nod)
        {
            swap(V[now][i], V[now][lg - 1]);
            V[now].pop_back();
            break;
        }
}

void dfs(int nod)
{
    while (!V[nod].empty())
    {
        int now = V[nod][0];
        swap(V[nod][0], V[nod][V[nod].size() - 1]);
        V[nod].pop_back();
        delete_nod(now, nod);

        if (!used[now])
        {
            used[now] = true;
            A[nod].push_back(now);
            A[now].push_back(nod);
            dfs(now);
        }
        else
        {
            I[nod].push_back(now);
            I[now].push_back(nod);
        }
    }
}

void delete_nodI(int now, int nod)
{
    int lg = I[now].size();
    for (int i = 0; i < lg; ++i)
        if (I[now][i] == nod)
        {
            swap(I[now][i], I[now][lg - 1]);
            I[now].pop_back();
            break;
        }
}

void delete_nodA(int now, int nod)
{
    int lg = A[now].size();
    for (int i = 0; i < lg; ++i)
        if (A[now][i] == nod)
        {
            swap(A[now][i], A[now][lg - 1]);
            A[now].pop_back();
            break;
        }
}

void solve(int nod)
{
    fout << nod << ' ';

    while (!I[nod].empty())
    {
        int now = I[nod][0];
        swap(I[nod][0], I[nod][I[nod].size() - 1]);
        I[nod].pop_back();
        delete_nodI(now, nod);

        solve(now);
    }

    while (!A[nod].empty())
    {
        int now = A[nod][0];
        swap(A[nod][0], A[nod][A[nod].size() - 1]);
        A[nod].pop_back();
        delete_nodA(now, nod);

        solve(now);
    }
}

int main()
{
    fin >> N >> M;
    for (int i = 1, nod1, nod2; i <= M; ++i)
    {
        fin >> nod1 >> nod2;

        V[nod1].push_back(nod2);
        V[nod2].push_back(nod1);
    }

    used[1] = true;
    dfs(1);
    /*for (int i = 1; i <= N; ++i)
    {
        int lg = V[i].size();
        if (!used[i] || lg % 2 == 1)
        {
            fout << "-1\n";
            return 0;
        }
    }*/

    solve(1);

    return 0;
}