Explain concept lexicographic-greedy-construction

This commit is contained in:
usaco site
2026-10-20 18:21:40 +00:00
parent 5772093741
commit 1fd2bd7517
3 changed files with 229 additions and 0 deletions
@@ -0,0 +1,21 @@
// concept: lexicographic-greedy-construction
// Lexicographically largest subsequence of exactly k elements (k <= n). O(n). 0-based.
// Works for string or vector<T>. For the smallest, flip `<` to `>`.
template<class S> S largestSubseq(const S& s, int k) {
S st; int n = s.size();
for (int i = 0; i < n; i++) {
// pop if top is smaller and we can still reach length k without it
while (!st.empty() && st.back() < s[i] && (int)st.size() - 1 + (n - i) >= k)
st.pop_back();
if ((int)st.size() < k) st.push_back(s[i]);
}
return st;
}
// Largest string obtainable by concatenating all pieces in some order. O(n log n * len).
string largestConcat(vector<string> v) {
sort(v.begin(), v.end(), [](const string& a, const string& b) { return a + b > b + a; });
string r;
for (auto& x : v) r += x;
return r;
}