sicily 1090

本文提供了两种实现最小生成树(MST)的算法示例:一种是通过Prim算法找到MST的最大边权重,另一种是利用Kruskal算法结合并查集确定MST。这两种方法都用于寻找连接所有顶点且总权重最小的树形子图。

最小生成树

#include <iostream> #include <cstring> using namespace std; #define MAX 65537 int adj[500][500]; bool isVis[500]; int lowcost[500]; int main() { int cases, n; cin >> cases; while(cases--) { cin >> n; int max = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cin >> adj[i][j]; } } memset(isVis, false, sizeof(isVis)); isVis[0] = true; for(int i = 0; i < n; i++) { lowcost[i] = adj[0][i]; } for(int i = 1; i < n; i++) { int min = MAX; int minIndex = 0; for(int j = 0; j < n; j++) { if(!isVis[j] && lowcost[j] < min) { min = lowcost[j]; minIndex = j; } } isVis[minIndex] = true; if(min > max) max = min; for(int j = 0; j < n; j++) { if(!isVis[j] && adj[minIndex][j] < lowcost[j]) lowcost[j] = adj[minIndex][j]; } } cout << max << endl; if(cases != 0) cout << endl; } return 0; }

找父节点是翻版陈泽裕的

#include <iostream> #include <cstring> #include <algorithm> using namespace std; #define MAX 65537 struct node { int x; int y; int weight; }edge[125000]; bool isVis[500]; int fa[500]; bool cmp(node a, node b) { return a.weight < b.weight; } int getfather(int x) { return fa[x] == x ? x : fa[x] = getfather(fa[x]); } int main() { int cases, n; cin >> cases; while(cases--) { cin >> n; int weight; int num = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cin >> weight; if(i < j) { edge[num].x = i; edge[num].y = j; edge[num].weight = weight; num++; } } } sort(edge, edge + num, cmp); memset(isVis, false, sizeof(isVis)); int max = 0; int e = 0; for(int i = 0; i < n; i++) fa[i] = i; for(int i = 0; i < num && e < n - 1; i++) { int x = getfather(edge[i].x); int y = getfather(edge[i].y); if(x != y) { e++; if(edge[i].weight > max) max = edge[i].weight; fa[x] = y; } } cout << max << endl; if(cases != 0) cout << endl; } return 0; }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值