找最大连通分量,没有一对pairs就输出1。
(19年5月10日)他要求 要么 选出来的人都互相是朋友(直接或间接),要么 就只选一个人。问你最多能选多少人。
(After Mr Wang 's selection) any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left.
题意就是给一些对(可能给0对,这样每个人都是孤立的)直接朋友关系,求形成的最大的朋友圈的人数。
用并查集(根记录个数的负值)一边输入一边union,不断更新答案就完事了。
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
const int MAXN = 1e7 + 2;
int pre[MAXN];
int pairs;
int opt;
int f(int x)
{
int f0 = x, f1 = x;
for (; pre[f0] > 0;)
f0 = pre[f0];
for (; pre[f1] > 0;)
{
int t = f1;
f1 = pre[f1];
pre[t] = f0;
}
return f0;
}
void u(int a, int b)
{
int f1 = f(a);
int f2 = f(b);
if (f1 != f2)
{
if (pre[f1] <= pre[f2])
{
pre[f1] += pre[f2];
if (-pre[f1] > opt) opt = -pre[f1];
pre[f2] = f1;
}
else
{
pre[f2] += pre[f1];
if (-pre[f2] > opt) opt = -pre[f2];
pre[f1] = f2;
}
}
}
int main()
{
for (; ~scanf("%d", &pairs);)
{
int a, b;
memset(pre, -1, sizeof pre);
opt = 1; // n=0 时直接输出 1 又是这种坑点,服
for (int i = 0; i < pairs; i++)
{
scanf("%d%d", &a, &b);
u(a, b);
}
printf("%d\n", opt);
}
return 0;
}

本文介绍了一种使用并查集解决寻找最大朋友圈人数的问题。通过输入一系列朋友关系对,并实时更新并查集来确定最大的互为朋友的群体规模。
331

被折叠的 条评论
为什么被折叠?



