Cod sursa(job #1139160)

Utilizator UAIC_Balan_Negrus_HreapcaUAIC Balan Negrus Hreapca UAIC_Balan_Negrus_Hreapca Data 10 martie 2014 21:40:42
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.54 kb
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iterator>
#include <random>
#include <assert.h>
using namespace std;

const string file = "ciclueuler";

const string infile = file + ".in";
const string outfile = file + ".out";

const int INF = 0x3f3f3f3f; 

//#define ONLINE_JUDGE
vector<vector<int> > G;
int N, M;
vector<int> Sol;

void euler(int x)
{
    stack<int> st;
    st.push(x);
    while(st.empty() == false)
    {
        int x = st.top();
        if(G[x].size() != 0)
        {
            int dst = G[x][G[x].size() - 1];
            G[x].pop_back();
            st.push(dst);
            for(vector<int>::iterator itr = G[dst].begin();
                    itr != G[dst].end();
                    itr++)
            {
                if(*itr == x)
                {
                    iter_swap(itr, G[dst].end() -1);
                    G[dst].pop_back();
                    break;
                }
            }
            M--;
        }
        else
        {
            st.pop();
            Sol.push_back(x);
        }
        
    }
}


int main()
{
#ifdef ONLINE_JUDGE
	ostream &fout = cout;
	istream &fin = cin;
#else
	fstream fin(infile.c_str(), ios::in);
	fstream fout(outfile.c_str(), ios::out);
#endif	

    fin >> N >> M;
    G.resize(N + 1);
    vector<int> Grad(N + 1);
    for(int i = 0; i < M; i++)
    {
        int x, y;
        fin >> x >> y;
        Grad[x] ++;
        Grad[y] ++;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    bool ok = true;
    for(int i = 1; i <= N; i++)
    {
        if(Grad[i] % 2 == 1)
        {
            ok = false;
            break;
        }
    }
    if(ok)
    {
        euler(1);
        if(M != 0)
        {
            fout << -1 << "\n";
        }
        else
        {
            Sol.pop_back();
            copy(Sol.begin(), Sol.end(), ostream_iterator<int>(fout, " "));
            fout << "\n";
        }
    }
    else
    {
        fout << -1 << "\n";
    }

#ifdef ONLINE_JUDGE
#else
    fout.close();
	fin.close();
#endif
}