SAC '21 Code Challenge P5 - Friends of Friends

View as PDF

Submit solution


Points: 7 (partial)
Time limit: 1.0s
Memory limit: 256M

Author:
Problem types

After a student started a rumour, you have been tasked with implementing a system to count the number of people that heard it for the N students in the school: you will be asked Q queries of 2 types:

1 u v: u and v are now friends and can spread the rumour from their friends to each other.

2 x: If x started a rumour, output the number of people that heard the rumour, including the starter.

Input Specification

The first line will contain N and Q, the number of students and the number of queries.

The next Q lines will contain one of the above queries.

Output Specification

Output the answer to each type 2 query.

Constraints

For all subtasks:

1N,Q100000

1u,v,xN

Subtask 1 [40%]

1N,Q1000

Subtask 2 [60%]

No additional constraints.

Sample Input

Copy
5 6
2 3
1 1 2
1 2 3
2 1
1 4 5
2 4

Sample Output

Copy
1
3
2

Explanation for Sample Output

For the 1st query, the 3rd student is only able to reach himself, so the answer is 1. For the 2nd query, the 1st student can reach himself and the 2nd and 3rd student. For the 3rd query, the 4th person can only reach himself and the 5th student.


Comments


  • 1
    kresteodymium  commented on June 10, 2021, 12:33 a.m. edited

    My DFS TLEd on the 3rd batch :(


    • 6
      vishnus  commented on June 10, 2021, 4:01 p.m. edited

      DFS will most likely TLE for this problem. Try using another data structure. You can also check the editorial for more tips.