Magical Bags
Limits: 4 sec., 512 MiB
In the magical land of Far Far Away, Shrek and his friends stumbled upon a peculiar puzzle hidden deep within the Enchanted Forest. Donkey, who was always on the lookout for new adventures, discovered \(n\) mystical bags, each containing a unique collection of magical objects. Each object held a distinct magic power, represented by an integer.
As usual, Donkey couldn’t resist turning it into a game. "Hey, Shrek, I dare you to make every pair of bags good while keeping the least number of magical objects in total," he challenged. Shrek, slightly annoyed but up for the task, asked, "And what do you mean by good, Donkey?".
"A pair of bags is good if you can choose one magical object from one bag that’s stronger than one in the other bag, and another that’s weaker. That way, the magic stays balanced!" Donkey explained, grinning mischievously.
More formally, a pair of bags \(A\) and \(B\) is called good if there exist elements \(a_1 \in A\) and \(b_1 \in B\) such that \(a_1 < b_1\) and there also exist elements \(a_2 \in A\) and \(b_2 \in B\) such that \(a_2 > b_2\). It’s possible that \(a_1 = a_2\) or \(b_1 = b_2\).
Now Shrek’s challenge is to figure out: What is the minimum number of magical objects that must remain in all the bags so that every pair of bags stays good if it was originally good? Of course, each bag must hold onto at least one magical object, just to keep the magic alive.
Input
The first line contains a single integer \(n\) — number of bags.
Next \(n\) lines contain a single integer \(k_i\) — number of magical object in the \(i\)-th bag, followed by \(k_i\) integers \(a_{ij}\) — magic power of the objects in \(i\)-th bag.
Output
Print a single number — minimum total number of magical objects remaining in the bags.
Constraints
\(2 \le n \le 2 \cdot 10^5\),
\(1 \le k_i\),
\(\sum k_i \le 5 \cdot 10^5\),
\(1 \le a_{ij} \le 10^9\),
all \(a_{ij}\) are distinct, even the objects in different bags can’t have the same magic power.
Samples
Input (stdin) | Output (stdout) |
---|---|
4 3 4 7 10 2 1 9 4 11 2 8 14 3 6 12 13 | 7 |
Input (stdin) | Output (stdout) |
---|---|
4 1 1 1 2 1 3 1 4 | 4 |
Notes
In the first example, each pair of bags is good initially. One of the possible solutions:
Object with power 7.
Objects with powers 1 and 9.
Objects with powers 2 and 8.
Objects with powers 6 and 12.
In the second example no pairs of bags are good, but still one object should remain in each bag.
Submit a solution
Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
---|
Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
---|