练习四 1002

来源:互联网 发布:相遇网络里 编辑:程序博客网 时间:2024/04/30 11:08

概述:在平面坐标系中给你一些孤立的点,求把这些点联系起来的最小路程。

思路:这是经典最小生成树问题的一个变种,因为点的坐标是Double型的,所以比较难像其他题一样用位置表示点的根节点,所以,要从新给每个输入的点分配一个ID,然后就转化为经典的问题了。在这里我采用的仍然是Kruskal算法。

感想:无。

#include <iostream>#include <fstream>#include <algorithm>#include <cmath>#include <cstdio>using namespace std;const int N = 105;int father[N];struct point{    double x,y;    int root;}p[N*N];int find(int x){if (x != father[x])father[x] = find(father[x]);return father[x];}struct edge{point a,b;double v;}e[N*(N - 1) / 2];int cmp(edge e1, edge e2){return e1.v<e2.v;}int main(){    //ifstream cin("aaa.txt");    int n;    cin>>n;        for(int i=0;i<n;++i)        {            cin>>p[i].x>>p[i].y;            p[i].root=i;            father[i]=p[i].root;        }        int cnt=0;        for(int i=0;i<n;++i)            for(int j=i+1;j<n;++j)            {                e[cnt].a=p[i];                e[cnt].b=p[j];                e[cnt].v=sqrt(pow(p[i].x-p[j].x,2)+pow(p[i].y-p[j].y,2));                ++cnt;            }        sort(e,e+n*(n-1),cmp);        double ans=0;        for(int i=0;i<n*(n-1);++i)        {            int x = find(e[i].a.root);int y = find(e[i].b.root);if (x != y){ans += e[i].v;father[x] = y;}        }        printf("%.2lf\n",ans);        return 0;}


0 0
原创粉丝点击