poj 1611 The Suspects // hoj 1564 The Suspects 并查集
/*
題目:
?? 是說學生0懷疑有SARS病,跟他接觸過的俱樂部的所有人以及他接觸過的人再與別人接觸,
?? 都有可能有SARS病,要你求出給出的所有俱樂部人的名單,要你求出所有的嫌疑犯。。。
分析:
?? 用并查集的方法做,具體實現是先定義n個森林,然后再把同一的人所在的森林合并在一起,
?? 而并查集的改善方法有兩種,我的使用的是壓縮路徑的方法
*/
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int X = 30010;
int parent[X],a[X],Rank[X],m,n,t;
int find_set(int x)?????????????? //路徑壓縮
{
?? if(x!=parent[x])
????? parent[x] = find_set(parent[x]);
?? return parent[x];
}
void union_set(int i,int j)
{
?? i = find_set(i);
?? j = find_set(j);
?? if(i!=j)
????? if(Rank[i]>Rank[j])???????? //等級越高,所在的樹的高度越高
???????? parent[j] = i;
????? else
????? {
???????? parent[i] = j;
???????? if(Rank[i]==Rank[j])
??????????? Rank[j]++;
????? }
}
int main()
{
?? freopen("sum.in","r",stdin);
?? freopen("sum.out","w",stdout);
?? int x,pre;
?? while(cin>>n>>m,n||m)
?? {
????? for(int i=0;i<n;i++)
????? {
???????? parent[i] = i;
???????? Rank[i] = 0;
????? }
????? for(int i=0;i<m;i++)
????? {
???????? scanf("%d",&t);
???????? if(t)????????????? //只需找出俱樂部的第一個人與其他人并起來即可
??????????? scanf("%d",&pre);
???????? for(int i=0;i<t-1;i++)
???????? {
??????????? scanf("%d",&x);
??????????? union_set(pre,x);
???????? }
????? }
????? pre = find_set(0);??? //找到0所在的樹的根節點編號,再用它與其他的人相比較
????? int ans = 1;
????? for(int i=1;i<n;i++)
???????? if(pre==find_set(i))
??????????? ans++;
????? cout<<ans<<endl;
?? }
?
?? return 0;
}
?
?
轉載于:https://www.cnblogs.com/yejinru/archive/2012/03/22/2412068.html
總結
以上是生活随笔為你收集整理的poj 1611 The Suspects // hoj 1564 The Suspects 并查集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 龙之谷手游圣徒技能怎么加点?圣徒技能加点
- 下一篇: FLASH怎么模拟按键音符动画效果(专注