pku 2253 Frogger Prim算法巧用 解题报告
题意:给出一个有权无向图,求出一条生成树其权值最大值,但在所有的生成树下,其值是最小的.
算法:熟悉Prim算法的过程,那么就很好解决次问题.
AC代码:
#include <math.h>
#include <stdio.h>
#include <string.h>
#define M 205
const double MAX = 2000000;
int n, s, t;
int x[M], y[M];
double graph[M][M], ans;
void init()
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
graph[i][j] = ((x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]));
}
}
}
void prim(int father[])
{
double min[M];
int i, j, k, used[M];
for (i= 0; i < n; i++)
{
min[i] = MAX;
used[i] = 0;
father[i] = -1;
}
min[0] = 0;
for (j = 0; j < n; j++)
{
for (k = -1, i = 0; i < n; i++)
{
if (!used[i] && (k == -1 || min[i] < min[k]))
{
k = i;
}
}
used[k] = 1;
for (i = 0; i < n; i++)
{
if (!used[i] && graph[k][i] < min[i])
{
father[i] = k;
min[i] = graph[k][i];
}
}
}
}
int main()
{
freopen("frogger.in", "r", stdin);
int i, test = 1;
while (scanf("%d", &n), n)
{
for (i = 0; i < n; i++)
{
scanf("%d%d", &x[i], &y[i]);
}
init();
s = 0, t = 1;
int father[M];
printf("Scenario #%d/n", test++);
prim(father);
i = 1;
ans = 0;
while (1)
{
if (ans < graph[father[i]][i])
{
ans = graph[father[i]][i];
}
i = father[i];
if (i == 0)
{
break;
}
}
printf("Frog Distance = %.3lf/n/n", (float)sqrt(ans));
getchar();
}
return 0;
}