POJ2728 最优比例生成树裸题
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <stack> using namespace std; #define N 1010 #define For(i,j,n) for(int i=j;i<=n;i++) double dis[N][N] ,cost[N][N] ,n ,x[N] ,y[N] ,z[N] ,d[N] ,dist[N]; double eps = 1e-5; bool vis[N]; template<class T> void read(T&num) { char CH; bool F=false; for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar()); for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar()); F && (num=-num); } double get_dis(int a, int b) { return sqrt((x[b]-x[a])*(x[b]-x[a]) + (y[b]-y[a])*(y[b]-y[a])); } void clear() { memset(vis , 0 ,sizeof(vis)); } bool check(double a) { clear(); double sum = 0.0; For(i ,1 ,n) d[i] = 100000000; For(i ,1 ,n) { d[i] = cost[1][i] - dis[1][i]*a; } double maxx; int k; vis[1] = 1; For(i ,2 ,n) { maxx = 100000000; For(j ,2 ,n) if(!vis[j]&&d[j] < maxx) { maxx = d[j]; k = j; } vis[k] = 1; For(j ,2 ,n) if(!vis[j]&&cost[k][j]-a*dis[k][j]<d[j]) d[j] = cost[k][j]-a*dis[k][j]; sum+=d[k]; } return sum>=0 ? true:false; } int main() { while(1) { read(n); if(n==0)break; For(i,1,n) { scanf("%lf%lf%lf",&x[i],&y[i],&z[i]); } For(i,1,n) For(j,i+1,n) { dis[i][j]=dis[j][i]=get_dis(i,j); cost[i][j]=cost[j][i]=abs(z[i]-z[j]); } double l=0.0,r=100.0; while(r-l>=eps) { double mid=(l+r)/2; if(check(mid))l=mid; else r=mid; } printf("%.3f\n",r); } return 0; }
河西,河东,穷少年