码迷,mamicode.com
首页 > 其他好文 > 详细

PAT 1013. Battle Over Cities

时间:2018-01-05 10:28:40      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:stream   destory   连通   and   body   cte   pair   tar   ini   

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

标签:stream   destory   连通   and   body   cte   pair   tar   ini   

原文地址:https://www.cnblogs.com/A-Little-Nut/p/8202687.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!