Birthday Party Celebration
All submissions for this problem are available.
Chef invited N friends on his birthday party. After celebrating his birthday, they ended up playing a new game. Everyone was assigned a special number from 1 till N in random order and all the friends sat in a line. Chef was assigned the number 0. The game comprised of a ball which would be passed from one person to another. Every friend passes the ball to his best friend. Of all the friends invited, it may be possible that all of them have their best friends present in the party or only M of them have their best friends in the party. The birthday boy is given the privilege to start the game, so he starts the game by passing the ball to his best friend and so on. A situation may arrive in which the ball starts circulating in a loop. Your task is to find the number of people who form the loop. If no loop is formed then the output should be 0.
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
- Each test case contains two space separated integers N and M.
- M lines follow. Where each line contains 2 space separated integers which are the special number assigned to the guest and the second number is the special number which is assigned to that guest’s best friend.
- For each test case, output a single line containing the number of guests who form the loop. If no loop is formed then the output should be 0.
- 1 ≤ T ≤ 100
- 2 ≤ N ≤ 10^7
- 2 ≤ M ≤ (N+1)
Input: 2 5 6 0 1 1 2 2 3 3 4 4 5 5 2 4 3 0 1 1 2 2 3 Output: 4 0
Example case 1. 2,3,4,5 form a loop, so output is 4.
Example case 2. No loop is formed, so output is 0.
|Time Limit:||1 sec|
|Source Limit:||50000 Bytes|
|Languages:||C, CPP14, JAVA, PYTH, PYTH 3.6, PYPY, CS2, PAS fpc, PAS gpc, RUBY, PHP, GO, NODEJS, HASK, SCALA, D, PERL, FORT, WSPC, ADA, CAML, ICK, BF, ASM, CLPS, PRLG, ICON, SCM qobi, PIKE, ST, NICE, LUA, BASH, NEM, LISP sbcl, LISP clisp, SCM guile, JS, ERL, TCL, PERL6, TEXT, SCM chicken, PYP3, CLOJ, FS|
Fetching successful submissions
If you are still having problems, see a sample solution here.