Connection

Description

There are N cities in the country and M bidirectional roads between the cities. The government wants to build some new roads such that for any pair of cities there is at least one path between them. Now you have to find out the minimal amount of roads that have to build.

 

Input

The input may contain multiple test cases.

For each test case, the first line is two integers N (1<=N<=100) and M (1<=M<=N*N/2), indicating the number of cities and the number of roads. Then the next M lines each contain two integers x and y (0<=x,y<n), meaning that there is a road between cities x and cities y.

N=M=0 indicates the end of input.

 

Output

For each test case, print the answer in a single line.

 

Sample Input
5 2
0 1
2 3
0 0
Sample Output
2

主要的思路是用记忆化深度搜索dfs。
#include<iostream>
using namespace std;
bool roads[101][101];
bool visited[101];
int city,road,connect;
void dfs(int index)
{
   visited[index]=true;
   for (int i = 0; i < city; ++i)
   {
    /* code */
    if(roads[index][i]==true&&!visited[i])
    dfs(i);
   }
}
int main()
{

while(cin>>city>>road&&(city!=0&&road!=0))
{
memset(roads,0, sizeof(roads));
memset(visited,0, sizeof(visited));
connect=0;
int a,b;
for (int i = 0; i < road; ++i)
{
/* code */
cin>>a>>b;
            roads[a][b]=true;
            roads[b][a]=true;
}
for (int i = 0; i < city; ++i)
{
/* code */
if(!visited[i]){
dfs(i);
connect++;
}

}
printf("%d\n",connect-1);
       
}
system("pause");
return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值