从点 1 开始生成最小生成树,直到将点 2 加入到树中,返回树中最大的边即可。
基本算法是Prim。
#include<iostream>
#include<cmath>
#include<cstdio>
#define FOR(i, N) for(int i = 1; i <= (N); i++)
using namespace std;
double cost[500][500];
int coordinate[500][2];
void read(int N){
FOR(i, N){
int x, y;
cin >> x >> y;
FOR(j, i){
coordinate[i][0] = x;
coordinate[i][1] = y;
int x0 = coordinate[j][0];
int y0 = coordinate[j][1];
double dist = sqrt(pow(x0 - x, 2.0) + pow(y0 - y, 2.0));
cost[i][j] = cost[j][i] = dist;
}
}
}
double prim(int N){
bool inTree[500];
FOR(i, N)
inTree[i] = false;
inTree[1] = true;
double MAX = -1;
FOR(i, N - 1){
double minCost = 10000000;
int index;
FOR(k, N){
if(inTree[k]){
FOR(j, N){
if(!inTree[j] && minCost > cost[k][j]){
minCost = cost[k][j];
index = j;
}
}
}
}
MAX = max(MAX, minCost);
inTree[index] = true;
//cout << MAX << " " << index << endl;
if(index == 2)
break;
}
return MAX;
}
int main(){
int N, caseNo = 0;
while(cin >> N && N != 0){
read(N);
printf("Scenario #%d\nFrog Distance = %.03f\n\n",++caseNo, prim(N));
}
}
本文介绍了一种使用Prim算法来解决特定问题的方法:从指定的起始点开始构造最小生成树,并在加入另一个指定点的过程中找到树中最大的边。通过具体的C++实现代码示例,详细展示了如何读取顶点坐标并计算它们之间的距离,然后逐步建立最小生成树直至包含特定点,并最终返回树中最大边的长度。
1362

被折叠的 条评论
为什么被折叠?



