22 lines
869 B
C++
22 lines
869 B
C++
// 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;
|
|
}
|