-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMST_KRUSKAL.cpp
More file actions
146 lines (130 loc) · 1.99 KB
/
MST_KRUSKAL.cpp
File metadata and controls
146 lines (130 loc) · 1.99 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
//https://www.acmicpc.net/problem/1197
#include<vector>
#include<iostream>
#include<algorithm>
typedef std::vector<std::vector<int>> Graph;
//with Disjoint-set forests
class UNION_FIND
{
public:
UNION_FIND() : n(101)
{
rank = new int[101];
parent = new int[101];
}
UNION_FIND(int n) : n(n)
{
rank = new int[n];
parent = new int[n];
}
~UNION_FIND()
{
delete[] rank;
delete[] parent;
}
void MAKE_SET(int x)
{
parent[x] = x;
rank[x] = 0;
}
void UNION(int x, int y)
{
LINK(this->FIND_SET(x), this->FIND_SET(y));
}
int FIND_SET(int x)//path compression
{
if (x != parent[x])
{
parent[x] = this->FIND_SET(parent[x]);
}
return parent[x];
}
int capacity()
{
return n;
}
private:
int* rank;//Union by ran
int* parent;
int n;
void LINK(int x, int y)
{
if (rank[x] > rank[y])
{
parent[y] = x;
}
else
{
parent[x] = y;
if (rank[x] == rank[y])
{
rank[y] = rank[y] + 1;
}
}
}
};
struct edge
{
int u;
int v;
int w;
bool operator <(edge& Edge)
{
return this->w < Edge.w;
}
};
std::vector<edge> MST_KRUSKAL(Graph& G, std::vector<edge>& W)
{
std::vector<edge> A;
const int n = G.size() - 1;
UNION_FIND SET(n+1);
for (int v = 1; v <= n; v++)
{
SET.MAKE_SET(v);
}
std::sort(W.begin(), W.end());
const int m = W.size();
for (int i = 0; i < m; i++)
{
if (SET.FIND_SET(W[i].u) != SET.FIND_SET(W[i].v))
{
A.push_back({ W[i].u,W[i].v,W[i].w });
SET.UNION(W[i].u, W[i].v);
}
}
return A;
}
/*
3 3
1 2 1
2 3 2
1 3 3
*/
int main()
{
std::ios::sync_with_stdio(false);
std::vector<edge> W;
Graph Graph;
int n, m;
std::cin >> n >> m;
Graph.resize(10001);
W.resize(m);
for (int i = 0; i < m; i++)
{
int u, v,w;
std::cin >> u >> v >> w;
Graph[u].push_back(v);
//Graph[v].push_back(u);
W[i].u = u;
W[i].v = v;
W[i].w = w;
}
std::vector<edge> A = MST_KRUSKAL(Graph,W);
std::int64_t sum = 0;
std::size_t mst_size = A.size();
for (int i = 0; i < mst_size; i++)
{
sum += A[i].w;
}
std::cout << sum;
}