生活随笔
收集整理的這篇文章主要介紹了
欧拉回路哈密顿回路
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
歐拉回路
總結
百度百科
混合圖的歐拉回路
Fleury算法
Hierholzer算法
#include<iostream>
#include<vector>
#include<stack>
using namespace std
;
vector
<int> g
[1001];
int n
,m
,x
,y
,d
[1001],s
=-1,t
=-1;
bool vis
[1001][1001];
stack
<int> ans
;
void dfs(int u
){for(int i
=0;i
<g
[u
].size();i
++){int v
=g
[u
][i
];if(!vis
[u
][v
]){vis
[u
][v
]=true;vis
[v
][u
]=true;dfs(v
);}}ans
.push(u
);
}
int main(){cin
>>n
>>m
;for(int i
=1;i
<=m
;i
++){cin
>>x
>>y
;d
[x
]++;d
[y
]++;g
[x
].push_back(y
);g
[y
].push_back(x
);}for(int i
=1;i
<=n
;i
++){if(d
[i
]%2==1){if(s
==-1)s
=i
;else if(t
==-1)t
=i
;else{cout
<<"Not Euler Path"<<endl
;return 0;}}}if(s
==-1)s
=1;dfs(s
);while(!ans
.empty()){int k
=ans
.top();cout
<<k
<<" ";ans
.pop();}return 0;
}
#include<iostream>
#include<vector>
#include<stack>
using namespace std
;
vector
<int> g
[1001];
int n
,m
,x
,y
,in
[1001],out
[1001],s
=-1,t
=-1;
bool vis
[1001][1001];
stack
<int> ans
;
void dfs(int u
){for(int i
=0;i
<g
[u
].size();i
++){int v
=g
[u
][i
];if(!vis
[u
][v
]){vis
[u
][v
]=true;dfs(v
);}}ans
.push(u
);
}
int main(){cin
>>n
>>m
;for(int i
=1;i
<=m
;i
++){cin
>>x
>>y
;out
[x
]++;in
[y
]++;g
[x
].push_back(y
);}for(int i
=1;i
<=n
;i
++){if(in
[i
]!=out
[i
]){if(s
==-1&&in
[i
]==out
[i
]-1)s
=i
;else if(t
==-1&&in
[i
]==out
[i
]+1)t
=i
;else{cout
<<"Not Euler Path"<<endl
;return 0;}}}if(s
==-1)s
=1;dfs(s
);while(!ans
.empty()){int k
=ans
.top();cout
<<k
<<" ";ans
.pop();}return 0;
}
哈密頓回路
哈密爾頓回路總結
總結
以上是生活随笔為你收集整理的欧拉回路哈密顿回路的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。