UPC朋友——并查集

题目描述

有一个城镇,住着n个市民。已知一些人互相为朋友。引用一个名人的话说,朋友的朋友也是朋友。意思是说如果A和B是朋友,C和B是朋友,则A和C是朋友.你的任务是数出最大朋友组的人数。

输入

输入第一行由N,M组成,N是市民的个数(1<=n<=30000),m是朋友对的个数(0<=m<=500000)。下面的m行每一行由两个数A和B组成(1<=A,B<=N,A<>B)表示A和B是朋友。注意给的朋友对可能会有重复。

输出

输出仅有一行包含一个整数,表示要求的最大朋友组的人数。

样例输入

10 12
1 2
3 1
3 4
5 4
3 5
4 6
5 2
2 1
7 10
1 2
9 10
8 9

样例输出

6

本题是较简单的并查集,A和B是朋友,B和C是朋友,则A和C是朋友
如果他们两个共同祖先,那么这两个人就是好朋友,给如果不是就将这两个人结为好朋友,并规定谁是谁的祖先(形式上的)。

#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector,fast-math")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize (2)
#pragma G++ optimize (2)
#include <bits/stdc++.h>
#include <algorithm>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define wuyt main
typedef long long ll;
#define HEAP(...) priority_queue<__VA_ARGS__ >
#define heap(...) priority_queue<__VA_ARGS__,vector<__VA_ARGS__ >,greater<__VA_ARGS__ > >
template<class T> inline T min(T &x,const T &y){return x>y?y:x;}
template<class T> inline T max(T &x,const T &y){return x<y?y:x;}
//#define getchar()(p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
//char buf[(1 << 21) + 1], *p1 = buf, *p2 = buf;
ll read(){ll c = getchar(),Nig = 1,x = 0;while(!isdigit(c) && c!='-')c = getchar();
if(c == '-')Nig = -1,c = getchar();
while(isdigit(c))x = ((x<<1) + (x<<3)) + (c^'0'),c = getchar();
return Nig*x;}
#define read read()
const ll inf = 1e15;
const int maxn = 2e5 + 7;
const int mod = 1e9 + 7;
#define start int wuyt()
#define end return 0
int num[maxn],n,m;
int father[maxn];
int ans;
int findfather(int x){
    if(father[x]==x) return x;
    else return father[x]=findfather(father[x]);
}
start{
    n=read,m=read;
    for(int i=1;i<=n;i++) father[i]=i;
    for(int i=1;i<=m;i++)
    {
        int x=read,y=read;
        int judge1=findfather(x);
        int judge2=findfather(y);
        if(judge1!=judge2) father[judge2]=judge1;
    }
    for(int i=1;i<=n;i++){
        num[findfather(i)]++;
    }
    ans=0;
    for(int i=1;i<=n;i++)
    {
        if(ans<num[i]) ans=num[i];
    }
    cout<<ans;
    end;
}
原文地址:https://www.cnblogs.com/PushyTao/p/13144207.html