【LittleXi】Minimum Spanning Tree
Introduction
In graph theory algorithms, it is often necessary to find the smallest edge that can connect all nodes
kruskal algorithm
Algorithm Introduction
The algorithm uses the greedy idea to connect all the points into a forest, and then connect all the forests into a tree. Each time, the nearest two points are connected until a tree is generated. At the same time, in order to prevent the formation of a ring, we are in the process of generating a tree. Use union search to check whether a cycle will be formed after connecting these two points. If find(l)==find®, it means that a cycle must be formed after connection.
example
P3366 [Template] Minimum spanning tree
[Template] Minimum spanning tree
topic description
As in the title, given an undirected graph, find the minimum spanning tree, and output it if the graph is not connected orz
.
input format
The first line contains two integers N , MN,MN,M , indicating that the graph has a total ofNNN nodes andMMM undirected edges.
next mmM lines each contain three integersX i , Y i , Z i X_i,Y_i,Z_iXi,Yi,Zi, indicating that there is a length Z i Z_iZiThe undirected edge connects nodes X i , Y i X_i,Y_iXi,Yi。
output format
If the graph is connected, output an integer representing the sum of the lengths of the sides of the minimum spanning tree. Output if the graph is not connected orz
.
Example #1
Sample Input #1
4 5
1 2 2
1 3 2
1 4 3
2 3 4
3 4 3
Sample output #1
7
hint
Data scale:
For 20 % 20\%2 0 % of the data,N ≤ 5 N\le 5N≤5,M≤20M\le 20M≤20。
For 40 % 40\%4 0 % of the data,N ≤ 50 N\le 50N≤5 0,M ≤ 2500 M\le 2500M≤2500。
For 70 % 70\%7 0 % of the data,N ≤ 500 N\le 500N≤5 0 0,M ≤ 1 0 4 M\le 10^4M≤104。
For 100 % 100\%1 0 0 % of data:1 ≤ N ≤ 5000 1\le N\le 50001≤N≤5 0 0 0,1 ≤ M ≤ 2 × 1 0 5 1\le M\le 2\times 10^51≤M≤2×105,1 ≤ Z i ≤ 1 0 4 1\le Z_i \le 10^41≤Zi≤104。
Example explanation:
So the total edge weight of the minimum spanning tree is 2 + 2 + 3 = 7 2+2+3=72+2+3=7。
Algorithm steps
- First sort the data according to the size of the edge
- Then traverse the edges in turn, if the two points are not connected together, then this edge is the edge of the minimum spanning tree
Algorithm implementation
struct edge
{
int l,r,dis;
};
edge es[200010];
int fa[5010];
bool comp(edge& e1, edge& e2)
{
return e1.dis < e2.dis;
}
void init(int n)
{
fa[n] = n;
}
int find(int i)
{
if (fa[i] == i)
return i;
fa[i] = find(fa[i]);
return fa[i];
}
void unionn(int x, int y)
{
int fa1 = find(x);
int fa2 = find(y);
fa[fa1] = fa2;
}
int main()
{
for (int i = 0; i < 5010; i++) init(i);
int n, m;
cin >> n >> m;;
for (int i = 0; i < m; i++)
cin >> es[i].l >> es[i].r >> es[i].dis;
sort(es, es + m, comp);
int cnt = 0;
for (int i = 0; i < m; i++)
{
int l = es[i].l;
int r = es[i].r;
if (find(l) == find(r))
continue;
unionn(l, r);
cnt += es[i].dis;
}
for(int i=1;i<n;i++)
if (find(i) != find(i + 1))
{
cout << "orz" << endl;
return 0;
}
cout << cnt << endl;
}