HDU1213 How Many Tables (并查集)
2024-09-24 14:13:34
题目大意:
有一个人要过生日了,请他的朋友来吃饭,但是他的朋友互相认识的才能坐在一起,朋友的编号从1 ~ n,输入的两个数代表着这两个人互相认识(如果1和2认识,2和3认识,那么1和3也就认识了)。问需要多少桌子。
思路:
并查集的基础题目,pre数组存的是父节点的值,root数组代表是否为根节点。最后统计根节点的数量就可以了~~~~~
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <algorithm>
using namespace std;
const int MAXN = 1e3 + ;
int pre[MAXN];
bool root[MAXN]; int Find(int x)
{
int r = x;
while(pre[r] != r)
{
r = pre[r];
}
int i = x,j;
while(pre[i] != r) //路径压缩
{
j = i;
i = pre[i];
pre[j] = r;
}
return r;
} void mix(int a,int b)
{
int x = Find(a);
int y = Find(b);
if(x > y)
{
pre[x] = y;
}
if(x < y)
{
pre[y] = x;
}
} int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int M,N;
for(int i = ; i <= MAXN; i++)
{
pre[i] = i;
root[i] = false;
}
scanf("%d%d",&M,&N);
while(N--)
{
int a,b;
scanf("%d%d",&a,&b);
mix(a,b);
}
for(int i = ; i <= M; i++)
{
if(pre[i] == i)
root[i] = true;
}
int ans = ;
for(int i = ; i <= M; i++)
{
if(root[i]) ans ++;
}
printf("%d\n",ans);
}
return ;
}
最新文章
- 自定义 Activity 的 标题栏 TitleBar
- Windows Azure Virtual Network (7) 设置Azure Virtual Machine固定公网IP (Virtual IP Address, VIP) (2)
- 【BZOJ-3832】Rally 拓扑序 + 线段树 (神思路题!)
- VS重新生成后仍然执行旧代码
- cocos2d-x 3.2 listview scorllview 等容器在小米华为等部分手机显示泛白解决
- EF 示例
- 从一个例子中体会React的基本面
- 关于typedef的使用方法
- 关于 Apple Metal API 的一些想法
- SpringAop学习
- iOS开发中的那些小技巧
- CSS水平、垂直居中小结
- android——fragment详解
- 【转】IntentService的原理及使用
- git使用教程及github远程仓库管理
- 测试与发布(Alpha版本)
- UltraEdit激活方法
- 使用java命令重启tomcat
- 安卓开发笔记(二十四):手把手教你一步步集成腾讯X5内核(Tencent TBS X5)
- eq
热门文章
- 【bzoj4998】星球联盟 LCT+并查集
- JavaScript正则表达式大全
- innodb_force_recovery
- __cdecl,__stdcall,__fastcall,__pascal,__thiscall 的区别
- JRE集成到Tomcat
- 状压dp的题目列表 (一)
- All in One到”分布式“迁移过程中的坑
- 在Idea中使用Eclipse编译器
- Matlab xpC启动盘
- bzoj1499: [NOI2005]瑰丽华尔兹&;&;codevs1748 单调队列优化dp