本题要求:
给出一个有向图,让你求出这个图的最小生成树
输入格式:
第一行输入V,E分别代表顶点数和边数
接下来E行,每行输入from to cost 代表从from到to的距离为cost
输出格式:
输出最小消耗
输入样例:
3 3
0 1 2
1 2 3
0 2 4
输出样例:
5
解题思路 :
按照边的权值的顺序从大到小查看一遍。
代码 :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Edge {
public:
int u;
int v;
int cost;
Edge(int u, int v, int cost) {
this->u = u;
this->v = v;
this->cost = cost;
}
Edge() {
}
};
using namespace std;
int par[];
int rank[];
void init(int n) {
for (int i = ; i < n; i++) {
par[i] = i;
rank[i] = ;
}
}
int find(int x) {
if (par[x] == x) {
return x;
} else {
return par[x] = find(par[x]);
}
}
void unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return;
} else if (rank[x] < rank[y]){
par[x] = y;
} else {
par[y] = x;
if (rank[x] == rank[y]) {
rank[x]++;
}
}
}
bool same(int x, int y) {
return find(x) == find(y);
}
bool comp(const Edge& e1, const Edge& e2) {
return e1.cost < e2.cost;
}
vector<Edge> es;
int V, E;
int kruskal() {
sort(es.begin(), es.end(), comp);
init(V);
int res = ;
for (int i = ; i < E; i++) {
Edge e = es[i];
if (!same(e.u, e.v)) {
unite(e.u, e.v);
res += e.cost;
}
}
return res;
}
int main() {
bool used[];
cin >> V >> E;
for (int i = ; i < E; i++) {
int f, t, c;
cin >> f >> t >> c;
es.push_back(Edge(f, t ,c));
}
cout << kruskal();
return ;
}