prim模板题加ac代码

Building a Space Station

#include<bits/stdc++.h>
using namespace std;

const int maxn=105;
double sum;

struct edge{
    int a,b;
    double v;
    edge(){}
    edge(int A,int B,double V){
        a=A;b=B;v=V;
    }
    bool operator < (const edge & a) const{
        return v>a.v;
    }
};


vector<edge>  G[maxn];
priority_queue<edge> Q;
bool vis[maxn];
int P,R;

void prim()
{
    int cou=0;
    //首先随便找一个点作为根
    for(int i=0;i<G[1].size();i++)
        Q.push(G[1][i]);
    vis[1]=true;
    while(!Q.empty()){
        //每次取不在树中的所有点中距离树最近的点
        edge W=Q.top();
        Q.pop();
        if(vis[W.b])
            continue;
        vis[W.b]=true;
        cou++;
        sum+=W.v;
        if(cou==P-1)
            return;
        for(int i=0;i<G[W.b].size();i++)
        Q.push(G[W.b][i]);
    }
}

void init(){
    for(int i=1;i<=P;i++)
            G[i].clear();
    while(!Q.empty())
        Q.pop();
    memset(vis,0,sizeof(vis));
    sum=0;

}
struct point{
    double x,z,y,r;
    point(){}
    point(double xx,double yy,double zz,double rr){
        x=xx,y=yy,z=zz,r=rr;
    }
}Poi[maxn];

int main()
{
    while(cin>>P && P)//输入点数和边数{
        init();
        for(int i=1;i<=P;i++){
            double x,y,z,r;
            cin>>x>>y>>z>>r;
            Poi[i]=point(x,y,z,r);
            
        }
        for(int i=1;i<=P-1;i++)
        for(int j=i+1;j<=P;j++){
            double dis=sqrt((Poi[i].x-Poi[j].x)*(Poi[i].x-Poi[j].x)+(Poi[i].y-Poi[j].y)*(Poi[i].y-Poi[j].y)+(Poi[i].z-Poi[j].z)*(Poi[i].z-Poi[j].z))-Poi[i].r-Poi[j].r;
            if(dis<0) dis=0;
            //无向图邻接表存储法
            G[i].push_back(edge(i,j,dis));
            G[j].push_back(edge(j,i,dis));
        }
        prim();
        printf("%.3lf\n",sum);
        getchar();
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值