boolassertRemove(vector<vector<int>>&edges, int idx){ // 建立并查集的过程中检查删除该边后是否还有环 for (int i = 0; i < n; ++ i) { // 遍历边集 if (i == idx) continue; // 排除该边 if (find(edges[i][0]) == find(edges[i][1])) returnfalse; p[find(edges[i][0])] = find(edges[i][1]); } returntrue; }
vector<int> remove(vector<vector<int>> &edges) { for (int i = 0; i < n; ++ i) { if (find(edges[i][0]) == find(edges[i][1])) return edges[i]; p[find(edges[i][0])] = find(edges[i][1]); } return {}; } vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) { n = size(edges); vector<int> vec; for (int i = 1; i <= n; ++ i) p[i] = i;// 初始化并查集
// 查看是否有入度为2的点 for (int i = 0; i < n; ++ i) ++ indegree[edges[i][1]]; for (int i = n - 1; i >= 0; -- i) { // 逆序是有多个答案时删除较后的答案 if (indegree[edges[i][1]]==2) vec.push_back(i);//保存节点对 }
// 如果有入度为2的点,则只需删除其中一条 if (vec.size()) { if (assertRemove(edges, vec[0])) return edges[vec[0]]; else return edges[vec[1]]; }