Problem B: 最小生成树模板题

Problem B: 最小生成树模板题

Problem B: 最小生成树模板题

Time Limit: 1 Sec  Memory Limit: 128 MB
[Submit][Status][Web Board]

Description

给出一个数字N,代表有N个点,然后给出这N个点的坐标。求一个最小生成树将这N个点连通起来。 这里两点间的距离为欧几里德距离

Input

整个测试有多组数据
对于每组数据
第一行给出数字N,N<=1000
接下来N行给点的坐标x,y.-10000 <= X,Y <= 10000
整个测试以0代表结束

Output

输出见样例

Sample Input

5
0 0
0 1
1 1
1 0
0.5 0.5
0

Sample Output

Case #1:
The minimal distance is: 2.83

HINT

Code

#include<bits/stdc++.h>
using namespace std;
int ans,n;
float g[101][101];
struct bobo {
    float a,b;
} last[101];
float sqr(float a) {
    return a*a;
}
void mst() {
    float lost[101],min,s=0;
    int mini;
    bool b[101];
    memset(b,1,sizeof(b));
    for(int i=2; i<=n; i++)
        lost[i]=100000000;
    lost[1]=0;
    while(1) {
        min=100000000;
        for(int i=1; i<=n; i++)
            if(b[i]&&lost[i]<min) {
                min=lost[i];
                mini=i;
            }
        if(min==100000000)
            break;
        b[mini]=false;
        s+=min;
        for(int i=1; i<=n; i++)
            if(b[i]&&g[mini][i]<lost[i])
                lost[i]=g[mini][i];
    }
    printf("%.2f\n",s);
}
int main() {
    while(cin>>n) {
        if(n==0)
            return 0;
        if(ans>0)
            cout<<endl;
        ans++;
        for(int i=1; i<=n; i++)
            cin>>last[i].a>>last[i].b;
        for(int i=1; i<=n-1; i++)
            for(int j=i+1; j<=n; j++) {
                g[i][j]=sqrt(sqr((last[i].a-last[j].a))+sqr((last[i].b-last[j].b)));
                g[j][i]=g[i][j];
            }
        cout<<"Case #"<<ans<<":"<<endl;
        cout<<"The minimal distance is: ";
        mst();
    }
    return 0;
}

About



posted @ 2019-03-09 10:56  ZhaoChongyan  阅读(150)  评论(0编辑  收藏  举报