diff --git a/utilities/sort_maximal.hpp b/utilities/sort_maximal.hpp new file mode 100644 index 00000000..55f03f5d --- /dev/null +++ b/utilities/sort_maximal.hpp @@ -0,0 +1,18 @@ +#pragma once +#include +#include +#include + +// Sort segments and erase not maximal ones +// {{0, 2}, {1, 5}, {3, 4}} => {{0, 2}, {1, 5}} +// {{1, 3}, {0, 1}, {1, 3}} => {{0, 1}, {1, 3}} // remove duplicates +// Verified: abc254g https://atcoder.jp/contests/abc254/tasks/abc254_g +template std::vector> sort_maximal(std::vector> ranges) { + std::sort(ranges.begin(), ranges.end()); + std::vector> ret; + for (const auto &p : ranges) { + if (!ret.empty() and ret.back().first == p.first) ret.pop_back(); + if (ret.empty() or ret.back().second < p.second) ret.push_back(p); + } + return ret; +} diff --git a/utilities/sort_maximal.md b/utilities/sort_maximal.md new file mode 100644 index 00000000..bd9540ba --- /dev/null +++ b/utilities/sort_maximal.md @@ -0,0 +1,15 @@ +--- +title: 区間たちをソートし極大でないものを消去 +documentation_of: ./sort_maximal.hpp +--- + +## 使用方法 + +```cpp +vector> segs; +segs = sort_maximal(segs); +``` + +## 問題例 + +- [AtCoder Beginner Contest 254 G - Elevators](https://atcoder.jp/contests/abc254/tasks/abc254_g)