#P3026. [USACO11OPEN] Learning Languages S
[USACO11OPEN] Learning Languages S
Description
Farmer John's () cows, conveniently numbered , are fluent in some () languages, also conveniently numbered . Cow can speak () languages, namely (). FJ's cows are not that smart, so the sum of over all cows is at most .
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 and can have a conversation if and only if there exists a sequence of cows such that and share a language, and share a language, ..., and and 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: and .
- Lines : Line describes the languages that cow can speak with space-separated integers: , , , ..., .
Output Format
- Line 1: A single integer that is the minimum number of books that FJ must purchase.
- Lines : Line contains two space-separated integers: the language id and the id of the cow to receive book , where 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
京公网安备 11011102002149号