zoj 1203 Swordfish(Prim!)

前几道最小生成树的题都是PRIM与KRUSKAL均可以做的,这道题明显的prim简单点~~

 

还是挺水的MST。。。不过PE了N次。小纠结下。。。

 

#include <stdio.h> #include <stdlib.h> #include <iostream> #include <iomanip> #include <math.h> #include <limits.h> #include <memory.h> #define N 110 using namespace std; struct c { double x,y; }city[N]; double compute(int x,int y) { return sqrt((city[x].x - city[y].x)*(city[x].x - city[y].x) + (city[x].y - city[y].y)*(city[x].y - city[y].y)); } double map[N][N]; int n; void input() { int i,j; for(i=1; i<=n; i++) cin >> city[i].x >> city[i].y; for(i=1; i<=n; i++) for(j=i+1; j<=n; j++) map[i][j] = map[j][i] = compute(i,j); } void prim() { double dis[N],sum = 0,min; int now,hash[N],i,j; memset(hash,0,sizeof(hash)); for(i=1; i<=n; i++) dis[i] = INT_MAX; now = 1; dis[now] = 0; hash[now] = 1; for(i=1; i<n; i++) { for(j=1; j<=n; j++) if( !hash[j] && dis[j] > map[now][j] ) dis[j] = map[now][j]; for(j=1,min = INT_MAX; j<=n; j++) if( !hash[j] && dis[j] < min ) min = dis[now = j]; hash[now] = 1; sum += dis[now]; } cout << "The minimal distance is: "; cout << setiosflags(ios::fixed) << setprecision(2) << sum << endl; } int main(void) { int count = 1; while( cin >> n && n ) { input(); if( n && count!=1 ) cout << endl; cout << "Case #" << count++ << ":"<< endl; prim(); } return 0; }  

你可能感兴趣的:(zoj 1203 Swordfish(Prim!))