-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskal.cpp
More file actions
82 lines (70 loc) · 1.44 KB
/
Kruskal.cpp
File metadata and controls
82 lines (70 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class UnionFind
{
private:
vector<int> parent;
public:
UnionFind(const int n):parent(vector<int>(n,-1))
{}
const int Find(const int p)
{
return parent[p] < 0 ? p : parent[p] = Find(parent[p]);
}
const void Merge(int p, int q);
const bool Belong(const int p, const int q)
{
return Find(p) == Find(q);
}
const int GetSize(const int p)
{
return -parent[Find(p)];
}
};
const void UnionFind::Merge(int p, int q)
{
p=Find(p);
q=Find(q);
if(p==q) return;
if(parent[p] < parent[q])
{
parent[p] += parent[q];
parent[q]=p;
}
else
{
parent[q] += parent[p];
parent[p]=q;
}
}
//
// Kruskal algorithm
//
struct Edge{
int start,end,dis;
bool operator >(const Edge &b)const{return dis > b.dis;}
};
using EdgeQueue=priority_queue<Edge,vector<Edge> ,greater<Edge> >;
const EdgeQueue convertGraph(const vector<vector<Edge> > &g)
{
EdgeQueue que;
for(auto&& es:g)
for(auto&& e:es)
que.push(e);
return que;
}
const vector<Edge> Kruskal(const int n, EdgeQueue que)
{
UnionFind belong(n);
Edge edge;
vector<Edge> min_cost_tree;
while(!que.empty())
{
edge=que.top();
if(belong.Find(edge.start)!=belong.Find(edge.end))
{
belong.Merge(edge.start, edge.end);
min_cost_tree.push_back(edge);
}
que.pop();
}
return min_cost_tree;
}