atcoder#ABC302F. [ABC302F] Merge Set
[ABC302F] Merge Set
Score : points
Problem Statement
On a blackboard, there are sets consisting of integers between and . Here, $S_i = \lbrace S_{i,1},S_{i,2},\dots,S_{i,A_i} \rbrace$.
You may perform the following operation any number of times (possibly zero):
- choose two sets and with at least one common element. Erase them from the blackboard, and write on the blackboard instead.
Here, denotes the set consisting of the elements contained in at least one of and .
Determine if one can obtain a set containing both and . If it is possible, find the minimum number of operations required to obtain it.
Constraints
- All values in the input are integers.
Input
The input is given from Standard Input in the following format:
Output
If one can obtain a set containing both and , print the minimum number of operations required to obtain it; if it is impossible, print -1
instead.
3 5
2
1 2
2
2 3
3
3 4 5
2
First, choose and remove and to obtain .
Then, choose and remove and to obtain .
Thus, one can obtain a set containing both and with two operations. Since one cannot achieve the objective by performing the operation only once, the answer is .
1 2
2
1 2
0
already contains both and , so the minimum number of operations required is .
3 5
2
1 3
2
2 4
3
2 4 5
-1
4 8
3
1 3 5
2
1 2
3
2 4 7
4
4 6 7 8
2