#C8985. Synonym Groups

    ID: 53027 Type: Default 1000ms 256MiB

Synonym Groups

Synonym Groups

Given a list of words and a list of synonym pairs, your task is to identify groups of words that are connected directly or transitively by synonym relationships. Two words belong to the same group if they are the same or if there exists a chain of synonym pairs connecting them.

Notes:

  • You may assume that the number of words \( n \) satisfies \(1 \le n \le 100,000\) and each word consists of at most 30 lowercase English letters.
  • The number of synonym pairs \( m \) satisfies \(0 \le m \le 100,000\).
  • The groups and the words within each group can be printed in any order. However, for consistency, you should sort the words in each group in lexicographical order, and sort all groups by the lexicographically smallest word in the group.

Example:

Input:
8
car
automobile
vehicle
driver
controller
steering
wheel
turn
3
car automobile
vehicle automobile
driver controller

Output: 5 automobile car vehicle controller driver steering turn wheel

</p>

inputFormat

The input is given from standard input (stdin) and has the following format:

Line 1: An integer \( n \) representing the number of words.
Next \( n \) lines: Each line contains a single word.
Next line: An integer \( m \) representing the number of synonym pairs.
Next \( m \) lines: Each line contains two words separated by a space, indicating that they are synonyms.

outputFormat

Output to standard output (stdout) in the following format:

Line 1: An integer representing the total number of synonym groups.
Next lines: Each line corresponds to one group. Print the words in the group separated by a space. Each group must have its words sorted in lexicographical order, and the groups should be ordered by their smallest word in lexicographical order.
## sample
8
car
automobile
vehicle
driver
controller
steering
wheel
turn
3
car automobile
vehicle automobile
driver controller
5

automobile car vehicle controller driver steering turn wheel

</p>