图论基础之并查集的简单看法:HDU 1232 畅通工程&&More is better
2013-07-29 23:40
561 查看
HDU 1232 畅通工程http://acm.hdu.edu.cn/showproblem.php?pid=1232
第一个并查集的题目:
反正就是一数组和俩函数(查找和连接) 具体看大牛的解析:http://hi.baidu.com/nicker2010/item/9b593c2019c720846f2cc3ee
还有一份更牛逼的代码:
第一个并查集的题目:
#include<iostream> #include<stdio.h> #include<algorithm> using namespace std; int father[1000]; int Find(int a) { if(a!=father[a]) return Find(father[a]); return father[a]; } void Union(int a,int b) { a=Find(a); b=Find(b); if(a!=b) father[a]=b; } int main() { int n,m,i,a,b,x; while(scanf("%d",&n)!=EOF) { if(n==0) break; scanf("%d",&m); for(i=1;i<=n;i++) father[i]=i; for(i=0;i<m;i++) { scanf("%d%d",&a,&b); Union(a,b); } x=0; for(i=1;i<=n;i++) { if(father[i]==i) x++; } printf("%d\n",x-1); } return 0; }
反正就是一数组和俩函数(查找和连接) 具体看大牛的解析:http://hi.baidu.com/nicker2010/item/9b593c2019c720846f2cc3ee
More is betterhttp://acm.hdu.edu.cn/showproblem.php?pid=1856
题意:一个老师想请学生帮忙 这些学生有只直接或者间接的朋友关系,老师只请他们中间的一群人帮忙 求最大的人数。#include<stdio.h> int pre[10000002]; int count[10000002];//每个集合的人数 int m;//集合中最大的人数 int find(int x) { int r=x; while(pre[r]!=r) r=pre[r]; return r; } int join(int x,int y) { if(count[x]>count[y]) { pre[y]=x; count[x]+=count[y]; if(count[x]>m) m=count[x]; } else { pre[x]=y; count[y]+=count[x]; if(count[y]>m) m=count[y]; } return 0; } int main() { int n,i; int a,b; while(scanf("%d",&n)!=EOF) { m=1; for(i=0;i<10000002;i++) { pre[i]=i; count[i]=1; } for(i=0;i<n;i++) { scanf("%d %d",&a,&b); a=find(a); b=find(b); if(a!=b) join(a,b); } printf("%d\n",m); } return 0; }
还有一份更牛逼的代码:
#include<stdio.h> int m,rank[10000010],p[10000010],max; void Make_set() { int i; for(i=0; i<10000010; i++) { p[i]=i; rank[i]=1; } } int Find_set(int x) { if(p[x]!=x) p[x]=Find_set(p[x]); return p[x]; } void Union(int x,int y) { p[x]=y; rank[y]+=rank[x]; max=max>rank[y]?max:rank[y]; rank[x]=0; } int main(){ int x,y,i; while(scanf("%d",&m)!=EOF) { Make_set(); max=0; for(i=0; i<m; i++) { scanf("%d%d",&x,&y); x=Find_set(x); y=Find_set(y); if(x!=y) Union(x,y); } if(max) printf("%d\n",max); else printf("1\n"); } }
相关文章推荐
- hdu 1232 畅通工程(简单并查集)
- hdu 1232 畅通工程 并查集基础题
- HDU 1856 More is better(并查集 很好的基础题)
- HDU--1232 -- 畅通工程 [并查集最简单应用]
- hdu 1232 畅通工程(简单并查集)
- HDU 1232 畅通工程(简单并查集)
- HDU 1856 More is better(并查集 很好的基础题)
- 畅通工程 HDU - 1232--并查集简单应用
- HDU 1856 More is better 基础并查集★(经典)
- hdu 1856 More is better 基础并查集★
- hdu 1856 more is better(并查集基础)
- HDU 1232-畅通工程(简单并查集)
- hdu 1232 畅通工程 基础并查集★
- HDU 1232 畅通工程(基础并查集)
- HDU 1856 More is better(简单并查集) 【最大并查集人数模板】
- HDU 1232 畅通工程(简单并查集)
- HDU 1856 More is better(基础并查集)
- hdu 1856 More is better(并查集基础)
- HDU 1232 畅通工程 __ 基础并查集
- HDU - 1232 畅通工程(简单并查集)