HDU ACM 1856 More is better(并查集)
【题目链接】http://acm.hdu.edu.cn/showproblem.php?pid=1856
【解题思路】给的数据有点大,干脆少开点数组,直接上set存储有朋友的孩子的编号,同时根据编号初始化对应的在father数组中的下标,同时也更新集合,后面开一个数组存储同属于于一个集合的数有多少个(在以根为数组的下标中存储),然后遍历一次找到最大的数
1 #include <cstdio> 2 #include <cstring> 3 #include <set> 4 #include <algorithm> 5 #define SIZE 10000001 6 #define MAXN 100002 7 using namespace std; 8 int father[SIZE]; 9 int num[SIZE]; 10 11 set<int>exist; 12 13 14 int find(int f) 15 { 16 return father[f] = f == father[f] ? f : find(father[f]); 17 } 18 19 20 int main() 21 { 22 #ifndef ONLINE_JUDGE 23 freopen("input.txt", "r", stdin); 24 #endif 25 int n; 26 while(scanf("%d", &n) != EOF) 27 { 28 if(!n) 29 { 30 printf("1\n"); 31 continue; 32 } 33 exist.clear(); 34 memset(num, 0, sizeof(num)); 35 for(int i=0; i<n; ++i) 36 { 37 int u, v; 38 scanf("%d%d", &u, &v); 39 if(exist.find(u) == exist.end()) 40 { 41 father[u] = u; 42 exist.insert(u); 43 num[u] = 0; 44 } 45 if(exist.find(v) == exist.end()) 46 { 47 exist.insert(v); 48 father[v] = v; 49 num[v] = 0; 50 } 51 u = find(u); 52 v = find(v); 53 father[u] = v; 54 } 55 for(set<int>::const_iterator iter = exist.begin(); iter != exist.end(); ++iter) 56 { 57 num[find(*iter)]++; 58 } 59 int curmax = 0; 60 for(set<int>::const_iterator iter = exist.begin(); iter != exist.end(); ++iter) 61 { 62 if(curmax < num[*iter]) curmax = num[*iter]; 63 } 64 printf("%d\n", curmax); 65 } 66 return 0; 67 }

更多内容请关注个人微信公众号 物役记 (微信号:materialchains)
作者:雪影蓝枫
本文版权归作者和博客园共有,欢迎转载,未经作者同意须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?