Mocha and Diana
time limit per test: 2 seconds
memory limit per test: 256 megabytes
Articles
This is the hard version of the problem. The only difference between the two versions is the constraint on . You can make hacks only if all versions of the problem are solved.
A forest is an undirected graph without cycles (not necessarily connected).
Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from to , and they would like to add edges to their forests such that:
- After adding edges, both of their graphs are still forests.
- They add the same edges. That is, if an edge is added to Mocha’s forest, then an edge is added to Diana’s forest, and vice versa.
Mocha and Diana want to know the maximum number of edges they can add, and which edges to add.
Input
The first line contains three integers , and — the number of nodes and the number of initial edges in Mocha’s forest and Diana’s forest.
Each of the next lines contains two integers and — the edges in Mocha’s forest.
Each of the next lines contains two integers and — the edges in Diana’s forest.
Output
The first line contains only one integer h, the maximum number of edges Mocha and Diana can add.
Each of the next lines contains two integers and — the edge you add each time.
If there are multiple correct answers, you can print any one of them.
Examples
input
1 | 3 2 2 |
output
1 | 0 |
input
1 | 5 3 2 |
output
1 | 1 |
input
1 | 8 1 2 |
output
1 | 5 |
Note
In the first example, we cannot add any edge.
In the second example, the initial forests are as follows.
We can add an edge .
Tutorial
找到在第一个森里中不与 连通,且在第二个森林中也不与 连通的点,与 相连。
重复上述操作直到没有点符合要求。
在新得到的两个森林中,所有的点要么与第一个森林的 连通,要么与第二个森林的 连通(与两个森林的 都连通的点除外)。
而上述两种点可以相互匹配加边,直到某个森林变成树为止。
Code
1 |
|