Hoj 2676 Relation\Hoj 1564 The Suspects\Hoj 2033 Ubiquitous Religions

Hoj 2676 Relation:

题目连接:http://acm.hit.edu.cn/hoj/problem/view?id=2676

本题是并查集的基础题:求亲戚关系。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
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[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 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
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

Hoj 2033 Ubiquitous Religions

题目:http://acm.hit.edu.cn/hoj/problem/view?id=2033

本题也是并查集。只不过要处理祖先有多少个,开一个bool的数组,记录是否访问过即可。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
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


你可能感兴趣的:(Algorithm_数据结构,Algorithm_并查集)