若干个树, q个询问
操作1:求出某一棵树的直径;
操作2:合并两个没合并的树(若合并了则省略),合并的树中树的直径最小。
见画板:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 3e5 + 10, M = 2 * N, inf = 0x3f3f3f3f;
int n, m, q;
int h[N], e[M], ne[M], idx;
int p[N], pd[N];
int id, d;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
int find(int x)
{
return x == p[x] ? p[x] : p[x] = find(p[x]);
}
void dfs(int u, int fa, int sum)
{
if(sum > d)
{
d = sum;
id = u;
}
for(int i = h[u]; ~i; i = ne[i])
{
int son = e[i];
if(son == fa) continue;
dfs(son, u, sum + 1);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
memset(h, -1, sizeof h);
for(int i = 0; i < N; i ++) p[i] = i, pd[i] = 0;
cin >> n >> m >> q;
for(int i = 0; i < m; i ++)
{
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
int pa = find(a), pb = find(b);
if(pa != pb) p[pa] = pb;
}
vector<int> root;
for(int i = 1; i <= n; i ++)
{
if(i == p[i]) root.push_back(i);
}
for(int i = 0; i < root.size(); i ++)
{
id = root[i], d = 0;
dfs(root[i], -1, 0);
dfs(id, -1, 0);
pd[root[i]] = d;
}
while(q --)
{
int c;
cin >> c;
if(c == 1)
{
int x;
cin >> x;
cout << pd[find(x)] << '\n';
}
else
{
int a, b;
cin >> a >> b;
int pa = find(a), pb = find(b);
if(pa != pb)
{
int tmp = (pd[pa] + 1) / 2 + (pd[pb] + 1) / 2 + 1;
p[pa] = pb;
pd[pb] = max(tmp, max(pd[pa], pd[pb]));
}
}
}
return 0;
}