甲级 1013 Battle Over Cities

It is vitally important to have all the cities connected by highways in a war. If a city is occupied by the enemy, all the highways from/toward that city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities connected. Given the map of cities which have all the remaining highways marked, you are supposed to tell the number of highways need to be repaired, quickly.

For example, if we have 3 cities and 2 highways connecting city1​-city2​ and city1​-city3​. Then if city1​ is occupied by the enemy, we must have 1 highway repaired, that is the highway city2​-city3​.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 3 numbers N (<1000), M and K, which are the total number of cities, the number of remaining highways, and the number of cities to be checked, respectively. Then M lines follow, each describes a highway by 2 integers, which are the numbers of the cities the highway connects. The cities are numbered from 1 to N. Finally there is a line containing K numbers, which represent the cities we concern.

Output Specification:

For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.

Sample Input:

3 2 3
1 2
1 3
1 2 3

Sample Output:

1
0
0

题目大意:

第一排输入三个数,分别代表城市总数-n、道路总数-m、检查数-k

接一下m排,描述每条路连接哪两个城市~

最后一排k个数,是k个要检查的城市代号,答案要求输出:如果这个城市丢失了,那连接剩余城市需要再添加几条路~

思路:

1、用vector来存储每个城市的邻居城市

2、用dfs深度遍历当前城市的所有邻居城市

3、用isvisited数组标记已遍历过的城市,同时还要记得避开lostcity

4、每遍历完一轮,就等于(在丢失那个城市)情况下,获得的一个连通城市的集合

5、全部遍历完,就可以知道一共有几个独立的集合

6、别忘了集合数减一(两个集合需要一条路连接,三个集合需要两条路连接,以此类推……)

下面是我的代码~

#include<bits/stdc++.h>
using namespace std;

int n,m,k,lostcity;
const int N = 1010;
vector<int> v[N];        //记录邻居城市(比如城市a的邻居城市都记录在v[a]这个数组里面~)
int isvisited[N];        //标记是否已经遍历过,每次丢失城市更新后,该数组也要初始化

void dfs(int curcity) {
    isvisited[curcity] = 1;            //每走一个城市,就把0改成1
    for (int i:v[curcity]) {            //遍历v[curcity]的一种写法
        if (!isvisited[i] && i != lostcity) {
            dfs(i);                //避开已遍历的和丢失城市,继续重复
        }
    }
}

int main(){
    cin >> n >> m >> k;

    for (int i = 0; i < m; i++) {
        int a,b;
        cin >> a >> b;
        v[a].emplace_back(b);            //将b加入a的邻居城市中
        v[b].emplace_back(a);            //将a加入b的邻居城市中
    }

    while(k--) {
        int ans = 0;
        cin >> lostcity;
        for (int i = 1; i <= n; i++) isvisited[i] = 0;        //初始化标记数组
        for (int i = 1; i <= n; i++) {
            if (!isvisited[i] && i != lostcity) {
                dfs(i);
                ans++;
            }
        }
        ans = ans-1;
        cout << ans << endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值