Pagini recente » Cod sursa (job #301929) | Cod sursa (job #2453359) | Cod sursa (job #1227436) | Cod sursa (job #2953923) | Cod sursa (job #361518)
Cod sursa(job #361518)
//Code by Patcas Csaba
//Time complexity:
//Space complexity:
//Method:
//Implementation time:
#include <vector>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <bitset>
#include <stack>
#include <list>
#include <numeric>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cctype>
#include <cmath>
#include <ctime>
#include <cassert>
using namespace std;
#define LL long long
#define PII pair <int, int>
#define VB vector <bool>
#define VI vector <int>
#define VD vector <double>
#define VS vector <string>
#define VPII vector <pair <int, int> >
#define VVI vector < VI >
#define VVB vector < VB >
#define FORN(i, n) for(int i = 0; i < (n); ++i)
#define FOR(i, a, b) for(int i = (a); i <= (b); ++i)
#define FORI(it, X) for(__typeof((X).begin()) it = (X).begin(); it !=(X).end(); ++it)
#define REPEAT do{
#define UNTIL(x) }while(!(x));
#define SZ size()
#define BG begin()
#define EN end()
#define CL clear()
#define X first
#define Y second
#define RS resize
#define PB push_back
#define MP make_pair
#define ALL(x) x.begin(), x.end()
#define in_file "ciclueuler.in"
#define out_file "ciclueuler.out"
ifstream fin(in_file);
ofstream fout(out_file);
int n, m;
vector < list <int> > g;
VI gr, sol;
VB was;
inline void AddEdge(int x, int y)
{
g[x].PB(y);
g[y].PB(x);
++gr[x];
++gr[y];
}
inline void RemoveEdge(int x, int y)
{
list<int> :: iterator i = g[x].BG;
while (*i != y) ++i;
g[x].erase(i);
i = g[y].BG;
while (*i != x) ++i;
g[y].erase(i);
--gr[x];
--gr[y];
}
inline bool Euler()
{
FOR(i, 1, n)
if (gr[i] & 1) return false;
return true;
}
void Bf()
{
queue <int> fifo;
fifo.push(1);
was[1] = true;
while (!fifo.empty())
{
int head = fifo.front();
for(list<int> :: iterator i = g[head].BG; i != g[head].EN; ++i)
{
int aux = *i;
if (!was[aux])
{
was[aux] = true;
fifo.push(aux);
}
}
fifo.pop();
}
}
bool Connected()
{
fill(ALL(was), false);
Bf();
FOR(i, 1, n)
if (gr[i] && !was[i]) return false;
return true;
}
void Fleury()
{
was.RS(n + 1);
int node = 1;
while (sol.SZ < m)
{
sol.PB(node);
int found = -1;
FORN(i, gr[node])
{
list<int> :: iterator it = g[node].BG;
int aux = *it;
RemoveEdge(node, aux);
if (Connected())
{
found = aux;
break;
}
AddEdge(node, aux);
}
if (found != -1) node = found;
else
{
found = *g[node].BG;
RemoveEdge(node, found);
node = found;
}
}
}
int main()
{
//Read data
fin >> n >> m;
g.RS(n + 1);
gr.RS(n + 1);
FORN(i, m)
{
int x, y;
fin >> x >> y;
AddEdge(x, y);
}
fin.close();
//Solve
if (!Euler())
{
fout << -1;
fout.close();
return 0;
}
Fleury();
//Write data
FORN(i, sol.SZ) fout << sol[i] << " ";
fout.close();
return 0;
}