Legal or notTime
limit:2000/1000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 5152 Accepted Submission (s): 2360
Problem Descriptionacm-diy is a large QQ group where many excellent acmers get together. It's so harmonious this just like a big family. Every Day,many "holy cows" like HH, hh, AC, ZT, LCC, BF, Qinz and so on chats on-line to exchange their ideas. When someone had questions, many warm-hearted cows like Lost would come to help. Then the one being helped would call Lost "master", and Lost would have a nice "Prentice". By and by, there is many pairs of "Master and Prentice". But then problem Occurs:there was too many masters and too many prentices, how can we know whether it's legal or not?
We all know a master can has many prentices and a Prentice may has a lot of masters too, it ' s legal. Nevertheless,some cows is not so honest, they hold illegal relationship. Take HH and 3xian for instant, HH was 3xian ' s master and, at the same time, 3xian is HH's Master,which is quite illegal! To avoid this,please help us to judge whether their relationship are legal or not.
Please note that the ' Master and Prentice ' relation is transitive. It means if A is B's master ans B is C's master, then A is C ' s master.
Inputthe input consists of several test cases. For each case, the first line contains-integers, N (members to is tested) and M (relationships to be tested) (2 <= N , M <= 100). Then M. lines follow, each contains a pair of (x, y) which means x are Y ' s master and y is X ' s Prentice. The input is terminated by N = 0.
To make IT simple, we give every one a number (0, 1, 2,..., N-1). We use their numbers instead of their names.
Outputfor each test case, print on one line the judgement of the messy relationship.
If It is legal, output "YES", otherwise "NO".
Sample Input
3 20 11 22 20 11 00 0
Sample Output
YESNO
#include <stdio.h> #include <string.h> #include <queue> #include <vector>using namespace std; const int N = 10005;int n,in[n];vector<int>mapt[n];void init () {for (int i=0;i<=n;i++) in[i]=0,mapt[i].c Lear ();} int Tope () {queue<int>q; int k=0; for (int i=0;i<n;i++) if (in[i]==0) {k++; Q.push (i); in[i]=-1; } while (!q.empty ()) {int S=q.front (); Q.pop (); for (int i=0;i<mapt[s].size (); i++) {int j=mapt[s][i]; if (in[j]>0) {in[j]--; if (in[j]==0) {k++; In[j]=-1; Q.push (j); }}}} if (k==n) return 1; return 0;} int main () {int m,a,b; while (scanf ("%d%d", &n,&m) >0&&n) {init (); while (m--) {scanf ("%d%d", &a,&b); in[b]++; Mapt[a].push_back (b); } printf ("%s\n", Tope ()? " YES ":" NO "); }}
HDU3342 Legal or not (topological sort)