6.23 PAT 甲级 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 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​​.

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

翻译:

在战争中,所有城市都必须通过高速公路连接起来,这一点至关重要。

如果一个城市被敌人占领,则从该城市/往该城市的所有高速公路都将关闭。

此时,我们必须立即判断是否需要维修其他高速公路以保持其余城市的连通性。

给定城市与道路分布地图以及一个重点关注城市列表,请你判断,当列表中的某个城市被攻陷时,至少要维修多少条高速公路才能保持其余城市的连通性。

例如,共有 3 座城市,由 2 条高速公路将它们连通,一条连接城市 1 和城市 2,一条连接城市 1 和城市 3。

当城市 1 被敌人占领时,我们需要在城市 2 和城市 3 之间维修一条高速公路,以保持这两座城市的连通。

输入格式

第一行包含三个整数 N,M,K,分别表示城市总数,高速公路总数,重点关注城市数量。

接下来 M 行,每行包含两个整数 a,b,表示城市 a 和城市 b 之间存在一条高速公路。

所有城市编号从 1 到 N。

最后一行,包含 K 个整数,表示重点关注的城市编号。

输出格式

共 K 行,每行输出一个重点关注城市被占领时,为了保持其余城市连通性,需要维修的最少高速公路条数。

 

本题采用并查集。先将通了路的城市并到一个集合里面去,然后将重点关注城市去掉,看剩下的图有几个连通分量,假设有t个连通分量,那么就需要维修t-1条高速公路。而求连通分量就是看剩下的路(不包括重点关注城市的)是否在一个集合内,假设原来的连通分量总数为n-1,如果不在一个集合内,就将连通分量减1,并将它们连结到一起。

#include
#include
using namespace std;

const int N = 1010, M = 500010;

int n,m,k;
int p[N];

struct Edge
{
    int a,b;
}e[M];

int find(int x)
{
    while(p[x] != x) p[x] = find(p[x]);
    return p[x];
}

int main()
{
    scanf("%d%d%d",&n, &m, &k);
    
    for(int i = 0; i < m; i ++ )
    {
        scanf("%d%d", &e[i].a, &e[i].b);
    }
    
    
    while(k -- )
    {
        int r;
        scanf("%d", &r);
        
        for(int j = 0; j <= n; j ++) p[j] = j;
        
        int cnt = n - 1;
        
        for(int j = 0; j < m; j ++ )
        {
            int a = e[j].a, b = e[j].b;
            if(a != r && b != r)
            {
                int pa = find(a), pb = find(b);
                if(pa != pb)
                {
                    p[pa] = pb;
                    cnt --;
                }
            }
        }
        
        printf("%d\n", cnt - 1);
            
    }
    
    return 0;
}

 

你可能感兴趣的:(PAT,甲级,C/C++)