1012.畅通工程

来源:互联网 发布:sai软件多大 编辑:程序博客网 时间:2024/05/17 21:41
题目描述:
某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
输入:
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
输出:
对每个测试用例,在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


非常典型的并查集问题。并查集就两个操作,find和union。

关于并查集有两种合并方法:

1.按大小合并,每个根的数组元素包含这棵树的大小的负值,小树是大树的子树,合并时每次都更新。

2.按高度合并,每个根的数组元素包含这棵树的深度的负值,浅的树成为深的树的子树,除非两棵树相等才更新。

按大小合并:

#include <iostream>#include <vector>using namespace std;int find(vector<int> &a, int x){if(a[x] < 0)return x;elsereturn a[x] = find(a,a[x]);}void unionSets(vector<int> &a, int num1,int num2){int root1 = find(a,num1);int root2 = find(a,num2);if(root1 == root2)return;if(a[root1] < a[root2]){a[root1] += a[root2];a[root2] = root1;}else{a[root2] += a[root1];a[root1] = root2;}}int main(){int M;vector<int> ivec;while(cin >> M && M != 0){ivec.assign(M + 1,-1); //下标从1 - M,下标0是不使用的。int N;cin >> N;for(int i = 1; i <= N; ++i){int a,b;cin >> a >> b;unionSets(ivec,a,b);}int sets_number = 0;for(int i = 1; i <= M; ++i){if(i == find(ivec,i))sets_number++;}cout << sets_number - 1 << endl;ivec.clear();}return 0;}

按高度合并:

#include <iostream>#include <vector>using namespace std;int find(vector<int> &a, int x){if(a[x] < 0)return x;elsereturn a[x] = find(a,a[x]);}void unionSets(vector<int> &a, int num1,int num2){int root1 = find(a,num1);int root2 = find(a,num2);if(root1 == root2)return;if(a[root1] < a[root2]){a[root2] = root1;}else{if(a[root1] == a[root2])--a[root2];a[root1] = root2;}}int main(){int M;vector<int> ivec;while(cin >> M && M != 0){ivec.assign(M + 1,-1); //下标从1 - M,下标0是不使用的。int N;cin >> N;for(int i = 1; i <= N; ++i){int a,b;cin >> a >> b;unionSets(ivec,a,b);}int sets_number = 0;for(int i = 1; i <= M; ++i){if(i == find(ivec,i))sets_number++;}cout << sets_number - 1 << endl;ivec.clear();}return 0;}


注意,这里不能用DFS方法,DFS只能得到图是否联通,不能判断图里面有多少个集合。

0 0
原创粉丝点击