Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
Prim 32ms#include <stdio.h> #include <math.h> #define To2(x) (x)*(x) #define MAXN 501 typedef struct { int x; int y; }Point; Point vex[MAXN]; double G[MAXN][MAXN],dis[MAXN]; int vexnum,visited[MAXN]; int S,P; double fach(int i,int j) { return (double)sqrt((double)(To2(vex[i].x-vex[j].x)+To2(vex[i].y-vex[j].y))); } void Initial(int N) { int i,j; for(i=1;i<=N;++i) for(j=1;j<=i;++j) G[i][j]=G[j][i]=fach(i,j); vexnum=N; } int FindMin() { int i,k=-1; double min=100000; for(i=1;i<=vexnum;++i) { if(visited[i]==1) continue; if(dis[i]<min) k=i,min=dis[i]; } return k; } void qsort(int left,int right) { if(left<right) { int i=left,j=right; double pivot=dis[left]; while(i<j) { while(i<j&&dis[j]>=pivot) j--; if(i<j) dis[i++]=dis[j]; while(i<j&&dis[i]<pivot) i++; if(i<j) dis[j--]=dis[i]; } dis[i]=pivot; qsort(left,i-1); qsort(i+1,right); } } void Prim(int k) { int i,j; for(i=1;i<=vexnum;++i) dis[i]=G[k][i],visited[i]=0; dis[k]=0,visited[k]=1; for(i=1;i<vexnum;++i) { k=FindMin(); if(k==-1) break; visited[k]=1; for(j=1;j<=vexnum;++j) { if(visited[j]==1) continue; if(dis[j]>G[k][j]) dis[j]=G[k][j]; } } qsort(1,vexnum); printf("%.2lf\n",dis[vexnum-S+1]); } int main() { int N,i; scanf("%d",&N); while(N--) { scanf("%d %d",&S,&P); for(i=1;i<=P;++i) scanf("%d %d",&vex[i].x,&vex[i].y); Initial(P); Prim(1); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator