HDUOJ-1325 Is It A Tree?(并查集)

Problem Description

在这里插入图片描述
图1图2是树,图3不是(存在环)

在这里插入图片描述

Input

在这里插入图片描述

Output

在这里插入图片描述

Sample Input

6 8 5 3 5 2 6 4
5 6 0 0
8 1 7 3 6 2 8 9 7 5
7 4 7 8 7 6 0 0
3 8 6 8 6 4
5 3 5 6 5 2 0 0
-1 -1

Sample Output

Case 1 is a tree.
Case 2 is a tree.
Case 3 is not a tree.

输入x,y表示有向边x->y,要求无环,只有一个根,所有节点连通(根能到达所有节点)

多组输入,每组以0 0结束,所有输入以-1 -1结束

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 1e3+10;
int pre[N];
bool vis[N]= {0};//表示节点是否被指向过
int findd(int x)//找父节点
{
    if(x!=pre[x])
    {
        int t=findd(pre[x]);
        pre[x]=t;
    }
    return pre[x];
}
void unity(int x,int y)
{
    int fx = findd(x), fy = findd(y);
    if (fx != fy)
    {
        pre[fy] = fx;
    }
}
int judge(int x,int y)//判断x,y是否连通(父节点相同)
{
    int fx=findd(x),fy=findd(y);
    if(fx!=fy)return 1;
    return 0;
}
struct node//结构体存边
{
    int x;
    int y;
} no[N];
int main()
{
    int n,tem;
    int x,y;
    int fl=1;
    for(int i=1; i<=1005; i++)//初始化
    {
        pre[i]=i;
    }
    int k=0;
    int cot=1;//计数
    while(~scanf("%d%d",&x,&y))
    {
        if(x==-1&&y==-1)break;
        if(x==0&&y==0)
        {
          for(int i=1; i<k; i++)//判断是否存在不连通点,由于每次输入x,y肯定连通,判断x和上次输入y即可
            {
                if(judge(no[i-1].y,no[i].x))                
                {
                    fl=0;
                    break;
                }
            }
            if(fl)printf("Case %d is a tree.\n",cot);
            else printf("Case %d is not a tree.\n",cot);
            for(int i=1; i<=1005; i++)
            {
                pre[i]=i;
            }
            fl=1;
            k=0;
            cot++;
            for(int i=1; i<=1005; i++)vis[i]=0;
            continue;
        }
        no[k].x=x;
        no[k++].y=y;//记录每条边
        unity(x,y);
        if(vis[y])fl=0;//判断是否有唯一根和环,如果多个点指向同一点,则必然存在环或多个根节点
        vis[y]=1;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值