注意:允许转载,但转载请注明作者和出处
最重要:复习并查集以及图的最大深度
并查集的作用:
(1)将2个集合合并
(2)验证图是否为连通图,如果是,那就是只有一个集合;若不是,子集合个数cnt也能得到
(我记得拓扑排序也可以看一下图是否为连通图)
AcWing 836. 合并集合
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int fa[N];
int n, m;
int find(int x) // 找到x的祖先,并进行压缩存储即查询后树变成2层
{
if (x == fa[x]) return x;
else fa[x] = find(fa[x]);
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++) fa[i] = i;
while (m --)
{
char op;
int a, b;
cin >> op >> a >> b;
if (op == 'M')
{
if (find(a) != find(b)) fa[find(a)] = find(b);
}
else
{
if (find(a) == find(b)) puts("Yes");
else puts("No");
}
}
return 0;
}
AcWing 1498. 最深的根
题目
解析
涉及到两个重要问题:
(1)怎么看是连通图还是非连通图—>并查集
(2)若是连通图,怎么找到图的最大深度
邻接表---->我觉得很麻烦
邻接矩阵---->尝试中
答案
方法1:邻接矩阵写法
方法2:邻接表写法
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
const int N = 1e4 + 10, M = 2 * N;
int fa[N];
int h[N], e[M], ne[M], idx;
int n;
void add(int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
int find(int x)
{
if (x == fa[x]) return x;
else fa[x] = find(fa[x]);
}
// 找到图的最大深度
int dfs(int root, int father) // 用father标记dfs root时上一个经过的点,防止走回头路
{
int depth = 0;
for (int i = h[root]; i != -1; i = ne[i])
{
int j = e[i];
if (j == father) continue; // 这里体现father的作用:防止无向图dfs的时候又返回上一级搜索
depth = max(depth, dfs(j, root) + 1);
}
return depth;
}
int main()
{
cin >> n;
memset(h, -1, sizeof h);
for (int i = 1; i <= n; i ++) fa[i] = i;
int cnt = n; // 统计集合个数,初始为n,两两合一就cnt--
// 若cnt最后减为0,则表示这n个结点都在一个集合里,即连通图
// 反之,这不是一个连通图
for (int i = 0; i < n - 1; i ++)
{
int a, b;
cin >> a >> b;
add(a, b), add(b, a); // 树是无向图
// 若a和b的祖先不一样,则二者在不同的集合里
if (find(a) != find(b))
{
cnt --;
fa[find(a)] = find(b);
}
}
// cout << cnt << endl;
if (cnt > 1) printf("Error: %d components\n", cnt);
else
{
vector<int> nodes;
int max_depth = -1;
for (int i = 1; i <= n; i ++)
{
int depth = dfs(i, -1);
// cout << depth << endl;
if (depth > max_depth)
{
max_depth = depth;
nodes.clear();
nodes.push_back(i);
}
else if (depth == max_depth)
{
nodes.push_back(i);
}
}
for (auto no : nodes) cout << no << endl;
}
return 0;
}