<OJ_Sicily>Connection

40 篇文章 0 订阅

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值