HDU1162,单纯地求最小生成树。此处用prim算法+邻接阵。
代码:
#include<iostream> #include<cmath> using namespace std; const int MAXV=105; const double inf=1000000000; typedef double elem_t; struct point { double x,y; }point[MAXV]; double map[MAXV][MAXV]; //prim算法 elem_t prim(int n) { double min[MAXV]; double ret=0; int v[MAXV],i,j,k; for (i=0;i<n;i++) min[i]=inf,v[i]=0; for (min[j=0]=0;j<n;j++) { for (k=-1,i=0;i<n;i++) if (!v[i]&&(k==-1||min[i]<min[k])) k=i; for (v[k]=1,ret+=min[k],i=0;i<n;i++) if (!v[i]&&map[k][i]<min[i]) min[i]=map[k][i]; } return ret; } int main(void) { int num,i,j; double length,ans,temp; while(scanf("%d",&num)==1)//节点数 { for(i=0;i<MAXV;i++) for(j=0;j<MAXV;j++) map[i][j]=map[j][i]=inf; for(i=0;i<num;i++) scanf("%lf%lf",&point[i].x,&point[i].y);//输入点的坐标 for(i=0;i<num;i++) for(j=0;j<num;j++) { temp=abs(point[i].x-point[j].x)*abs(point[i].x-point[j].x)+abs(point[i].y-point[j].y)*abs(point[i].y-point[j].y); length=sqrt(temp); map[i][j]=map[j][i]=length; } ans=prim(num); printf("%.2lf\n",ans); } return 0; } |
HDU1875,输入的时候做处理就行,题目要求边不能小于10||边不能大于1000,当边为这么大时,将其处理为inf即可。
代码:
#include<iostream> #include<cmath> using namespace std; const int MAXV=105; const double inf=1000000000; typedef double elem_t; struct point { double x,y; }point[MAXV]; double map[MAXV][MAXV]; elem_t prim(int n) { double min[MAXV]; double ret=0; int v[MAXV],i,j,k; for (i=0;i<n;i++) min[i]=inf,v[i]=0; for (min[j=0]=0;j<n;j++) { for (k=-1,i=0;i<n;i++) if (!v[i]&&(k==-1||min[i]<min[k])) k=i; for (v[k]=1,ret+=min[k],i=0;i<n;i++) if (!v[i]&&map[k][i]<min[i]) min[i]=map[k][i]; } return ret; } int main(void) { int num,i,j,cas; double length,ans,temp; scanf("%d",&cas); while(cas--) { scanf("%d",&num); for(i=0;i<MAXV;i++) for(j=0;j<MAXV;j++) map[i][j]=map[j][i]=inf; for(i=0;i<num;i++) scanf("%lf%lf",&point[i].x,&point[i].y); for(i=0;i<num;i++) for(j=0;j<num;j++) { temp=abs(point[i].x-point[j].x)*abs(point[i].x-point[j].x)+abs(point[i].y-point[j].y)*abs(point[i].y-point[j].y); length=sqrt(temp); if(10-length>0.00001||length-1000>0.00001) map[i][j]=map[j][i]=inf; else map[i][j]=map[j][i]=length; } ans=prim(num); if(ans>=inf) printf("oh!\n"); else printf("%.1lf\n",ans*100); } return 0; } |