1790D: Matryoshkas ⧉
The task here is to find the minimum number of valid sets into which we can partition an array of integers. A valid set is a set of consecutive integers, e.g. 3 or 6. We can accomplish this in O(nlogn) time by first sorting the integers, and then using a map to collapse (or nest, to fit the "nesting doll" narrative of the problem) each integer onto a previous occurence of that integers predecessor.
_41#include <iostream>_41#include <algorithm>_41#include <vector>_41#include <map>_41_41void solve() {_41 int n;_41 std::cin >> n;_41 std::vector<int> a (n);_41 for (auto& x : a) std::cin >> x;_41 std::sort(a.begin(), a.end());_41_41 // we nest whenever possible_41 std::map<int,int> dolls;_41 for (auto d : a) {_41 // if we can nest, we do_41 auto smaller = dolls.find(d-1);_41 if (smaller != dolls.end() && smaller->second != 0) {_41 smaller->second--;_41 }_41_41 dolls[d]++;_41 }_41_41 int sets = 0;_41 for (auto [_, cnt] : dolls) {_41 sets += cnt;_41 }_41_41 std::cout << sets << '\n';_41}_41_41_41int main() {_41 int t;_41 std::cin >> t;_41 for (int tc = 1; tc <= t; ++tc) {_41 solve();_41 }_41 return 0;_41}
If you found this solution helpful, consider leaving a star!