HDU-1875 最小生成树 PRIM

来源:互联网 发布:数据库锁的特性 编辑:程序博客网 时间:2024/06/05 21:52

简单小题,没什么好说的。

/* * hdu-1875 * mike-w * 2012-4-19 */#include<stdio.h>#include<stdlib.h>#include<string.h>#include<math.h>#define MAX_SIZE 128#define INF (1e20)#ifndef true#define true (1)#endif#define EPS (1e-5)double lake[MAX_SIZE][2];double f[MAX_SIZE][MAX_SIZE];double dst[MAX_SIZE];int tag[MAX_SIZE];int T,N;int build_graph(void){int i,j;double dx,dy,dd;for(i=0;i<N;i++)for(j=i;j<N;j++){dx=lake[i][0]-lake[j][0];dy=lake[i][1]-lake[j][1];dd=sqrt(dx*dx+dy*dy);if(dd>=10.0 && dd<=1000.0)f[i][j]=f[j][i]=dd*100.0;elsef[i][j]=f[j][i]=INF;}return 0;}double prim(void){int i,x,fail;double cost;for(i=0;i<N;i++)tag[i]=0,dst[i]=INF;dst[0]=0;fail=0;cost=0.0;while(true){/* extract mininal */x=-1;for(i=0;i<N&&tag[i];i++);for(x=i++;i<N;i++)if(!tag[i] && dst[i]<dst[x])x=i;if(x>=N || fabs(dst[x]-INF)<EPS)break;/* update */tag[x]=1;cost+=dst[x];for(i=0;i<N;i++)if(!tag[i] && f[x][i]<INF && f[x][i]<dst[i])dst[i]=f[x][i];}for(i=0;i<N;i++)if(!tag[i])fail=1,i=N;return fail?-1.0:cost;}int main(void){#ifndef ONLINE_JUDGEfreopen("in","r",stdin);#endifint i;double cost;scanf("%d",&T);while(T-->0){scanf("%d",&N);for(i=0;i<N;i++)scanf("%lf%lf",lake[i],lake[i]+1);build_graph();cost=prim();if(cost<0)puts("oh!");elseprintf("%.1lf\n",cost);}return 0;}


原创粉丝点击