欧拉路
Fluery算法:
1 #include <cstdlib> 2 #include <cstring> 3 #include <cstdio> 4 #include <iostream> 5 #include <algorithm> 6 using namespace std; 7 8 /* 9 弗罗莱算法 10 */ 11 12 #define MAXN 1005 13 14 int stk[MAXN]; 15 int top; 16 int N, M, start; 17 int mp[MAXN][MAXN]; 18 19 void dfs(int x) { 20 stk[top++] = x; 21 for (int i = 1; i <= N; ++i) { 22 if (mp[x][i]) { 23 mp[x][i] = mp[i][x] = 0; // 删除此边 24 dfs(i); 25 break; 26 } 27 } 28 } 29 30 void fleury(int start) { 31 int brige; 32 top = 0; 33 stk[top++] = start; // 将起点放入Euler路径中 34 while (top > 0) { 35 brige = 0; 36 for (int i = 1; i <= N; ++i) { // 试图搜索一条边不是割边(桥) 37 if (mp[stk[top-1]][i]) { 38 brige = 1; 39 break; 40 } 41 } 42 if (!brige) { // 如果没有点可以扩展,输出并出栈 43 printf("%d ", stk[--top]); 44 } else { // 否则继续搜索欧拉路径 45 dfs(stk[--top]); 46 } 47 } 48 printf("\n"); 49 } 50 51 int main() { 52 int x, y, deg, num; 53 while (scanf("%d %d", &N, &M) != EOF) { 54 memset(mp, 0, sizeof(mp)); 55 for (int i = 0; i < M; ++i) { 56 scanf("%d %d", &x, &y); 57 mp[x][y] = mp[y][x] = 1; 58 } 59 start = 1, num = 0; 60 for (int i = 1; i <= N; ++i) { 61 deg = 0; 62 for (int j = 1; j <= N; ++j) { 63 deg += mp[i][j]; 64 } 65 if (deg % 2 == 1) { 66 start = i, ++num; 67 } 68 } 69 if (num == 0 || num == 2) fleury(start); 70 else printf("No Euler Path\n"); 71 } 72 return 0; 73 }