最小生成树算法-Kruskal && Prim
图:
~无向图:
~有向图:DAG 拓扑排序
树:最小生成树
图和树:最短路
//kruskal, 加边
pair<int, pair<int,int> > edge[maxn];
//pair<int, pair<int, int> > a;
//a.first = w; // u<--- w ---> v
//a.second.first = u;
//a.second.second = v;
cin >> n >> m; // O(mlogm)
for (int i = 1; i <= m; i++){
int u, v, w;
cin >> u >> v >> w;
edge[i] = make_pair(w,make_pair(u,v));
}
sort(edge + 1, edge + m + 1);
for (int i = 1; i <= m; i++) {
int u = edge[i].second.first;
int v = edge[i].second.second;
int w = edge[i].first;
if(find(u) == find(v)) continue;
else{
union(u, v);
ans += w;
}
}
cout << ans << endl;
//prim, 加点
memset(dis, 63, sizeof(dis));
memset(vis, 63, sizeof(dis));
dis[1] = 0;
for (int t = 1; t <= n; t++) {
for (int i = 1; i <= n; i++){
pair<int, int> minn; // first: w, second: node
minn = make_pair(1 << 30, 1 <<30);
if(!vis[i] && dis[i] < minn.first){
minn = make_pair(dis[i], i);
}
}
int u = minn.first; //second???
vis[u] = true;
for(int i = 0; i < (int)g[u].size(); i++){
int ch = g[u][i].first;
if(!vis[ch] && dis[ch] > g[u][i].second)
dis[ch] = g[u][i].second;
}
}