【图论06】最小生成树 1001 Constructing Roads

来源:互联网 发布:什么图案画数据对比表 编辑:程序博客网 时间:2024/06/14 10:15

算法思路:Kruskal + 并查集。


//模板开始#include <string>   #include <vector>   #include <algorithm>   #include <iostream>   #include <sstream>   #include <fstream>   #include <map>   #include <set>   #include <cstdio>   #include <cmath>   #include <cstdlib>   #include <ctime>#include<iomanip>#include<string.h>#define SZ(x) (int(x.size()))using namespace std;int toInt(string s){istringstream sin(s); int t; sin>>t; return t;}template<class T> string toString(T x){ostringstream sout; sout<<x; return sout.str();}typedef long long int64;int64 toInt64(string s){istringstream sin(s); int64 t; sin>>t;return t;}template<class T> T gcd(T a, T b){ if(a<0) return gcd(-a, b);if(b<0) return gcd(a, -b);return (b == 0)? a : gcd(b, a % b);}//模板结束(通用部分)#define ifs cin#define BIAN_SHU 5060#define DING_DIAN_SHU 105int u[BIAN_SHU];int v[BIAN_SHU];int w[BIAN_SHU];int r[BIAN_SHU];int p[DING_DIAN_SHU];int dis[DING_DIAN_SHU][DING_DIAN_SHU];int cmp(const int i, const int j){return w[i] < w[j];}int find(int x){return p[x] == x ? x : p[x] = find(p[x]);}void init(int n){for(int i = 0; i < n; i++){p[i] = i;}}int kruskal(int m){int ans = 0;for(int i = 0; i < m; i++){r[i] = i;}sort(r, r + m, cmp);for(int i = 0; i < m; i++){int e = r[i];int x = find(u[e]);int y = find(v[e]);if(x != y){ans += w[e];p[x] = y;}}return ans;}//【图论06】最小生成树 1001 Constructing Roadsint main(){//ifstream ifs("shuju.txt", ios::in);int villages;int bian;while(ifs>>villages){init(villages);bian = 0;int temp;for(int i = 0; i < villages; i++){for(int j = 0; j < villages; j++){if(j > i){ifs>>w[bian];u[bian] = i;v[bian] = j;bian++;}else{ifs>>temp;}}}int exist;int ui, vi;ifs>>exist;for(int i = 0; i < exist; i++){ifs>>ui>>vi;ui--;vi--;int x = find(ui);int y = find(vi);if(x != y){p[x] = y;}}int ans = kruskal(bian);cout<<ans<<endl;}return 0;}


原创粉丝点击