银河英雄传说
作者:互联网
P1196 [NOI2002] 银河英雄传说 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
- front数组代表每个点到队头的距离,x,y之间隔了几个舰队答案为abs(front[x]-front[y])-1;
- nums数组代表当前队伍一共有几个舰队
- 合并操作只需要将x,y对应祖先也就是fa(x),fa(y)也就是它们各自的队头front nums 数组修改再合并parent
- front数组在fa里更新,先递归进去处理了离队首进的结点的front值,再将当前的x的front值加上他父亲(不是祖先)的front值,最后再路径压缩(把父亲命为祖先)
// https://www.luogu.com.cn/problem/solution/P1196
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define MAX 10000001
int n, ii, jj, parent[MAX], cnt, front[MAX], nums[MAX], fx, fy;
char flag;
int fa(int x)
{
if (x == parent[x])
return x;
int ffx = fa(parent[x]);
front[x] += front[parent[x]];
parent[x] = ffx;
return ffx;
}
void M()
{
front[fx] += nums[fy];
parent[fx] = fy;
nums[fy] += nums[fx];
nums[fx] = 0;
}
void C()
{
if (fx != fy)
printf("-1\n");
else
printf("%d\n", abs(front[ii] - front[jj]) - 1);
}
void init()
{
for (int i = 1; i <= n; i++)
{
parent[i] = i;
front[i] = 0;
nums[i] = 1;
}
}
int main()
{
cin >> n;
init();
for (int i = 1; i <= n; i++)
{
cin >> flag >> ii >> jj;
fx = fa(ii), fy = fa(jj);
if (flag == 'M')
M();
else
C();
}
}
标签:parent,nums,fx,fy,fa,银河,英雄,传说,front 来源: https://www.cnblogs.com/Wang-Xianyi/p/16559806.html