POJ 2230 Watchcow 欧拉回路的DFS解法(模板题)
Watchcow
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 9974 Accepted: 4307 Special Judge
Description
Bessie’s been appointed the new watch-cow for the farm. Every night, it’s her job to walk across the farm and make sure that no evildoers are doing any evil. She begins at the barn, makes her patrol, and then returns to the barn when she’s done.
If she were a more observant cow, she might be able to just walk each of M (1 <= M <= 50,000) bidirectional trails numbered 1…M between N (2 <= N <= 10,000) fields numbered 1…N on the farm once and be confident that she’s seen everything she needs to see. But since she isn’t, she wants to make sure she walks down each trail exactly twice. It’s also important that her two trips along each trail be in opposite directions, so that she doesn’t miss the same thing twice.
A pair of fields might be connected by more than one trail. Find a path that Bessie can follow which will meet her requirements. Such a path is guaranteed to exist.
Input
-
Line 1: Two integers, N and M.
-
Lines 2…M+1: Two integers denoting a pair of fields connected by a path.
Output -
Lines 1…2M+1: A list of fields she passes through, one per line, beginning and ending with the barn at field 1. If more than one solution is possible, output any solution.
Sample Input
4 5
1 2
1 4
2 3
2 4
3 4
Sample Output
1
2
3
4
2
1
4
3
2
4
1
Hint
OUTPUT DETAILS:
Bessie starts at 1 (barn), goes to 2, then 3, etc…
Source
USACO 2005 January Silver
這道題當(dāng)時做的時候,覺得好難啊,學(xué)長說這是歐拉回路,然后我一想沒學(xué),后來在課程總結(jié)中發(fā)現(xiàn)原來學(xué)了,自己沒注意。對全圖進(jìn)行dfs,從規(guī)定起點(diǎn)開始,過程中記錄經(jīng)過了哪些邊,以保證每條邊只經(jīng)過一次。當(dāng)一個點(diǎn)的所有邊都遍歷完成后,把該點(diǎn)入棧。最后依次彈棧得到的就是歐拉路徑。被入棧的點(diǎn)都是走投無路的點(diǎn),如果存在歐拉路徑,第一次出現(xiàn) 沒有邊一定是在走回到起點(diǎn)時,因?yàn)槠渌闆r無論怎么走只可能略過一些邊,而不可能走進(jìn)死路,所以若存在歐拉回路,必定在最后一個點(diǎn)的最后一條邊回到起始點(diǎn)。
總結(jié)
以上是生活随笔為你收集整理的POJ 2230 Watchcow 欧拉回路的DFS解法(模板题)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 标签云效果(简单示例,入门参考)
- 下一篇: 电视网络版和电视版的区别