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

如果對您有幫助,幫忙點個小拇指唄~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章