题解:P6908 [ICPC 2015 WF] Evolution in Parallel
先按长度排序,若
最小链覆盖等于最长反链,所以存在
于是直接贪心,维护两条链
复杂度
#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';
}