PAT 1013. Battle Over Cities

Posted A-Little-Nut

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT 1013. Battle Over Cities相关的知识,希望对你有一定的参考价值。

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

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

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

分析

这道题主要考图,其实大家很容易看出最后的答案等于去掉点后的连通分量减一,我们可以借助visited数组的dfs或者bfs来实现对图的连通分量计算,首先被destoryed的city直接被标记为访问过的,因为与之相连的所有路都不通了(即所有点都访问不了他,他也访问不了其他点),然后对visited中为访问过的点进行dfs,dfs经过的每一个点都标记为访问过了,如果dfs结束后,cnt++,在对visited中其他为访问过的dfs,cnt++,如此下去,直至所有点都被访问过,此时cnt就是连通分量数;

代码如下

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int G[1001][1001]={-1};
int n,m,k,c1,c2,destroyed;
vector<int> visited(1001,0);
void dfs(int i){
    visited[i]=1;
    for(int j=1;j<=n;j++)
        if(visited[j]==0&&G[i][j]==1)
        dfs(j);
}
using namespace std;
int main(){
    cin>>n>>m>>k;
    for(int i=0;i<m;i++){
        cin>>c1>>c2;
        G[c1][c2]=G[c2][c1]=1;
    } 
    for(int i=0;i<k;i++){
        fill(visited.begin(),visited.end(),0);
        cin>>destroyed;
        visited[destroyed]=1;
        int cnt=0;
        for(int i=1;i<=n;i++)
        if(visited[i]==0){
            cnt++;
            dfs(i);
        }
        cout<<cnt-1<<endl;
    }
    return 0;
}

以上是关于PAT 1013. Battle Over Cities的主要内容,如果未能解决你的问题,请参考以下文章

PAT1013: Battle Over Cities

pat 1013 Battle Over Cities(25 分) (并查集)

PAT A1013 Battle Over Cities (25 分)

PAT Advanced 1013 Battle Over Cities (25分)

PAT Advanced Level 1013 Battle Over Cities (25)(25 分)

PAT 1013Battle Over Cities