[CF] C. Brutality - Educational Codeforces Round 59 (Rated for Div. 2)

https://codeforces.com/contest/1107/problem/C

题目大意

给出 $n$ 长的小写字符的串 $S$ 和数组 $a$。给出某个 $k$,需要删掉字符串中的某些字符,使得最终串连续的相同字符个数不会超过 $k$。问最后保留下的字符的下标对应的 $a_i$ 的和最大是多少。

$1 \le k \le n \le 2 \times 10^5$。$1 \le a_i \le 10^9$。

简要题解

观察:

  1. $a_i$ 都是正的,因此不会有能留下更多的,不如其某个子集好的情况。
  2. 对于两个 $c$ 字符中间的其他字符,一定是保留更好,因为删掉可能反而使更多的 $c$ 连起来。

于是每个相同字符的段可以分开处理,保留尽量多的,权值大的字符即可。

复杂度

$T$:$O(n \log n)$

$S$:$O(n)$

代码实现

#include <bits/stdc++.h>
using namespace std;

int io_=[](){ ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();

using LL = long long;
using ULL = unsigned long long;
using LD = long double;
using PII = pair<int, int>;
using VI = vector<int>;
using MII = map<int, int>;

template<typename T> void cmin(T &x,const T &y) { if(y<x) x=y; }
template<typename T> void cmax(T &x,const T &y) { if(x<y) x=y; }
template<typename T> bool ckmin(T &x,const T &y) { 
    return y<x ? (x=y, true) : false; }
template<typename T> bool ckmax(T &x,const T &y) { 
    return x<y ? (x=y, true) : false; }
template<typename T> void cmin(T &x,T &y,const T &z) {// x<=y<=z 
    if(z<x) { y=x; x=z; } else if(z<y) y=z; }
template<typename T> void cmax(T &x,T &y,const T &z) {// x>=y>=z
    if(x<z) { y=x; x=z; } else if(y<z) y=z; }

// mt19937 rnd(chrono::system_clock::now().time_since_epoch().count());
// mt19937_64 rnd_64(chrono::system_clock::now().time_since_epoch().count());

/*
---------1---------2---------3---------4---------5---------6---------7---------
1234567890123456789012345678901234567890123456789012345678901234567890123456789
*/

void solve() {
  int n, k; cin >> n >> k;
  vector<int> a(n);
  for (int& i : a) cin >> i;
  string s; cin >> s;

  vector<int> b;
  
  LL ans = 0;
  for (int i = 0; i < n; ) {
    int j = i;
    b.clear();
    while (j < n && s[j] == s[i]) {
      b.push_back(a[j]);
      j++;
    }

    int cnt = min(j - i, k);
    sort(b.rbegin(), b.rend());
    for (int k = 0; k < cnt; k++) {
      ans += b[k];
    }

    i = j;
  }
  cout << ans << '\n';
}

int main() {
  int t = 1; 
  // cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
Prev: [CF] D. Compression - Educational Codeforces Round 59 (Rated for Div. 2)
Next: [CF] D. Eating - Codeforces Round 1005 (Div. 2)