POJ 2728 最小比率生成树 Prim 二分

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define eps 1e-5
#define INF 1e18
#define Distance(i,j) (sqrt((edge[i].x-edge[j].x)*(edge[i].x-edge[j].x)+(edge[i].y-edge[j].y)*(edge[i].y-edge[j].y)))
#define Cost(i,j) (fabs(edge[i].z-edge[j].z))
using namespace std;
const int maxv=1010;
const int maxe=1010;
bool visit[maxv];
int n;
double dis[maxv][maxv],cost[maxv][maxv];
struct Edge {
    double x,y,z;
} edge[maxe];
bool Prim(double x) {
    memset(visit,false,sizeof visit);
    double sum=0,lowcost[maxv];
    visit[1]=true;
    for(int i=1; i<=n; i++)
        lowcost[i]=cost[1][i]-x*dis[1][i];//lowcost记录每两个点的权值
    for(int i=2; i<=n; i++) {
        double temp=INF;
        int k=-1;
        for(int j=2; j<=n; j++) {//遍历顶点
            if(!visit[j]&&lowcost[j]<temp) {//找到最小权值
                k=j;
                temp=lowcost[j];
            }
        }
        if(k==-1)
            break;
        visit[k]=true;
        sum+=temp;
        for(int j=2; j<=n; j++) {
            if(visit[j]==false&&cost[k][j]-x*dis[k][j]<lowcost[j])
                lowcost[j]=cost[k][j]-x*dis[k][j];
        }
    }
    if(sum>=0)
        return true;
    return false;
}
int main(void) {
#ifndef ONLINE_JUDGE
    freopen("E:\\input.txt","r",stdin);
#endif
    while(cin>>n&&n) {
        for(int i=1; i<=n; i++)
            cin>>edge[i].x>>edge[i].y>>edge[i].z;
        for(int i=1; i<=n; i++)
            for(int j=1; j<=i-1; j++) { //下三角
                dis[i][j]=dis[j][i]=Distance(i,j);
                cost[i][j]=cost[j][i]=Cost(i,j);
            }
        double l=0.0,r=100.0;
        while(r-l>=eps) {
            double m=(l+r)/2;
            if(Prim(m))
                l=m;
            else
                r=m;
        }
        printf("%.3f\n",r);
    }
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值