1900-Dominos(并查集) ZCMU

Description

  Dominos are lots of fun. Children like to stand the tiles on their side in long lines. When one domino falls, it knocks down the next one, which knocks down the one after that, all the way down the line. However, sometimes a domino fails to knock the next one down. In that case, we have to knock it down by hand to get the dominos falling again.

  Your task is to determine, given the layout of some domino tiles, the minimum number of dominos that must be knocked down by hand in order for all of the dominos to fall.

Input

  The first line of input contains one integer specifying the number of test cases to follow. Each test case begins with a line containing two integers, each no larger than 100 000. The first integer n is the number of domino tiles and the second integer m is the number of lines to follow in the test case. The domino tiles are numbered from 1 to n. Each of the following lines contains two integers x and y indicating that if domino number x falls, it will cause domino number y to fall as well.

Output

  For each test case, output a line containing one integer, the minimum number of dominos that must be knocked over by hand in order for all the dominos to fall.

Sample Input

1

3 2

1 2

2 3

Sample Output

1

思路

一看到题我想到并查集,但会出现一种情况 1-2,3-2,这种情况应该需要推两次,但在并查集中它们会变成同一个集合,所以这里可以计算一下读取时没有父亲的牌,然后和并查集后的集合数比较,输出较大的那个

代码

#include<stdio.h>
#include<algorithm>
using namespace std;
#define MAX 100005
int tile[MAX],vis[MAX];
void init(int n)
{
    for(int i=1;i<=n;i++)
    {
       tile[i]=i;
       vis[i]=0;
    }
}
int getfar(int x)
{
    if(tile[x]==x) return x;
    else
    {
        tile[x]=getfar(tile[x]);
        return tile[x];
    }
}
int Merge(int x,int y)
{
    int tx=getfar(x);
    int ty=getfar(y);
    if(tx!=ty) tile[ty]=tx;
}
int main()
{
    int T,n,m,i,x,y;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        if(n==0)
        {
            printf("0\n");
            continue;
        }
        init(n);
        for(i=1;i<=m;i++)
        {
            scanf("%d%d",&x,&y);
            Merge(x,y);
            vis[y]=1;
        }
        int sum=0,ans=0;
        for(i=1;i<=n;i++)
        {
            if(tile[i]==i) sum+=1;
            if(!vis[i]) ans+=1;
        }
        printf("%d\n",max(sum,ans));
    }
    return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值