poj2485(Kruskal)
2024-10-19 04:23:29
这道题显然是一道最小生成树的问题,参考算法导论中的Kruskal方法,先对路径长度进行排序,然后使用并查集(Disjoint Set Union)来判断节点是否连通,记录连接所有节点的最后一条路径的长度即为最大的长度了。
下面的并查集算法还可以通过设置rank数组记录节点的等级来进一步优化。总的来说还是一道简单题。
#include <cstdio>
#include <algorithm>
using namespace std; struct Edge{
int x, y;
int dis;
}; int pre[]; int find(int x)
{
int r = x;
while (pre[r] != r){
r = pre[r];
}
int i = x, j;
while (i != r){
j = pre[i];
pre[i] = r;
i = j;
}
return r;
} bool joint(int x, int y)
{
int xRoot = find(x),
yRoot = find(y);
if (xRoot == yRoot)
return false;
pre[xRoot] = yRoot;
return true;
} bool cmp(Edge e1, Edge e2)
{
return e1.dis < e2.dis;
} int main()
{
int t;
scanf("%d", &t);
while (t--){
int n;
Edge edge[];
scanf("%d", &n);
for (int i = ; i < n; i++){
pre[i] = i;
}
int cnt = ;
for (int i = ; i < n; i++){
for (int j = ; j < n; j++){
int dis;
scanf("%d", &dis);
if (i > j)continue;
edge[cnt].x = i;
edge[cnt].y = j;
edge[cnt++].dis = dis;
}
}
sort(edge, edge + cnt, cmp);
int max = -;
for (int i = ; i < cnt; i++){
if (joint(edge[i].x, edge[i].y)){
max = edge[i].dis > max ? edge[i].dis : max;
}
}
printf("%d\n", max);
}
return ;
}
最新文章
- Javascript理解this对象
- 移动端-js触摸事件
- canvas 3D运动球效果 多球
- jS-模式之简单的订阅者和发布者模式
- Android拼图游戏
- [转载] 关关采集不能生成html的问题
- Invalid encoding name ";UTF8";. 报错 XML
- http://www.blogjava.net/nokiaguy/category/37087.html
- Mysql中Key与Index的区别
- #include <;limits.h>;
- SQL整理5
- 微信原生支付 Native扫码支付( V3.3.7 版本)
- ArrayList 冷门方法
- tar.gz和tar.bz2
- CodeForces - 589B(暴力)
- Apache beam中的便携式有状态大数据处理
- 第二个Sprint冲刺第 七天(燃尽图)
- JS实现弹出层效果
- 广播机制的CS模型实现
- MySQL查看用户权限的两种方法