POJ 1904 King's Quest(强连通分量)
題目鏈接
Description
Once upon a time there lived a king and he had N sons. And there were N beautiful girls in the kingdom and the king knew about each of his sons which of those girls he did like. The sons of the king were young and light-headed, so it was possible for one son to like several girls.
So the king asked his wizard to find for each of his sons the girl he liked, so that he could marry her. And the king’s wizard did it – for each son the girl that he could marry was chosen, so that he liked this girl and, of course, each beautiful girl had to marry only one of the king’s sons.
However, the king looked at the list and said: “I like the list you have made, but I am not completely satisfied. For each son I would like to know all the girls that he can marry. Of course, after he marries any of those girls, for each other son you must still be able to choose the girl he likes to marry.”
The problem the king wanted the wizard to solve had become too hard for him. You must save wizard’s head by solving this problem.
Input
The first line of the input contains N – the number of king’s sons (1 <= N <= 2000). Next N lines for each of king’s sons contain the list of the girls he likes: first Ki – the number of those girls, and then Ki different integer numbers, ranging from 1 to N denoting the girls. The sum of all Ki does not exceed 200000.
The last line of the case contains the original list the wizard had made – N different integer numbers: for each son the number of the girl he would marry in compliance with this list. It is guaranteed that the list is correct, that is, each son likes the girl he must marry according to this list.
Output
Output N lines.For each king’s son first print Li – the number of different girls he likes and can marry so that after his marriage it is possible to marry each of the other king’s sons. After that print Li different integer numbers denoting those girls, in ascending order.
Sample Input
4
2 1 2
2 1 2
2 2 3
2 3 4
1 2 3 4
Sample Output
2 1 2
2 1 2
1 3
1 4
Hint
This problem has huge input and output data,use scanf() and printf() instead of cin and cout to read data to avoid time limit exceed.
題意
N個王子和N個公主,巫師已經為每個王子分配一個公主,但是皇帝想知道每個王子在保證每個王子都能夠匹配的前提下能娶的公主有多少?
思路
- 剛開始用二分圖暴力刪邊 -> TLE
- 強連通分量:王子向公主建邊,公主向和她匹配的王子建邊。這樣保證每一對王子和公主都在一個強聯通分量中,這是如果求得一個強聯通分量,在分量中的王子和公主都可以相互結婚而之前已經匹配的也能找到新的關系,這樣就符合題意
有兩個坑點:
- 輸出公主編號要升序(in ascending order)
- 同一個強連通分量其實也不能互相結婚,還有個前提是王子要喜歡才行,最后輸出的時候要判斷一下
scanf + printf + vector :12s
讀寫掛 + 鏈式向前星:500ms
總結
以上是生活随笔為你收集整理的POJ 1904 King's Quest(强连通分量)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Tarjan 强连通分量
- 下一篇: HDU 4685 Prince and