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.
题目解释:对于给出N个城市,已知已有M条路,求问还需要添加多少条路可以实现任何两条路间至少有一条通路
解题思路:把N个城市看做N个点,M条路看做M条边,那么就可以将其看做是一个图。我们求出这个图一共有多少部分的时候,就可以求出需要多少条边了。因为我们的任务是将所有的城市连成一个整体,那么只需要在部分与部分之间连接便可。这道题使用上色的方法,对于一个连通图,我们标记同一个数字,最终看标记了多少个数字就可以知道这个图由多少个子图组成。
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
vector<int> r[100];
int visited[100];
void tag(int city, int color){
for (int i = 0; i < r[city].size(); i++) {
int nextcity = r[city][i];
if (visited[nextcity] == -1) {
visited[nextcity] = color;
tag(nextcity, color);
}
else continue;
}
}
int main(int argc, const char * argv[]) {
// insert code here...
int cityNum, rodeNum;
while (cin >> cityNum >> rodeNum) {
if (cityNum == 0 && rodeNum == 0) break;
for (int i = 0; i < cityNum; i++) {
r[i].clear();
}
int a,b;
for (int i = 0; i < rodeNum; i++) {
cin >> a >>b;
r[a].push_back(b);
r[b].push_back(a);
}
memset(visited, -1, sizeof(visited)); // 初始化
int index = 0; // index相同的城市属于同一个部分
for (int i = 0; i < cityNum; i++) {
if (visited[i] != -1) continue; // 该点已标记过
else{ // 该点无标记过,说明是新的部分
index ++;
visited[i] = index;
tag(i, index);
}
}
cout << index - 1 << endl;
}
return 0;
}