PAT(甲)1013 Battle Over Cities (25)(详解)

1013 Battle Over Cities (25)(25 分)

题目描述:

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 city~1~-city~2~ and city~1~-city~3~. Then if city~1~ is occupied by the enemy, we must have 1 highway repaired, that is the highway city~2~-city~3~.


  • 输入格式
    Each input file contains one test case. Each case starts with a line containing 3 numbers N (&lt1000), 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.

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


解题方法:
题目大意:通过拿掉其中一个城市,看剩余的城市要连通至少需要建几条高速公路。
方法:dfs+连通图分量个数计算
由于我们知道N个点,至少只需要N-1条边遍可以把所有点连接起来。在这里,也是这样考虑的,我们可以把每个城市看成图中的一个点,而高速公路就是图中的边,构建无向图。而连通分量个数的计算只需要用dfs从每一个未访问过的点中进行遍历,dfs结束便得到一个连通分量。


程序:

#include <stdio.h>
bool visit[1002];
int G[1002][1002];
int N;

void dfs(int city)
{   /* 深度优先搜索遍历 */
    visit[city] = true;
    for (int i = 1; i <= N; i++)
        if (visit[i] == false && G[city][i] == 1)
            dfs(i);
}

int main(int argc, char const *argv[])
{
    int M, K, city_1, city_2, loss_city, cnt;
    scanf("%d %d %d", &N, &M, &K);
    for (int i = 0; i < M; i++)
    {   /* 创建图 */
        scanf("%d %d", &city_1, &city_2);
        G[city_1][city_2] = G[city_2][city_1] = 1;
    }
    for (int i = 0; i < K; i++)
    {
        for (int j = 1; j <= N; j++)
            visit[j] = false;    /* 每次都要初始化visit数组 */
        scanf("%d", &loss_city);
        visit[loss_city] = true;    /* 这样就可以在dfs时去掉与loss_city相关的边 */
        cnt = 0;
        for (int j = 1; j <= N; j++) /* 遍历所有城市 */
            if (visit[j] == false)
            {   /* 如果当前城市还未访问, 进入dfs同时把联通的城市访问置为true */
                dfs(j);
                cnt++;
            }
        printf("%d\n", cnt-1);
    }
    return 0;
}

如果对您有帮助,帮忙点个小拇指呗~

猜你喜欢

转载自blog.csdn.net/invokar/article/details/80500573