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.
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.
For each test case, print the answer in a single line.
5 2
0 1
2 3
0 0
2
#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;
}