PAT甲级1013. Battle Over Cities (25)

来源:互联网 发布:淘宝网店如何加盟 编辑:程序博客网 时间:2024/06/16 02:27

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

分析:
有N个城市,有M条高速公路。有一个城市被敌人占领了,需要补修多少条路才能保证剩下N-1个城市是连通的?如果两个城市之间有道路连通,那么这两个城市属于同一个集合。需要补修的高速路的数量=集合的数量(即连通分量的数量)-1
判断连通性的高效简洁的方法当然是并查集了。

#include <cstdio>using namespace std;#include <vector>const int MAX=1000+10;int C[MAX];int cnt=0; //连通分量的个数 struct Road{    int City1;    int City2;};int Find(int x){    if(C[x]==x) return x;    return C[x]=Find(C[x]);}void Union(int u,int v){    int pu=Find(u);    int pv=Find(v);    if(pu!=pv) {        C[pu]=pv;        cnt--;    }}int main(){    int N,M,K;    scanf("%d %d %d",&N,&M,&K);    /*Infomation of highways connecting two cities*/     vector<Road> V(M);    for(int i=0;i<M;i++){        scanf("%d %d",&V[i].City1,&V[i].City2);    }    for(int k=0;k<K;k++){        cnt=N-1; //不算被占领的城市,最开始的连通分量的个数为 N-1         for(int i=1;i<=N;i++) C[i]=i; //初始化并查集         int occupied;        scanf("%d",&occupied);        for(int i=0;i<M;i++){            if(V[i].City1!=occupied&&V[i].City2!=occupied) Union(V[i].City1,V[i].City2);        }        printf("%d\n",cnt-1);//需要修建的道路的条数 = 连通分量的个数减 1     }    return 0;}
0 0
原创粉丝点击