zoukankan      html  css  js  c++  java
  • poj2560

    最小生成树

    View Code
    #include <iostream>
    #include
    <cstdio>
    #include
    <cstdlib>
    #include
    <cstring>
    #include
    <cmath>
    using namespace std;

    #define maxn 105

    struct Point
    {
    double x, y;
    } point[maxn];

    double cost[maxn][maxn];
    int n;

    double dis(int a, int b)
    {
    return sqrt((point[a].x - point[b].x) * (point[a].x - point[b].x) + (point[a].y
    - point[b].y) * (point[a].y - point[b].y));
    }

    void makecost()
    {
    for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
    cost[i][j]
    = dis(i, j);
    }

    double prim()
    {
    double lowcost[maxn];
    bool vis[maxn];

    memset(vis,
    0, sizeof(vis));
    for (int i = 0; i < n; i++)
    lowcost[i]
    = -1;
    lowcost[
    0] = 0;
    vis[
    0] = true;
    int pre = 0;
    double ans = 0;
    while (1)
    {
    for (int i = 0; i < n; i++)
    if (lowcost[i] > lowcost[pre] + cost[i][pre] || lowcost[i] == -1)
    lowcost[i]
    = lowcost[pre] + cost[i][pre];
    int best = 1000000000;;
    pre
    = -1;
    for (int i = 0; i < n; i++)
    if (!vis[i] && lowcost[i] < best)
    {
    best
    = lowcost[i];
    pre
    = i;
    }
    if (pre == -1)
    break;
    ans
    += lowcost[pre];
    vis[pre]
    = true;
    lowcost[pre]
    = 0;
    }
    return ans;
    }

    int main()
    {
    //freopen("t.txt", "r", stdin);
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    scanf(
    "%lf%lf", &point[i].x, &point[i].y);
    makecost();
    printf(
    "%.2f\n", prim());
    return 0;
    }

  • 相关阅读:
    虚拟机下linux系统安装spark一个小提示
    寒假学习记录第七天
    寒假学习记录第六天
    寒假学习记录第五天
    快捷键
    yum安装软件内容
    常见问题处理
    linux目录详解
    linux三剑客
    linux符号与正则表达式
  • 原文地址:https://www.cnblogs.com/rainydays/p/2051897.html
Copyright © 2011-2022 走看看