首页 > 代码库 > uva 10034 Problem A: Freckles

uva 10034 Problem A: Freckles

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=975

最小生成树。

 1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <algorithm> 5 #define maxn 1000 6 using namespace std; 7 const double inf=(double)(1<<29); 8  9 int t,n;10 struct node11 {12     double x,y;13 }p[maxn];14 bool vis[maxn];15 double dis[maxn];16 double g[maxn][maxn];17 double ans;18 19 double sqr(double x)20 {21     return x*x;22 }23 24 void prim()25 {26     memset(vis,false,sizeof(vis));27     for(int i=1; i<=n; i++) dis[i]=g[1][i];28     dis[1]=0;29     vis[1]=true;30     for(int i=1; i<n; i++)31     {32         double m=inf;33         int x;34         for(int y=1; y<=n; y++) if(!vis[y]&&dis[y]<m) m=dis[x=y];35         ans+=m;36         vis[x]=true;37         for(int y=1; y<=n; y++) if(!vis[y]&&dis[y]>g[x][y]) dis[y]=g[x][y];38     }39 }40 41 int main()42 {43     scanf("%d",&t);44     while(t--)45     {46         scanf("%d",&n);47         for(int i=1; i<=n; i++)48         {49             scanf("%lf%lf",&p[i].x,&p[i].y);50         }51         for(int i=1; i<=n; i++)52         {53             for(int j=i; j<=n; j++)54             {55                 if(i==j) g[i][j]=0;56                 else57                 g[i][j]=g[j][i]=sqrt(sqr(p[i].x-p[j].x)+sqr(p[i].y-p[j].y));58             }59         }60         ans=0;61         prim();62         printf("%.2lf\n",ans);63         if(t) printf("\n");64     }65     return 0;66 }
View Code

 

uva 10034 Problem A: Freckles