#P3026. [USACO11OPEN] Learning Languages S

[USACO11OPEN] Learning Languages S

Description

Farmer John's NN (2N10,0002 \le N \le 10{,}000) cows, conveniently numbered 1..N1..N, are fluent in some MM (1M30,0001 \le M \le 30{,}000) languages, also conveniently numbered 1..M1..M. Cow ii can speak KiK_i (1KiM1 \le K_i \le M) languages, namely Li1,Li2,...,LiKiL_{i1}, L_{i2}, ..., L_{i K_i} (1LijM1 \le L_{ij} \le M). FJ's cows are not that smart, so the sum of KiK_i over all cows ii is at most 100,000100{,}000.

Two cows cannot directly talk to each other unless they both speak a common language. However, cows can pass messages along, translating if necessary. In other words, cows AA and BB can have a conversation if and only if there exists a sequence of cows T1,T2,...,TkT_1, T_2, ..., T_k such that AA and T1T_1 share a language, T1T_1 and T2T_2 share a language, ..., and TkT_k and BB share a language.

Farmer John wants all his cows to be able to socialize with any other cow. He can buy books to teach any one of his cows any language he pleases. Being frugal, FJ wants to purchase the minimum number of books necessary to enable all of his cows to speak to each other. Help him determine:

  • The minimum number of books he must purchase.
  • Any set of books assigned to cows, in any order, that will achieve this goal; a program will grade your output.

By way of example, suppose there are three cows named Alberta, Bessie, and Contessa along with three languages denoted as #1, #2, and #3. Alberta can speak languages #2 and #3, Bessie can speak language #2, and Contessa can speak language #1. Currently, Alberta and Bessie can talk to each other, but Contessa is left alone.

#1   #2   #3
Alberta           x    x
Bessie            x
Contessa     x

FJ wants to fix this situation, so he can buy Contessa a book to teach her language #2. This will ensure all cows speak the same language, so they can all communicate with one another.

Note that an alternate solution exists: instead, FJ could buy Contessa a book to teach her language #3. Not all cows would speak the same language, but this would still be a valid solution because Contessa could communicate through Alberta (who also speaks language #3) if she wants to talk to Bessie. Other alternatives exist, and any valid alternate solution will also be accepted.

Input Format

  • Line 1: Two space-separated integers: NN and MM.
  • Lines 2..N+12..N+1: Line i+1i+1 describes the languages that cow ii can speak with Ki+1K_i + 1 space-separated integers: KiK_i, Li1L_{i1}, Li2L_{i2}, ..., LiKiL_{i K_i}.

Output Format

  • Line 1: A single integer that is the minimum number of books that FJ must purchase.
  • Lines 2..B+12..B+1: Line i+1i+1 contains two space-separated integers: the language id and the id of the cow to receive book ii, where BB is the number printed on line 1. If multiple solutions exist, print any one.
3 3 
2 3 2 
1 2 
1 1 

1 

Hint

Translated by ChatGPT 5