简单并查集, 搞出一棵树即可
1 class Solution { 2 public: 3 int fi(int x, vector<int>& fa) { 4 return x == fa[x] ? x : fa[x] = fi(fa[x], fa); 5 } 6 vector<int> findRedundantConnection(vector<vector<int>>& edges) { 7 int n = edges.size(); 8 vector<int> ans; 9 vector<int> fa(n + 1, 0); 10 for (int i = 0; i <= n; i++) fa[i] = i; 11 for (auto p : edges) { 12 int x = fi(p[0], fa), y = fi(p[1], fa); 13 if (x != y) { 14 fa[x] = y; 15 } else { 16 ans = p; 17 break; 18 } 19 } 20 return ans; 21 } 22 };
A和B, P为A,B的公因子, 连接P和A即可, 最后再判断, 用并查集处理即可
1 class Solution { 2 public: 3 int fi(int x, vector<int>& fa) { 4 return x == fa[x] ? x : fa[x] = fi(fa[x], fa); 5 } 6 vector<bool> areConnected(int n, int threshold, vector<vector<int>>& queries) { 7 vector<bool> ans; 8 vector<int> fa(n + 1, 0); 9 for (int i = 1; i <= n; i++) fa[i] = i; 10 for (int i = threshold + 1; i <= n; i++) { 11 for (int j = 2 * i; j <= n; j += i) { 12 int fx = fi(i, fa), fy = fi(j, fa); 13 if (fx != fy) fa[fx] = fy; 14 } 15 } 16 int m = queries.size(); 17 for (int i = 0; i < m; i++) { 18 int fx = fi(queries[i][0], fa), fy = fi(queries[i][1], fa); 19 ans.push_back(fx == fy); 20 } 21 return ans; 22 } 23 };