Pagini recente » Cod sursa (job #1631699) | Cod sursa (job #2112644) | Cod sursa (job #3268725) | Cod sursa (job #2328307) | Cod sursa (job #1221107)
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
#define MAX 100010
struct Node{
int X;
struct Node * Edge, * Next, * Prev;
Node(){
Edge = Next = Prev = NULL;
X = 0;
}
Node(int X) {
Edge = Next = Prev = NULL;
this->X = X;
}
} *Gr[MAX];
stack<int> S;
vector<int> Sol;
int N, M;
void AddNeighbor(Node *A, int X) {
if (Gr[X] == NULL) {
Gr[X] = A;
} else {
Gr[X]->Next = A;
A->Prev = Gr[X];
Gr[X] = A;
}
}
void RemoveNeighbor(Node *A, int X) {
if (A->Next != NULL) {
if (A->Prev == NULL) {
A->Next->Prev = NULL;
} else {
A->Next->Prev = A->Prev;
A->Prev->Next = A->Next;
}
} else {
if (A->Prev == NULL) {
Gr[X] = NULL;
} else {
Gr[X] = A->Prev;
Gr[X]->Next = NULL;
}
}
}
void DFS() {
int X;
S.push(1);
while (S.size()) {
X = S.top();
if (Gr[X] == NULL) { // if no more neighbors
Sol.push_back(X); // then add to cycle
S.pop(); // and extract from stack
} else {
S.push(Gr[X]->X); // otherwise put that neighbor to stack
RemoveNeighbor(Gr[X]->Edge, Gr[X]->X); // and remove edge from both sides
RemoveNeighbor(Gr[X], X);
}
}
}
int main() {
int X, Y;
Node *A, *B;
freopen("ciclueuler.in","r",stdin);
freopen("ciclueuler.out","w",stdout);
memset(Gr, 0, sizeof(Gr));
scanf("%d %d", &N, &M);
for (int i = 1; i <= M; i++) {
scanf("%d %d", &X, &Y);
A = new Node(Y);
B = new Node(X);
AddNeighbor(A, X);
AddNeighbor(B, Y);
A->Edge = B;
B->Edge = A;
}
DFS();
for (int i = 0; i < Sol.size() - 1; i++) {
printf("%d ", Sol[i]);
}
return 0;
}