Pagini recente » Cod sursa (job #1507641) | Cod sursa (job #1911739) | Cod sursa (job #2762124) | Cod sursa (job #2466460) | Cod sursa (job #320567)
Cod sursa(job #320567)
#include <stdio.h>
#define MaxN 100001
int n, m;
struct nod {
int inf, edge,elim;
nod *urm,*ant;
};
nod *L[MaxN];
bool viz[MaxN];
int grad[MaxN];
void add(int ex1, int ex2){
nod *p, *q;
p = new nod;
p->inf = ex2;
p->urm = L[ex1];
p->ant = NULL;
p->edge = 0;
p->elim = 0;
if (p->urm != NULL) p->urm->ant = p;
L[ex1] = p;
q = new nod;
q->inf = ex1;
q->urm = L[ex2];
q->ant = NULL;
q->edge = 0;
q->elim = 0;
if (q->urm != NULL) q->urm->ant = q;
L[ex2] = q;
};
void DFS(int x){
viz[x] = true;
printf("%d ",x);
nod *q;
for (nod *p = L[x]; p != NULL; p = p->urm)
if (!viz[p->inf]){
p->edge = 1;
for (q = L[p->inf]; q != NULL && q->inf != x; q = q->urm);
if (q !=NULL && q->inf == x) q->edge = 1;
DFS(p->inf);
};
};
void Euler(){
int ex1,ex2,much;
ex1 = 1;
nod *p = L[1];
nod *q;
printf("%d ",ex1);
much = 1;
while (much < m){
for (q = p; q != NULL && (q->edge == 1 || q->elim == 1); q = q->urm);
if (q == NULL){
for (q = p; q != NULL && (q->elim == 1); q = q->urm);
p = q;
}; //daca nu avem decat bridge-uri
ex2 = q->inf;
q->elim = 1;
//if (ex2 != 1)
printf("%d ",ex2);
much ++;
for (q = L[ex2]; q != NULL && (q->inf != ex1); q = q->urm);
q->elim = 1;
/*
if (q->ant != NULL){ //in caz in care nu este primul nod din lista
q -> ant ->urm = q->urm;
} else { //daca este primul nod din lista
L[ex1] = L[ex1]->urm;
};
if (q->urm != NULL) //daca nu este ultimul nod din lista
q -> urm ->ant = q->ant;
delete q; //eliminam memoria alocata muchiei eliminate
if (q->ant != NULL){ //in caz in care nu este primul nod din lista
q -> ant ->urm = q->urm;
} else { //daca este primul nod din lista
L[ex2] = L[ex2]->urm;
};
if (q->urm != NULL) //daca nu este ultimul nod din lista
q -> urm ->ant = q->ant;
delete q;
*/
p = L[ex2]; //trecem la cealalta extremitate
ex1 = ex2;
}
};
int main(){
int ex1, ex2;
freopen("ciclueuler.in","r",stdin);
freopen("ciclueuler.out","w",stdout);
scanf("%d %d",&n, &m);
for (int i = 1; i <= m; i++){
scanf("%d %d", &ex1, &ex2);
add(ex1,ex2);
grad[ex1]++;
grad[ex2]++;
};
DFS(1);
for (int i = 1; i <= n; i++){
if (grad[i] % 2) {
printf("-1");
return 0;
};
if (viz[ i ] != true ) {
printf("-1");
return 0;
};
};
printf("\n");
Euler();
};