Test instructions: Give the master and pupil relationship of N, if there is a is the teacher of B, B is the master of C, C is a master, so it is not legal, output no, otherwise output yes.
Idea: Each relationship can be regarded as a directed edge, from the master to apprentice, then the apprentice's grandchildren is impossible to point to his master or himself, so it is impossible to form a ring.
Two methods:
1, with the method of topology, each time to remove a point in the degree of 0, all points are removed is legal. (This method is used in the code below)
2, with deep search, record the path, when the search through the path of the point is a ring. Each point can be searched repeatedly, because this is not a tree.
1#include <bits/stdc++.h>2 using namespacestd;3 Const intn= the;4 intN, M;5 BOOLVis[n];//Traverse6 intNum[n];//in degrees7vector< vector<int> >Vect;8deque<int>que;9 Ten intcal () One { A que.clear (); - for(intI=0; i<n; i++)if(!num[i]) que.push_back (i);//0 of the pick-and-exit degree - the while(!que.empty ()) - { - intp=Que.front (); - Que.pop_front (); +vis[p]=true; - for(intI=0, q; I<vect[p].size (); i++ ) + { Aq=Vect[p][i]; atnum[q]--;//this side of the line is erased . - if(!Num[q]) que.push_back (q); - } - } - - for(intI=0; i<n; i++)if(!vis[i])return 0; in return 1; - } to + intMain () - { the intA, B; * //freopen ("Input.txt", "R", stdin); $ while(SCANF ("%d%d",&n,&m), N)Panax Notoginseng { - vect.clear (); the vect.resize (n); +memset (NUM,0,sizeof(num)); Amemset (Vis,0,sizeof(Vis)); the for(intI=0; i<m; i++) + { -scanf"%d%d",&a,&b); $Vect[a].push_back (b);//a map of the direction $num[b]++; - } - the if(Cal ()) printf ("yes\n"); - Elseprintf"no\n");Wuyi the } - return 0; Wu}
AC Code
HDU 3342 Legal or not (whether the figure has a ring)