为什么不能用邻接矩阵呢?

P1551 亲戚

可以,但不建议。
by MushR @ 2023-10-06 23:00:13


有个大佬回复我了,举个反例:连了12,连了34,再连23的时候,程序不会把14连起来!!!
by csq_pig @ 2023-10-07 09:14:50


@[csq_pig](/user/1073710) 其实你可以手动连起来的
by Lemon_zqp @ 2023-12-03 15:24:11


不至于用邻接矩阵吧?我用并查集做的
by Dumbo @ 2023-12-07 19:19:21


```cpp //洛谷P1551-亲戚 #include <bits/stdc++.h> #define N 5050 using namespace std; int n, m, p, P; int fa[N];//每个点的父亲 /* 函数名:init 功能:初始化各个结点的父结点 参数:结点的总数 返回值:无 */ void init(int x) { for (int i = 1; i <= x; i++) fa[i] = i; } /* 函数名:find 功能:查找某个结点的根结点 参数:结点的编号 返回值:根结点的编号 */ int find(int x) { return (fa[x] == x ? x : find(fa[x])); } /* 函数名:join 功能:合并两个结点所在的树 参数:点x,点y 返回值:无 */ void join(int x, int y) { find(x) == find(y) ? x = x, y = y : fa[find(y)] = find(x);//中间其实没用 } int main() { cin >> n >> m >> P; p = P; init(n); for (int i = 1; i <= m; ++i) { int a, b; cin >> a >> b; join(a, b); } while (p--) { int x, y; cin >> x >> y; cout << (find(x) == find(y) ? "Yes\n" : "No\n"); } return 0; } ```
by Dumbo @ 2023-12-07 19:19:43


|