Hoj 2676 Relation:
题目连接:http://acm.hit.edu.cn/hoj/problem/view?id=2676
本题是并查集的基础题:求亲戚关系。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
using namespace std;
int f[5002];
int findset(int a)
{
if(a == f[a])
{
return a;
}
f[a] = findset(f[a]);
return f[a];
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int n,m,q;
int t1,t2;
while(scanf(" %d %d %d",&n,&m,&q)!=EOF)
{
for(int i=1;i<=n;i++)
{
f[i] = i;
}
for(int i=1;i<=m;i++)
{
scanf(" %d %d",&t1,&t2);
t1 = findset(t1);
t2 = findset(t2);
if(t1<t2)
{
f[t2] = t1;
}
else if(t1 > t2)
{
f[t1] = t2;
}
}
for(int i=1;i<=q;i++)
{
scanf(" %d %d",&t1,&t2);
if(findset(t1) == findset(t2))
{
printf("yes\n");
}
else
{
printf("no\n");
}
}
}
return 0;
}
Hoj 1564 The Suspects
题目:http://acm.hit.edu.cn/hoj/problem/view?id=1564
本题也是并查集的基础题,要求连带关系。注意每组先求出最小的根,进行启发式的优化。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
using namespace std;
int f[30005];
int temp[30005];
int findset(int a)
{
if(a == f[a])
{
return a;
}
f[a] = findset(f[a]);
return f[a];
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int n,m;
int num = 0;
while(scanf(" %d %d",&n,&m)!=EOF && !(n==0 && m==0))
{
num = 0;
for(int i=0;i<n;i++)
{
f[i] = i;
}
for(int i=0;i<m;i++)
{
int t;
int father;
int x;
int min = n;
scanf(" %d",&t);
for(int j=0;j<t;j++)
{
scanf(" %d",&x);
temp[j] = findset(x);
if(temp[j]<min)
{
min = temp[j];
}
}
for(int j=0;j<t;j++)
{
f[temp[j]] = min;
}
}
int ans = findset(0);
for(int i=0;i<n;i++)
{
if(findset(i) == ans)
{
num++;
}
}
printf("%d\n",num);
}
return 0;
}
Hoj 2033 Ubiquitous Religions
题目:http://acm.hit.edu.cn/hoj/problem/view?id=2033
本题也是并查集。只不过要处理祖先有多少个,开一个bool的数组,记录是否访问过即可。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
using namespace std;
int f[50005];
bool vis[50005];
int findset(int a)
{
if(a == f[a])
{
return a;
}
f[a] = findset(f[a]);
return f[a];
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int n,m;
int num = 0;
while(scanf(" %d %d",&n,&m)!=EOF && !(n==0 && m==0))
{
num ++;
for(int i=1;i<=n;i++)
{
f[i] = i;
}
int x,y;
for(int i=1;i<=m;i++)
{
scanf(" %d %d",&x,&y);
x = findset(x);
y = findset(y);
if(x<y)
{
f[y] = x;
}
else
{
f[x] = y;
}
}
memset(vis,false,sizeof(vis));
vis[1] = true;
int ans = 1;
for(int i=1;i<=n;i++)
{
if(vis[findset(i)] == false)
{
ans++;
vis[findset(i)] = true;
}
}
printf("Case %d: %d\n",num,ans);
}
return 0;
}