zoukankan      html  css  js  c++  java
  • 1162Eddy's picture

    一次通过,刚学prim的时候做过一道类似的,将每个点之间的距离保存在double型的邻接矩阵里,然后调用prim
    #include <iostream>
    #include <algorithm>
    #include <iomanip>
    #include <cstring>
    #include <cmath>
    using namespace std;
    #ifndef ONLINE_JUDGE
    #include <fstream>
    ifstream fin("test.txt");
    #define cin fin
    #endif
    double graph[110][110];
    const int INF = 1000000;
    double dist(double a, double b, double c, double d)
    {
        return sqrt((a-c)*(a-c)+(b-d)*(b-d));
    }
    double prim(int n)
    {
        double lowcost[110],sum = 0;
        bool used[110];
        memset(used,0,sizeof(used));
        int i,j,k;
        for(i = 1; i <= n; ++i)
        lowcost[i] = graph[i][1];
        used[1] = 1;
        for(i = 1; i < n; ++i)
        {
            double min = INF;
            k = 1;
            for(j = 2; j <= n; ++j)
            {
                if(lowcost[j] < min && !used[j])
                {
                    k = j;
                    min = lowcost[j];
                }
            }
            used[k] = 1;
            sum += lowcost[k];
        //    sum += min;   搞不懂为什么这么写会错,输出变成了10000003.41 
            //明白了,输出1000003.41是因为i循环哪里多了一个等号,循环了n次,事实上只用n-1次
            for(j = 2; j <= n; ++j)
            if(graph[k][j] < lowcost[j] && !used[j])
            lowcost[j] = graph[k][j];
        }
        return sum;
    }
    int main()
    {
        ios::sync_with_stdio(false);
        int n,i,j;
        double x[110],y[110];
        while(cin >> n)
        {
            for(i = 1; i <= n; ++i)
            cin >> x[i] >> y[i];
            for(i = 1; i <= n; ++i)
            for(j = 1; j <= n; ++j)
            graph[i][j] = dist(x[i],y[i],x[j],y[j]);
            cout <<fixed << setprecision(2) << prim(n) << endl;
        }
        return 0;
    }
    View Code
    
    
  • 相关阅读:
    Openlayers 3 热力图
    javaScript 新学习:Array.contains 函数
    将页面内容转为Excel下载
    Cookie 的设置和获取
    escape()、encodeURI()、encodeURIComponent()区别详解
    java 对象与二进制互转
    获取与当前类同级目录下的文件
    Windows下比较小巧的c/c++ ide
    保存到properties
    javafx 普通弹框提示
  • 原文地址:https://www.cnblogs.com/fchx/p/3097585.html
Copyright © 2011-2022 走看看