NOJ——[1143] Irrigation of Farmland


  • 问题描述
  • Hungar has bought some farms.There is a river near the farm. It was found that linking these farms is more conducive for hungar. Therefore, he need to calculate that the minimum number of waterway he should build to connect all the farms, either connecting directly or not directly.There is not existing a waterway between river and farm,so you should also connecting them.
  • 输入
  • Input until EOF.
    For each case:
    First line: two non-negative integers M (1<=M<= 500) and N(1<=N<=500), M means the number of farms, from 1 to M.
    The next N lines: each line have two numbers A, B represents the existing waterway number.
  • 输出
  • Print the number of waterway in one line.
  • 样例输入
  • 4 2
    1 3
    4 3
    2 2
    1 2
    1 2
    
  • 样例输出
  • 2
    1
    
  • 提示
  • 来源
  • hungar

并查集。

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>

using namespace std;

int father[505];

int find(int x)
{
if(x!=father[x])
father[x]=find(father[x]);
return father[x];
}

int main()
{
int m,n;
while(~scanf("%d%d",&m,&n))
{
for(int i=0;i<=m;i++)
father[i]=i;
int u,v,cnt=0;
while(n--)
{
scanf("%d%d",&u,&v);
int x=find(u);
int y=find(v);
if(x!=y)
father[x]=y;
}
for(int i=1;i<=m;i++)
if(i==father[i])
cnt++;
printf("%d\n",cnt);
}
return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值