forked from jyx-fyh/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkruskal.cpp
More file actions
59 lines (58 loc) · 1.34 KB
/
kruskal.cpp
File metadata and controls
59 lines (58 loc) · 1.34 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
//
// Created by ButcherX on 23-11-13.
//
#include<vector>
#include"../header/UnionFind.h"
#include"../header/graph.h"
#include<queue>
using std::priority_queue;
using std::vector;
struct cmp
{
bool operator()(graphEdge* a, graphEdge* b)
{
return a->weight > b->weight;
}
};
unordered_set<graphEdge*> kruskal(const graph &_graph)
{
unordered_set<graphEdge*> ret;
list<graphNode*> listNode;
for(auto n : _graph.nodes)
listNode.push_back(n.second);
UnionFind<graphNode*> uf(listNode);
priority_queue<graphEdge*, vector<graphEdge*>, cmp> queEdge;
for(auto n : _graph.edges)
queEdge.push(n);
graphEdge* tmp;
while(!queEdge.empty())
{
tmp = queEdge.top();
queEdge.pop();
if(!uf.isSameSet(tmp->to, tmp->from))
{
ret.emplace(tmp);
uf.Union(tmp->from, tmp->to);
}
}
return ret;
}
int main()
{
vector<vector<int>> vec = {
{3, 'a', 'b'},
{1, 'a', 'c'},
{1, 'b', 'c'},
{10, 'b', 'e'},
{2, 'c', 'e'},
{50, 'c', 'f'},
{1, 'e', 'g'},
{6, 'f', 'h'},
{3, 'f', 'g'},
{9, 'g', 'h'}
};
graph gra = graphAdaptor(vec);
auto ret = kruskal(gra);
for(auto e : ret)
std::cout << e->weight << std::endl;
}