跳到正文

题解

题解:CF1137B Camp Schedule

DerRichter约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年6月7日
收录
2025年12月12日
更新
2026年10月10日
篇幅
约 3 分钟
题目
CF1137B

版本

  1. v1当前

题意

给定两个 01 字符串 s,ts, t,重新排列 ss,使得 tt 在 ss 中作为子串的出现次数最多。

思路

首先,一定是拿 tt 不断地拼凑,不够凑了就输出剩下的。不难想到最长公共前后缀(border),每次往上拼接一个 tt,要从 ∣t∣−border∣t∣|t| - border_{|t|} 开始拼,这样就可以使得每次拼接后的字符串长度变短,不会使总出现次数变少。border 部分按照 kmp 的求法求即可。

代码

思路虽简单,实现上还是有些细节的。详见代码。

C++
#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int MAXN = 5e5 + 10;

string s, t;
int fail[MAXN], cnt[MAXN][2];

int main() {
  ios::sync_with_stdio(0), cin.tie(0);
  cin >> s >> t;
  int n = s.size(), m = t.size();
  s = '#' + s; t = '#' + t;
  pair<int, int> res = {0, 0};
  cnt[1][t[1] - '0'] = 1;
  for (int i = 2, j = 0; i <= m; i++) {
    for (; j && t[i] != t[j + 1]; j = fail[j]);
    j += t[i] == t[j + 1];
    fail[i] = j;
    for (int _ : {0, 1}) {
      cnt[i][_] = cnt[i - 1][_] + (t[i] - '0' == _);
    }
  }
  for (int i = 1; i <= n; i++) {
    res.first += s[i] == '0';
    res.second += s[i] == '1';
  }
  string k = t.substr(1);
  if (res.first < cnt[m][0] || res.second < cnt[m][1] || m > n) {
    cout << s.substr(1);
    return 0;
  }
  res.first -= cnt[m][0], res.second -= cnt[m][1];
  while (1) {
    if (res.first < cnt[m][0] - cnt[fail[m]][0] || res.second < cnt[m][1] - cnt[fail[m]][1]) {
      break;
    }
    res.first -= cnt[m][0] - cnt[fail[m]][0];
    res.second -= cnt[m][1] - cnt[fail[m]][1];
    k += t.substr(fail[m] + 1);
  }
  for (int i = 1; i <= res.first; i++) k += '0';
  for (int i = 1; i <= res.second; i++) k += '1';
  cout << k;
  return 0;
}
原文