Minimum spanning tree: A spanning tree of a connected graph with n nodes is a minimal connected subgraph of the original graph, and contains all n nodes in the original graph, and has the fewest edges that keep the graph connected. In fact, it is to make the graph connected with the smallest edge required to form a graph
Primm algorithm O(n 2 ) Idea: We initialize all points to positive infinity, and then maintain a set, each time we find a point from outside the set to the closest point to the set, and then use this point to update other points to the set The distance (distance to the set: the minimum value of the distance from this point to all points in the set), the point found each time is the point of the minimum spanning tree
Code
#include<iostream>#include<cstdio>#include<string>#include<cstring>#include<algorithm>usingnamespace std;constint N =510;constint INF =0x3f3f3f3f;int n, m;int g[N][N];int dist[N];//存储其他点到当前最小生成树的距离bool st[N];//存储每个点是否已经在生成树里面了intprim(){
memset(dist,0x3f,sizeof dist);int res =0;//边权之和for(int i =0; i < n; i++){
int t =-1;for(int j =1; j <= n; j++){
//找最小距离if(!st[j]&&(t ==-1|| dist[t]> dist[j])){
t = j;}}//说明图不连通if(i && dist[t]== INF)return INF;//防止自环更新(第一个点是正无穷)if(i) res += dist[t];//放入集合
st[t]=true;//用t更新其他点for(int j =1; j <= n; j++) dist[j]=min(dist[j], g[t][j]);}return res;}intmain(){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);memset(g,0x3f,sizeof g);
cin >> n >> m;for(int i =1; i <= m; i++){
int a, b, c;
cin >> a >> b >> c;
g[a][b]= g[b][a]=min(g[a][b], c);}int res =prim();if(res == INF) cout <<"impossible"<< endl;else cout << res << endl;return0;}