zoj1203_Swordfish(最小生成树)

来源:互联网 发布:如何评价黄海冰 知乎 编辑:程序博客网 时间:2024/06/06 21:46
#include<iostream>#include<string.h>#include<vector>#include<utility>#include<cmath>#include<queue>#include<iomanip>using namespace std;struct cmpq{    bool operator()(pair<int,double> p1,pair<int,double> p2){        return p1.second>p2.second;    }};vector<pair<int,double>> edge[110];bool used[110];vector<pair<double,double>> pos;priority_queue<pair<int,double>,vector<pair<int,double>>,cmpq> q;double getlen(pair<double,double> p1,pair<double,double> p2){    double len=0;    len=sqrt(pow((p1.first-p2.first),2)+pow((p1.second-p2.second),2));    return len;}double prim(int n){    memset(used,false,sizeof(used));    double res=0;    while(!q.empty())        q.pop();    used[0]=true;    for(int i=0;i<edge[0].size();i++)        q.push(edge[0][i]);    for(int i=1;i<n;i++)    {        while(used[q.top().first])            q.pop();        used[q.top().first]=true;        res+=q.top().second;        int nexp=q.top().first;        q.pop();        for(int j=0;j<edge[nexp].size();j++)            q.push(edge[nexp][j]);    }    return res;}int main(){    int n;    int t=1;    while(cin>>n&&n)    {        for(int i=0;i<n;i++)            edge[i].clear();        pos.clear();        for(int i=0;i<n;i++)        {            double x,y;            cin>>x>>y;            pos.push_back(make_pair(x,y));            for(int j=0;j<i;j++)            {                double tlen=getlen(pos[i],pos[j]);                edge[i].push_back(make_pair(j,tlen));                edge[j].push_back(make_pair(i,tlen));            }        }        if(t>1)            cout<<endl;        cout<<"Case #"<<t++<<":"<<endl;        cout<<"The minimal distance is: "<<setiosflags(ios::fixed)<<setprecision(2)<<prim(n)<<endl;    }    return 0;}
0 0
原创粉丝点击