1013. Battle Over Cities (25)

来源:互联网 发布:亚马逊关键词软件 编辑:程序博客网 时间:2024/05/02 12:42

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 31 21 31 2 3
Sample Output
100

分析:

(1)本题可以用并查集,也可以有其他方法,但是显然并查集的方法更巧妙。

(2)思路大致为,读取,个点根节点指向自己,若两点联通其中一点就指向另外一点的跟节点(不包含删除点),最终统计除了删除节点外指向自己的节点个数,这边是不想交子集数,也就是需要需要加的路径数-1.

(3)嗯,如果没有了解过并查集就会用到比较麻烦的思路,所以在学习阶段,先分析考察什么再编程序是可以提高效率的。

#include <stdio.h>int root[1002];int findx(int x){return root[x]==x?x:root[x]=findx(root[x]);}void merge(int x, int y){int fx,fy;fx=findx(x);fy=findx(y);if (fx!=fy){root[fy]=fx;//}}int main(int argc, char *argv[]){int n,m,k,i,j,t;int link[1002*1002][2]={0};scanf("%d%d%d",&n,&m,&k);for (i=0;i<m ;i++ ){scanf("%d%d",&link[i][0],&link[i][1]);}for (i=0;i<k ;i++ ){int d;scanf("%d",&d);for (t=0;t<=n ;t++){root[t]=t;}for (j=0;j<m ;j++ ){if (link[j][0]!=d&&link[j][1]!=d){merge(link[j][0],link[j][1]);}}int cn=-1;for (t=1;t<=n ;t++ ){if (root[t]==t&&t!=d){cn++;}}printf("%d\n",cn);}return 0;}


0 0