Jedi knights, Qui-Gon Jinn and his young apprentice Obi-Wan Kenobi, are entrusted by Queen Padmé Amidala to save Naboofrom an invasion by the Trade Federation. They must leave Naboo immediately and go to Tatooine to pick up the proof of the Federation’s evil design. They then must proceed on to the Republic’s capital planet Coruscant to produce it in front of the Republic’s Senate. To help them in this endeavor, the queen’s captain provides them with an intergalactic map. This map shows connections between planets not yet blockaded by the Trade Federation. Any pair of planets has at most one connection between them, and all the connections are two-way. To avoid detection by enemy spies, the knights must embark on this adventure without visiting any planet more than once. Can you help them by determining if such a path exists?
Note - In the attached map, the desired path is shown in bold.
The first line of the input is a positive integer t ≤ 20, which is the number of test cases. The descriptions of the test cases follow one after the other. The first line of each test case is a pair of positive integers n, m (separated by a single space). 2 ≤ n ≤ 30011 is the number of planets and m ≤ 50011 is the number of connections between planets. The planets are indexed with integers from 1 to n. The indices of Naboo, Tatooine and Coruscant are 1, 2, 3 respectively. The next m lines contain two integers each, giving pairs of planets that have a connection between them.
The output should contain t lines. The ith line corresponds to the ith test case. The output for each test case should be YES if the required path exists and NO otherwise.
Input
2
3 3
1 2
2 3
1 3
3 1
1 3
Output
YES
NO
題意:
給出一張無向圖,要求從1先走到2,再從2走到3,且每個點至多經過一次,問是否可能。
分析:
每個點至多經過一次,顯然往網絡流上靠,非常明顯的拆點。但是要求從1走到2,再從2走到3,顯然不太好處理。因為每個點最多經過一次,所以從1走到2的路徑與2走到3的路徑顯然是完全不同的兩條路徑,而且還是無向圖,那麼不妨考慮從2出發找兩條不同的路徑分別走到1和3。這樣建圖就呼之欲出了:s->2,容量為2;1->t,3->t容量均為1,圖中所有邊容量均為1,在此圖中跑最大流即可。要注意的是輸入中不在區間[1,n]內的點要扔掉。
/* * * Author : fcbruce* * Time : Wed 19 Nov 2014 04:39:23 PM CST * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include
#include