classSolution { public: intmaximumInvitations(vector<int>& favorite){ int n = favorite.size(); int ans = 0, ans2 = 0; vector<int> cnt(n), vis(n); vector<vector<int>> G(n); for (int i = 0; i < favorite.size(); i++) { cnt[favorite[i]]++; G[i].push_back(favorite[i]); G[favorite[i]].push_back(i); } vector<int> tmp(n); function<int(int, int)> get = [&](int u, int u2) { int d = 1; tmp[u] = 1; for (int v : G[u]) { if (v != u2 && !tmp[v]) { d = max(d, get(v, u2) + 1); } } return d; }; int two = 0; for (int i = 0; i < n; i++) { if (!cnt[i]) { vector<int> loop; int j = i; for (int j = i; ; j = favorite[j]) { loop.push_back(j); if (!vis[j]) { vis[j] = 1; } elseif (vis[j] == 1) { int sz = loop.size(); for (int i = 0; i < sz; i++) { if (i > 0) cnt[loop[i]]--; vis[loop[i]] = 2; if (j == loop[i] && i != sz - 1) { int x = i, y = sz - x - 1; if (y == 2) { int cur = get(j, loop[i + 1]) + get(loop[i + 1], j); ans2 = max(ans2, cur); two += cur; } else { ans = max(ans, y); } } } break; } elseif (vis[j] == 2) { int sz = loop.size(); for (int i = 1; i < sz; i++) { cnt[loop[i]]--; } break; } } } } memset(vis.data(), 0, n << 2); for (int i = 0; i < n; i++) { while (cnt[i]) { vector<int> loop; int j = i; for (int j = i; ; j = favorite[j]) { loop.push_back(j); if (!vis[j]) { vis[j] = 1; } else { int sz = loop.size(); if (sz == 3) { two += 2; ans2 = max(ans2, 2); } else { ans = max(ans, sz - 1); } for (int i = 0; i < sz; i++) { vis[loop[i]] = 0; if (i > 0) cnt[loop[i]]--; } break; } } } } ans = max(ans, two); return ans; } };
classSolution { public: intmaximumInvitations(vector<int> &favorite){ int n = favorite.size(); vector<int> deg(n); for (int f: favorite) { deg[f]++; // 统计基环树每个节点的入度 }
vector<vector<int>> rg(n); // 反图 queue<int> q; for (int i = 0; i < n; i++) { if (deg[i] == 0) { q.push(i); } } while (!q.empty()) { // 拓扑排序,剪掉图上所有树枝 int x = q.front(); q.pop(); int y = favorite[x]; // x 只有一条出边 rg[y].push_back(x); if (--deg[y] == 0) { q.push(y); } }