Pagini recente » Cod sursa (job #1681656) | Cod sursa (job #245800) | Cod sursa (job #1923914) | usu9 | Cod sursa (job #771874)
Cod sursa(job #771874)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxn 100001
struct list{ int v; struct list *next; } *G[maxn];
int N, D[maxn], Q[500000], top;
FILE *in, *out;
int eulerian();
int conex();
void erase(int a, int b);
int main ()
{
int i, a, b;
struct list *p;
in = fopen ("ciclueuler.in", "r");
fscanf (in, "%d %d", &N, &i);
for (; i; --i)
{
fscanf (in, "%d %d", &a, &b);
D[a]++, D[b]++;
p = malloc (sizeof(struct list));
p->v = b; p->next = G[a]; G[a] = p;
p = malloc (sizeof(struct list));
p->v = a; p->next = G[b]; G[b] = p;
}
fclose (in);
out = fopen ("ciclueuler.out", "w");
if (!eulerian())
fprintf (out, "-1");
else
for (top = 0, Q[0] = 1; top >= 0;)
{
if ( D[ Q[top] ] == 0 )
{
fprintf(out, "%d ", Q[top]);
top--;
}
else
for (p = G[ Q[top] ]; p; p = p->next)
{
D[ Q[top] ]--; D[p->v] --;
Q[++top] = p->v;
erase (Q[top-1], p->v);
break;
}
}
fprintf(out, "\n");
fclose (out);
return 0;
}
void erase(int a, int b){
struct list *p, *i;
for (i = NULL, p = G[a]; p->v != b; i = p, p = p->next);
if(i == NULL)
{
G[a] = p->next;
free(p);
}
else
{
i->next = p->next;
free(p);
}
for (i = NULL, p = G[b]; p->v != a; i = p, p = p->next);
if(i == NULL)
{
G[b] = p->next;
free(p);
}
else
{
i->next = p->next;
free(p);
}
}
int eulerian(){
int i;
for(i = 1; i <= N; ++i)
if(D[i] % 2 == 1)
return 0;
return conex();
}
int conex(){
char used[maxn];
int l, r;
struct list *p;
memset(used, 0, sizeof(used));
Q[0] = 1;
used[1] = 1;
for(l = r = 0; l <= r; ++l)
for(p = G[ Q[l] ]; p; p = p->next)
if(!used[p->v]){
used[p->v] = 1;
Q[++r] = p->v;
}
for(l = 1; l <= N; ++l)
if(!used[l])
return 0;
return 1;
}