0
点赞
收藏
分享

微信扫一扫

HDU——1856 More is better(并查集模板题)

原题链接:​​http://acm.hdu.edu.cn/showproblem.php?pid=1856​​

HDU——1856 More is better(并查集模板题)_并查集
测试样例:

样本输入
4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8


样本输出
4
2

题意: 你会有1000万个男孩,你也会有这些男孩之间的关系,你想要留住最多的男孩(留下的男孩直接或间接是朋友关系),问最多是多少?

解题思路: 此题是一道并查集模板题,我们先要合并成多个集合,再找出集合中最大的值即可,这个过程中我们要用nums数组来存储每个状态的男孩数,最后遍历一遍nums数组寻得最大值即可。同时也要注意多个优化:在输入过程中找出最大编号用于最后的nums数组遍历,利用路径压缩减小合并时间,利用cin cout的输入输出优化语句或者改用scanf和printf输入输出,对n=0是直接特判

AC代码:

/*
*
*
*/
#include<bits/stdc++.h> //POJ不支持

#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pair

using namespace std;

const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 1e7+2;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//
int father[maxn],nums[maxn];//根节点数目,和存储每个点当前扩展到最大朋友数。
int maxx;//保留最大男孩数。
//查找根节点操作。
void init(){
rep(i,1,maxn)
father[i]=i,nums[i]=1;
}
int Find(int x){
int r=x;
while(r!=father[r])
r=father[r];
int i=x,j;
while(father[i]!=r){
j=father[i];
father[i]=r;
i=j;
}
return r;
}
//合并操作。
void Merge(int x,int y){
int fx=Find(x),fy=Find(y);
if(fx!=fy){
father[fx]=fy;
nums[fy]+=nums[fx];//合并之后自然要加方案数。
}
}
int main(){
//freopen("in.txt", "r", stdin);//提交的时候要注释掉
IOS;
int n;//关系数。
int u,v,temp;//临时变量。
while(cin>>n){
temp=0;
if(n==0){
cout<<"1"<<endl;
continue;
}
init();
while(n--){
cin>>u>>v;
temp=max(temp,max(u,v));
Merge(u,v);
}
maxx=0;
rep(i,1,temp){
if(nums[i]>maxx)
maxx=nums[i];
}
cout<<maxx<<endl;
}
return 0;
}


举报

相关推荐

0 条评论