Description
The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has a very poor system of public highways. The Flatopian government is aware of this problem and has already constructed a number of highways connecting some of the most important towns. However, there are still some towns that you can't reach via a highway. It is necessary to build more highways so that it will be possible to drive between any pair of towns without leaving the highway system.Input
The input consists of two parts. The first part describes all towns in the country, and the second part describes all of the highways that have already been built.Output
Write to the output a single line for each new highway that should be built in order to connect all towns with minimal possible total length of new highways. Each highway should be presented by printing town numbers that this highway connects, separated by a space.Sample Input
9 1 5 0 0 3 2 4 5 5 1 0 4 5 2 1 2 5 3 3 1 3 9 7 1 2
Sample Output
1 6 3 7 4 9 5 7 8 3
Source
Northeastern Europe 1999此題很坑,竟然是單實例,且邊比較多,最好用prim算法。
對於已經連通的邊,可以把邊權賦值為0,輸出時加以判斷就OK了。
#include"stdio.h" #include"string.h" #define N 800 const int inf=0x7fffffff; int x[N],y[N],n,pre[N]; int g[N][N],dis[N]; bool mark[N]; int fun(int i,int j) { return (x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]); } void prim() { int s=1,min,i,j; for(i=1;i<=n;i++) { dis[i]=g[s][i]; pre[i]=s; } memset(mark,0,sizeof(mark)); mark[s]=1; for(j=1;jdis[i]&&!mark[i]) { min=dis[i]; s=i; } } if(min!=0) printf("%d %d\n",pre[s],s); mark[s]=1; for(i=1;i<=n;i++) { if(!mark[i]&&dis[i]>g[s][i]) { dis[i]=g[s][i]; pre[i]=s; } } } } int main() { int i,j,m; scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d%d",&x[i],&y[i]); } for(i=1;i<=n;i++) { g[i][i]=0; for(j=i+1;j<=n;j++) { g[i][j]=g[j][i]=fun(i,j); } } scanf("%d",&m); while(m--) { scanf("%d%d",&i,&j); g[i][j]=g[j][i]=0; } prim(); return 0; }