Sample Input
2
2
10 10 //坐标
20 20
3
1 1
2 2
1000 1000
Sample Output
1414.2 //最小权值和*100 保留1位小数
oh! //不连通
prim
1 # include <iostream> 2 # include <cstdio> 3 # include <cstring> 4 # include <algorithm> 5 # include <cmath> 6 # define LL long long 7 using namespace std ; 8 9 const int INF=0x3f3f3f3f; 10 const int MAXN=110; 11 bool vis[MAXN]; 12 double lowc[MAXN]; 13 int n ; 14 double cost[MAXN][MAXN] ; 15 16 struct poin 17 { 18 int x ; 19 int y ; 20 }p[110]; 21 22 double Prim()//点是0~n-1 23 { 24 double ans=0; 25 memset(vis,false,sizeof(vis)); 26 vis[0]=true; 27 for(int i=1;i<n;i++)lowc[i]=cost[0][i]; 28 for(int i=1;i<n;i++) 29 { 30 double minc=INF; 31 int p=-1; 32 for(int j=0;j<n;j++) 33 if(!vis[j]&&minc>lowc[j]) 34 { 35 minc=lowc[j]; 36 p=j; 37 } 38 if(minc==INF)return -1;//原图不连通 39 ans+=minc; 40 vis[p]=true; 41 for(int j=0;j<n;j++) 42 if(!vis[j]&&lowc[j]>cost[p][j]) 43 lowc[j]=cost[p][j]; 44 } 45 return ans; 46 } 47 48 int main() 49 { 50 51 // freopen("in.txt","r",stdin) ; 52 int T ; 53 scanf("%d" , &T) ; 54 while(T--) 55 { 56 scanf("%d" , &n) ; 57 int i , j ; 58 for (i = 0 ; i < n ; i++) 59 for (j = 0 ; j < n ; j++) 60 cost[i][j] = INF ; 61 for (i = 0 ; i < n ; i++) 62 scanf("%d %d" , &p[i].x , &p[i].y) ; 63 for (i = 0 ; i < n ; i++) 64 for (j = i+1 ; j < n ; j++) 65 { 66 double t = sqrt((double)(p[i].x - p[j].x) * (p[i].x - p[j].x) + (p[i].y - p[j].y) * (p[i].y - p[j].y)) ; 67 if (t <10.0 || t > 1000.0) 68 continue ; 69 cost[i][j] = t ; 70 cost[j][i] = t ; 71 } 72 double k = Prim() ; 73 if (k == -1) 74 printf("oh!\n") ; 75 else 76 printf("%.1lf\n" , k*100) ; 77 78 } 79 return 0 ; 80 }
时间: 2024-10-11 09:39:47