跳到正文

题解

题解:P6908 [ICPC 2015 WF] Evolution in Parallel

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

文章信息

发布
2026年10月28日
收录
2026年10月29日
更新
2026年11月14日
篇幅
约 3 分钟
题目
P6908

版本

  1. v1当前

先按长度排序,若 i<ji < j,sis_i 是 sjs_j 的子序列则连 i→ji\to j 的边,题目相当于求这个图的最小链覆盖。

最小链覆盖等于最长反链,所以存在 i<j<ki < j <k,si,sj,sks_i, s_j, s_k 互不为子序列则无解。

于是直接贪心,维护两条链 p,qp, q,和一条延迟决策的链 rr。枚举 sis_i,若 sis_i 只能接到 p,qp, q 中一条上,就直接接;如果两条都可以,考虑接到 rr 上延迟决策。如果不能接到 rr 上,那么 sis_i 和 rr 必然在不同的链,随便接 p,qp, q 即可;如果两条都不能接,那么此时 si,p,qs_i, p, q 构成了长度为 33 的反链,无解。

复杂度 O(n∣s∣)O(n|s|)。

C++
#include <bits/stdc++.h>
using namespace std;
constexpr int N = 5009;
int n;
string s[N];
bool cmp(const string &a, const string &b) {
  if (a.size() > b.size()) return false;
  for (int i = 0, j = 0; i < a.size(); ++i, ++j) {
    while (j < b.size() && b[j] != a[i]) ++j;
    if (j == b.size()) return false;
  }
  return true;
}
signed main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  cin >> n >> s[n + 1];
  for (int i = 1; i <= n; ++i) {
    cin >> s[i];
    if (!cmp(s[i], s[n + 1])) return cout << "impossible", 0;
  }
  sort(s + 1, s + n + 1, [&](const string &ls, const string &rs) -> bool { return ls.size() < rs.size(); });
  vector<string> p[2], r;
  for (int i = 1; i <= n; ++i) {
    int t = 0;
    if (p[0].empty() || cmp(p[0].back(), s[i])) t += 1;
    if (p[1].empty() || cmp(p[1].back(), s[i])) t += 2;
    if (!t) return cout << "impossible", 0;
    if (t == 3) {
      if (r.empty() || cmp(r.back(), s[i])) {
        r.push_back(s[i]);
        continue;
      }
      t = 1;
    }
    p[t - 1].push_back(s[i]);
    for (auto &j : r) p[(t - 1) ^ 1].push_back(j);
    r.clear();
  }
  for (auto &j : r) p[0].push_back(j);
  cout << p[0].size() << ' ' << p[1].size() << '\n';
  for (auto &i : p[0]) cout << i << '\n';
  for (auto &i : p[1]) cout << i << '\n';
}
原文