Pagini recente » Cod sursa (job #2170425) | Cod sursa (job #1198773) | Cod sursa (job #1786867) | Cod sursa (job #2506049) | Cod sursa (job #882021)
Cod sursa(job #882021)
#include <fstream>
#include <vector>
#include <algorithm>
#define DMAX 100001
using namespace std;
const char input[] = "ciclueuler.in";
const char output[] = "ciclueuler.out";
struct Node
{
int vf;
struct Node * p_next;
};
typedef struct Node * List;
List c1,c2,sfc1,sfc2;
vector <int> G[DMAX];
int d[DMAX], vis[DMAX];
int n,m, ind;
void init();
int cicle(int x, List & c, List & sfc);
void build_cicle();
void dfs(int x);
int conex();
int eulerian();
void show_cicle()
{
ofstream fout(output);
for(List p = c1; p->p_next ;p = p->p_next)
{
fout << p->vf << ' ';
}
fout << '\n';
fout.close();
}
int main()
{
init();
if(!eulerian())
{
ofstream fout(output);
fout << -1;
fout.close();
return 0;
}
build_cicle();
show_cicle();
return 0;
}
void init()
{
ifstream fin(input);
fin >> n >> m;
int i,x,y;
for(i = 1; i <= m; i++)
{
fin >> x >> y;
if(find(G[x].begin(), G[x].end(), y) != G[x].end())
{
G[x].push_back(y);
G[y].push_back(x);
}
d[x]++;
d[y]++;
}
fin.close();
}
void dfs(int x)
{
vis[x] = 1;
for(int i = 0; i < G[x].size(); i++)
if(!vis[G[x][i]])
dfs(G[x][i]);
}
int conex()
{
dfs(1);
for(int i = 1; i <= n; i++)
if(vis[i] == 0) return 0;
return 1;
}
int eulerian()
{
if(!conex()) return 0;
for(int v = 1; v <= n; v++)
if(d[v] % 2 == 1)
return 0;
return 1;
}
int cicle(int x, List & c, List & sfc)
{
List p;
int y, uvf, lg=0;
p = new Node;
p->vf = x;
p->p_next = NULL;
c = sfc = p;
do
{
uvf = sfc->vf;
if(G[uvf].empty() || G[G[uvf][0]].empty()) break; //nu mai am varfuri
y = G[uvf][0];
p = new Node;
p->vf = y;
p->p_next = NULL;
sfc->p_next = p;
sfc = p;
lg++;
G[uvf].erase(G[uvf].begin());
G[y].erase(G[y].begin());
d[y]--;
d[uvf]--;
}
while(y != x);
return lg;
}
void build_cicle()
{
int x, total = 0;
List p,q;
for(x = 1; x <= n && !d[x]; x++);
total = cicle(x, c1, sfc1);
while(total < m)
{
for(p = c1; !d[p->vf]; p = p->p_next);
total += cicle(p->vf, c2, sfc2);
q = p->p_next;
p->p_next = c2->p_next;
sfc2->p_next = q;
}
}