例5.1 畅通工程 (1012)
-
题目描述:某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
-
输入:测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。
输出:对每个测试用例,在1行里输出最少还需要建设的道路数目。
样例输入:
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
998
#include<stdio.h> using namespace std; #define N 1000 int Tree[N]; int findRoot(int x){ if(Tree[x]==-1) return x; else{ int tmp=findRoot(Tree[x]); Tree[x]=tmp; return tmp; } } int main(){ int n,m; while(scanf("%d",&n)!=EOF&&n!=0){ scanf("%d",&m); for(int i=1;i<=n;i++) Tree[i]=-1; while(m--){ int a,b; scanf("%d%d",&a,&b); a=findRoot(a); b=findRoot(b); if(a!=b) Tree[a]=b; } int ans=0; for(int i=1;i<=n;i++){ if(Tree[i]==-1) ans++; } printf("%d\n",ans-1); } return 0; }
例5.2 More is better (1044)
题目描述:Mr Wang wants some boys to help him with a project. Because the project is rather complex, the more boys come, the better it will be. Of course there are certain requirements.Mr Wang selected a room big enough to hold the boys. The boy who are not been chosen has to leave the room immediately. There are 10000000 boys in the room numbered from 1 to 10000000 at the very beginning. After Mr Wang's selection any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left. Given all the direct friend-pairs, you should decide the best way.
-
输入:The first line of the input contains an integer n (0 ≤ n ≤ 100 000) - the number of direct friend-pairs. The following n lines each contains a pair of numbers A and B separated by a single space that suggests A and B are direct friends. (A ≠ B, 1 ≤ A, B ≤ 10000000)
输出:The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.
题目大意:有10000000个小朋友,他们之中有N对好朋友,且朋友的关系具有传递性,要求我们找出一个最大(人数最多)的集合,该集合中任意两人之间都是朋友或者该集合中只有一个人,输出该最大人数。
样例输入:
4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8
样例输出:
4
2
#include <stdio.h> const int maxm = 10000002; int parent[maxm]; int num[maxm]; int n; int i; int findParent(int f) { while(parent[f] != f){ f = parent[f]; } return f; } void unionTwo(int f, int t) { int a = findParent(f); int b = findParent(t); if (a == b) return; if (a > b) { parent[a] = b; } else { parent[b] = a; } } int max(int a, int b){ return a > b ? a : b; } int main(){ while(scanf("%d",&n) != EOF){ for(i = 1; i < maxm; i++){ parent[i] = i; num[i] = 1; } for(i = 0 ; i < n ; i++){ int a, b; scanf("%d%d",&a,&b); unionTwo(a,b); } if(n == 1){ printf("%d\n",2); continue; } int maxNum = 1; for (i = 1; i < maxm; i++) { maxNum = max(++num[findParent(i)] , maxNum); } printf("%d\n",maxNum - 1); } return 0; }