4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
1 0 2 998Huge input, scanf is recommended.HintHint
在地图上给你若干个城镇,这些城镇都可以看作点,然后告诉你哪些对城镇之间是有道路直接相连的。最后要解决的是整幅图的连通性问题。比如随意给你两个点,让你判断它们是否连通,或者问你整幅图一共有几个连通分支,也就是被分成了几个互相独立的块。像畅通工程这题,问还需要修几条路,实质就是求有几个连通分支。
如果是1个连通分支,说明整幅图上的点都连起来了,不用再修路了;如果是2个连通分支,则只要再修1条路,从两个分支中各选一个点,把它们连起来,那么所有的点都是连起来的了;如果是3个连通分支,则只要再修两条路……用并查集!!!
#include<iostream> #include<stdio.h> int pre[1010]; int union_find(int node) { int leaf=node; while(node!=pre[node])node=pre[node]; while(node!=leaf) { int tmp=pre[node]; pre[leaf]=node; leaf=tmp; } return node; } int main(int argc, char *argv[]) { int num,road,total,a,b; //freopen("1232.in","r",stdin); while(scanf("%d %d",&num,&road)&&num!=0) { total = num-1; for(int i=1;i<=num;++i) pre[i]=i; while(road--) { scanf("%d %d",&a,&b); int p=union_find(a); int q=union_find(b); if(p!=q) { pre[p]=q; total--; } } printf("%d\n",total); } return 0; }
原文地址:http://blog.csdn.net/wdkirchhoff/article/details/41724197