思路
把毒株看成点,从一个毒株变异为另一个毒株,则在它们间连一条边。由于源头只有一个,因此图全连通(所有点都和源头连通)。又因为没有环,因此图是树。问题是求树的深度,显然,树的深度等于最大子树深度加一,时间复杂度 $O(n)$。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 10010;
int n;
bool has_father[N];
vector<int> son[N];
vector<int> dfs(int u) {
sort(son[u].begin(), son[u].end());
vector<int> res;
for (auto s: son[u]) {
auto lk = dfs(s);
if (res.size() < lk.size())
res = lk;
}
res.push_back(u);
return res;
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
int m; cin >> m;
while (m--) {
int s; cin >> s;
has_father[s] = true;
son[i].push_back(s);
}
}
int root = 0;
while (has_father[root]) root++;
auto res = dfs(root);
cout << res.size() << endl;
for (auto it = res.rbegin(); it != res.rend(); it++)
cout << *it << " ";
cout << endl;
return 0;
}