Topic Connection
http://acm.hdu.edu.cn/showproblem.php?pid=5154
Harry and Magical Computerdescription
In reward of being yearly outstanding magic student, Harry gets a magical computer. When the computer begins-deal with a process, it'll work until the ending of the processes. One day the computer got N processes to deal with. We number the processes from 1 to n. However there is some dependencies between some processes. When there exists a dependencies (a, b), it means process B must is finished before process a. By knowing all the M dependencies, Harry wants to know if the computer can finish all the n processes.
Input
There is several test cases, you should process to the end of file.
For each test case, there is numbers N m on the first line, indicates the number processes and the number of Dependen Cies. $ \leq n \leq 100,1 \leq m \leq 10000$
The next following m lines, each line contains the numbers a B, indicates a dependencies $ (a, B). 1 \leq A, b \leq n$
Output
Output one line for each test case.
If the computer can finish all the process print "YES" (without quotes).
Else print "NO" (without quotes).
Sample Input
3 2
3 1
2 1
3 3
3 2
2 1
1 3
Sample Output
YES
NO
First set up a graph, and then traverse, if the vertex has not access to the output "no", otherwise output "YES" ...
1#include <algorithm>2#include <iostream>3#include <cstdlib>4#include <cstring>5#include <cstdio>6#include <vector>7#include <queue>8#include <map>9 usingstd::cin;Ten usingstd::cout; One usingStd::endl; A usingStd::find; - usingStd::sort; - usingstd::p air; the usingstd::vector; - usingStd::queue; - usingStd::multimap; - #definePB (E) push_back (e) + #defineSZ (c) (int) (c). Size () - #defineMP (A, b) Make_pair (A, B) + #defineAll (c) (c). Begin (), (c). End () A #defineITER (c) Decltype ((c). Begin ()) at #defineCLS (arr,val) memset (arr,val,sizeof (arr)) - #defineCpresent (c, E) (Find (All (c), (e))! = (c). End ()) - #defineRep (i, n) for (int i = 0; i < (int) (n); i++) - #defineTR (c, I) for (ITER (c) i = (c). Begin (); I! = (c). end (); ++i) - Const intN = the; - intN, M, g[n][n]; in BOOLVis[n], flag[n]; -typedef unsignedLong Longull; to voidBFs () { + BOOLf =false; -queue<int>que; the Rep (i, N) { * if(!Flag[i]) { $Vis[i] =true;Panax Notoginseng Que.push (i); - } the } + while(!Que.empty ()) { A intp =Que.front (); Que.pop (); the Rep (i, N) { + if(G[p][i]) { - if(Vis[i])Continue; $ Que.push (i); $Vis[i] =true; - } - } the } - Rep (i, N) {Wuyi if(!vis[i]) {f =true; Break; } the } -Puts (f?"NO":"YES"); Wu } - intMain () { About #ifdef LOCAL $Freopen ("In.txt","R", stdin); -Freopen ("OUT.txt","w+", stdout); - #endif - intA, B; A while(~SCANF ("%d%d", &n, &m)) { +CLS (Vis,0), CLS (Flag,0), CLS (G,0); the Rep (i, m) { -scanf"%d%d", &a, &b); $G[b-1][a-1] =1; theFlag[a-1] =1; the } the BFS (); the } - return 0; in}
View Code
Hdu 5154 Harry and magical computer