zoj 1203 Swordfish(Prim!)

來源:互聯網
上載者:User

前幾道最小產生樹的題都是PRIM與KRUSKAL均可以做的,這道題明顯的prim簡單點~~

 

還是挺水的MST。。。不過PE了N次。小糾結下。。。

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.