题目链接:http://poj.org/problem?id=2728
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 26878 | Accepted: 7459 |
Description
After days of study, he finally figured his plan out. He wanted the average cost of each mile of the channels to be minimized. In other words, the ratio of the overall cost of the channels to the total length must be minimized. He just needs to build the necessary channels to bring water to all the villages, which means there will be only one way to connect each village to the capital.
His engineers surveyed the country and recorded the position and altitude of each village. All the channels must go straight between two villages and be built horizontally. Since every two villages are at different altitudes, they concluded that each channel between two villages needed a vertical water lifter, which can lift water up or let water flow down. The length of the channel is the horizontal distance between the two villages. The cost of the channel is the height of the lifter. You should notice that each village is at a different altitude, and different channels can't share a lifter. Channels can intersect safely and no three villages are on the same line.
As King David's prime scientist and programmer, you are asked to find out the best solution to build the channels.
Input
Output
Sample Input
4
0 0 0
0 1 1
1 1 2
1 0 3
0
Sample Output
1.000
Source
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <set>
#define ms(a,b) memset((a),(b),sizeof((a)))
using namespace std;
typedef long long LL;
const double EPS = 1e-;
const int INF = 2e9;
const LL LNF = 2e18;
const int MAXN = 1e3+; int n;
double x[MAXN], y[MAXN], z[MAXN];
double dis[MAXN][MAXN], height[MAXN][MAXN], d[MAXN][MAXN];
//dis为两点间的距离, height为两点间的高度差。d[i][j] = height[i][j] - L*dis[i][j],作为图的边权。 bool vis[MAXN];
double cost[MAXN];
double prim()
{
ms(vis, );
for(int i = ; i<=n; i++)
cost[i] = d[][i];
vis[] = true; double sum = ;
for(int i = ; i<=n-; i++)
{
int k;
double minn = INF;
for(int j = ; j<=n; j++)
if(!vis[j] && minn>cost[j])
minn = cost[k=j]; vis[k] = true;
sum += cost[k]; //加上边权
for(int j = ; j<=n; j++)
if(!vis[j])
cost[j] = min(cost[j], d[k][j]);
}
return sum;
} bool test(double L)
{
for(int i = ; i<=n; i++)
for(int j = ; j<=n; j++)
d[i][j] = height[i][j]-L*dis[i][j]; return prim()>=;
} int main()
{
while(scanf("%d", &n) && n)
{
for(int i = ; i<=n; i++)
scanf("%lf%lf%lf", &x[i], &y[i], &z[i]); for(int i = ; i<=n; i++)
for(int j = ; j<=n; j++)
{
dis[i][j] = sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
height[i][j] = fabs(z[i]-z[j]);
} double l = , r = 100.0;
while(l+EPS<=r)
{
double mid = (l+r)/;
if(test(mid))
l = mid + EPS;
else
r = mid - EPS;
}
printf("%.3f\n", r);
}
}