PAT

    xiaoxiao2021-12-14  43

    1013. Battle Over Cities (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 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

    分析 该题目就是求连通分支,可用查并集计算。发现测试点有误,立刻想到自己的查并集有问题,比如 边为1-4 2-3 3-4的图。要好好学习一下查并集,这是pat_a中第三次遇到查并集。code #include<iostream> #include<vector> #include<map> using namespace std; int city[1010][1010]; int f[1010]; vector<int>check; int N,M,K; int getf(int a) { for(int i=1;i<=N;i++) f[i]=i; //总感觉这样是不行的,应该搜索整个连通的图中,找到最小 //但却通过了,待研究! for(int i=1;i<=N;i++) { int min=f[i]; if(i==a) continue; //找出最小的父亲 for(int j=1;j<=N;j++) { if(j==a) continue; if(city[i][j]==1) { if(min>f[j]) min=f[j]; } } //更新:将这个集合中最小的值作为其他的父亲 for(int j=1;j<=N;j++) { if(j==a) continue; if(city[i][j]==1) f[j]=min; } } //map tmp[a]=b; //tmp中如果没有a-b,则插入a-b,有责修改b。 //以此消去重复 map<int,int>out; for(int i=1;i<=N;i++) { if(a==i) continue; out[f[i]]=1; } return out.size(); } int main() { cin>>N>>M>>K; int tmp1,tmp2; for(int i=1;i<=N;i++) f[i]=i; for(int i=0;i<M;i++) { cin>>tmp1>>tmp2; city[tmp1][tmp2]=1; city[tmp2][tmp1]=1; } for(int i=0;i<K;i++) { cin>>tmp1; check.push_back(tmp1); } for(int i=0;i<check.size();i++) { //连通分支-1接是需要修最少的路可使整个城市在一个图上 cout<<getf(check[i])-1<<endl; } return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-969037.html

    最新回复(0)