POJ2349Arctic Network(最小生成树)

题目大意:

给出p个点的坐标,构成一颗最小生成树,把其中权值最大的s-1条边去掉后,问权值最大的边是多少


分析:

prime完后,有每条边的权值大小记录,排下序就行。

#include
#include
#include
#include
#include
using namespace std;
const int maxn = 505;
const double inf = 0x3f3f3f3f;
double road[maxn][maxn], dis[maxn];
bool vis[maxn];
int s, n;
struct Poi
{
    double x, y;
}poi[maxn];
double get_dis(int i, int j)
{
    double x1, y1, x2, y2;
    x1 = poi[i].x;
    y1 = poi[i].y;
    x2 = poi[j].x;
    y2 = poi[j].y;
    return sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
}
void prim()
{
    int v;
    double mi;
    for(int i = 0; i < n; i++)
    {
        dis[i] = road[0][i];
        vis[i] = false;
    }
    for(int i = 1; i <= n; i++)
    {
        mi = inf;
        for(int j = 0; j < n; j++)
        {
            if(!vis[j] && (mi - dis[j]) > 1e-6)
            {
                mi = dis[j];
                v = j;
            }
        }
        vis[v] = true;
        for(int j = 0; j < n; j++)
        {
            if(!vis[j] && (dis[j] - road[v][j]) > 1e-6)
                dis[j] = road[v][j];
        }
    }
    sort(dis, dis+n);
    printf("%.2f\n", dis[n-s]);
}
int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        cin >> s >> n;
        for(int i = 0; i < n; i++)
            scanf("%lf%lf", &poi[i].x, &poi[i].y);
        for(int i = 0; i < n; i++)
            for(int j = i+1; j < n; j++)
                road[i][j] = road[j][i] = get_dis(i, j);
        prim();
    }
    return 0;
}



你可能感兴趣的:(图论-生成树)