#K74917. Count Friends Who Received a Token

    ID: 34304 Type: Default 1000ms 256MiB

Count Friends Who Received a Token

Count Friends Who Received a Token

A group of friends is playing a game in which a token is passed among them according to a predefined calling pattern. The game starts with the first friend listed receiving the token. Each friend passes the token to another friend as specified. If a friend does not pass the token further, their record will contain only their name.

The task is to determine the number of distinct friends who receive the token. Formally, if we denote the passing function by $$f: \text{Friend} \to \text{Friend} \cup \{\text{None}\}$$, starting from the initial friend, compute the size of the set of friends encountered until the process terminates or a cycle is detected.

inputFormat

The input is read from standard input and follows this format:

The first line contains an integer T, representing the number of test cases.

Then for each test case:

  • The first line contains an integer N, the number of friends.
  • The second line contains N space-separated strings, representing the names of the friends. The first name is the one who initially receives the token.
  • This is followed by N lines. Each of these lines contains either one or two space-separated strings. If the line contains two strings, the first is the friend passing the token and the second is the recipient; if it contains one string, that friend does not pass the token further.

outputFormat

For each test case, output a single integer on a separate line, indicating the number of distinct friends who received the token.## sample

2
5
alice bob charlie dave eve
alice bob
bob charlie
charlie dave
dave eve
eve
3
x y z
x y
y z
z
5

3

</p>