欧拉回路第一题TVT
本题的一个小技巧在于:
【建立一个存放点与边关系的邻接矩阵】
1.先判断是否存在欧拉路径
无向图:
欧拉回路:连通 + 所有定点的度为偶数
欧拉路径:连通 + 除源点和终点外都为偶数
有向图:
欧拉回路:连通 + 所有点的入度 == 出度
欧拉路径:连通 + 源点 出度-入度=1 && 终点 入度 - 出度 = 1 && 其余点 入度 == 出度;
2.求欧拉路径 :
step 1:选取起点(如果是点的度数全为偶数任意点为S如果有两个点的度数位奇数取一个奇数度点为S)
step 2:对当前选中的点的所有边扩展,扩展条件(这条边为被标记),若可扩展 ->step 2;否则 step 3;
step 3:将次边计入path结果保存。
思路还是很清晰的。
贴代码了:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm> #define ll long long
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = ;
int vis[], indegree[], map[][], n;
stack <int> s; void init(){
n = ;
memset(vis, , sizeof(vis));
memset(map, , sizeof(map));//define the relationship between vertex and edge
memset(indegree, , sizeof(indegree));
} int euler(int u){
int i;
for(i = ; i <= n; ++i){// n represents edges
if(map[u][i] && !vis[i]){
vis[i] = ;
euler(map[u][i]);
s.push(i);
}
}
return ;
} int main(){
int first, i, j, x, y, w;
while(cin >> x >> y){
if(x == && y == ) break;
cin >> w;
init();
map[x][w] = y;
map[y][w] = x;
++indegree[x];
++indegree[y];
first = x > y ? y : x;//get first vertex , but speacil judge as u casual
n = n > w ? n : w;//get numbered largest edge
while(true){
cin >> x >> y;
if(!x && !y)
break;
cin >> w;
map[x][w] = y;
map[y][w] = x;
++indegree[x];
++indegree[y];
n = n > w ? n : w;
}
for(i = ; i < ; ++i)//judge if exists solution
if(indegree[i] % ) break;
if(i < )
cout << "Round trip does not exist.\n";
else{
euler(first);
while(!s.empty()){
cout << s.top() << ' ';
s.pop();
}
cout << endl;
}
}
return ;
}