2021团体程序设计天梯赛 L2-2 病毒溯源
思路:
dfs+优化
Tip:
得到答案后回溯可得到路径
#include <bits/stdc++.h> using namespace std; const int maxn = 10000 + 5; int father[maxn]; bool isp[maxn]; int ceng[maxn]; int maxceng = 0; vector<int> vmaxn; int dfs(int now) { if (ceng[now]) return ceng[now]; if (father[now] == now) { ceng[now] = 1; return 1; } ceng[now] = dfs(father[now]) + 1; return ceng[now]; } int main() { int n; cin >> n; for (int i = 0; i < n; i++) father[i] = i; for (int i = 0; i < n; i++) { int t; cin >> t; if (t == 0) isp[i] = true; for (int j = 1; j <= t; j++) { int x; cin >> x; father[x] = i; } } for (int i = 0; i < n; i++) { if (isp[i]) { ceng[i] = dfs(i); if (ceng[i] > maxceng) { maxceng = ceng[i]; vmaxn.clear(); int now = i; while (father[now] != now) { vmaxn.push_back(now); now = father[now]; } vmaxn.push_back(now); } else if (ceng[i] == maxceng) { vector<int> vnow; int now = i; while (father[now] != now) { vnow.push_back(now); now = father[now]; } vnow.push_back(now); bool flag = false; for (int k = maxceng - 1; k >= 0; k--) { if (vnow[k] < vmaxn[k]) { flag = true; break; } else if (vnow[k] > vmaxn[k]) { flag = false; break; } } if (flag) vmaxn = vnow; } } } cout << maxceng << endl; bool first = true; for (int k = maxceng - 1; k >= 0; k--) { if (first) { first = false; cout << vmaxn[k]; } else cout << " " << vmaxn[k]; } return 0; }