Apollo is playing an interesting computer game. There are n rounds in the game.
At each round, the computer will give Apollo two integers ai and bi, and Apollo can do exactly one of the following three actions.
Apollo can do nothing.
If integer ai has not been selected in all previous rounds, Apollo can select integer ai.
If integer bi has not been selected in all previous rounds, Apollo can select integer bi.
Apollo has cracked the game, and he has known all the candidate numbers of each round before the game starts. Now he wants to know the maximum number of integers he can select with the optimal strategy.
I believe it would be very simple question for you, please help Apollo solve this question.
输入描述
The first line is an integer T(1⩽T⩽10), which is the number of test cases.
Each test case begins with a line containing a positive integer n(1⩽n⩽105), indicating the number of rounds in this game.
Then n lines follow. The i-th line contains two integers ai and bi(1⩽ai⩽109,1⩽bi⩽109), indicating that two integers of the i-th round.
输出描述
For each test case, output one line containing Case#x:y, where x is the test case number and y is the answer.
示例1
输入
1 2 3 4 5 6 7 8 9 10 11 12 13 14
2 6 1 2 2 3 3 4 1 4 1 3 2 4 5 1 2 1 2 1 3 2 3 5 6
输出
1 2
Case #1: 4 Case #2: 4
分析
考虑用网络最大流解决。 ai 和 bi 组成一个二元组,每个二元组至多只能选取其中的一个数字;为了体现这种限制,可以设置 n 个点,编号为 1∼n,第 i 个点有两条边分别连向二元组 (ai,bi) 的两个数,容量为 1。每个数字至多被选取一次,将所因此要将所有二元组的数据离散化后,得到 cnt 个不同的数字,设为 cnt 个点,编号为 n+1∼n+cnt;接着,将代表二元组的 n 个点向对应的两个数连边。源点向 n 个表示二元组的点连边,容量为 1;cnt 个表示数据的点向 汇点连边,容量为 1。
按照上述方式建图,满足:每次至多选 (ai,bi) 中的一个数字,已选的数字不会再选,网络最大流即为答案。由于边的容量为 1,因此当一条边在增广路上时,这条边的容量就被修改为 0;且按照图的结构,残量网络的层数较少;基于以上,虽然 Dinic 算法的最坏时间复杂度为 O(n2m)(n 为点数,m 为边数),但是远远达不到这一上限,在 2s 的时限内是可以通过的。