poj 2420 A Star not a Tree?
阿新 • • 發佈:2019-01-27
題意:給出平面上N(<=100)個點,你需要找到一個這樣的點,使得這個點到N個點的距離之和儘可能小。輸出這個最小的距離和(四捨五入到最近的整數)
思路:三分求
三分演算法解決凸形或者凹形函式的極值;
二分解決具有單調性的函式的極值;
如下圖
mid = (l+r) / 2;
midmid = (r+mid) / 2;
求極大值
if(cal(mid)>cal(midmid)) r= midmid;
else l = mid;
求極小值
if(cal(mid)<cal(midmid)) r= midmid;
else l = mid;
/* **********************************************
Auther: xueaohui
Created Time: 2015-7-25 8:56:03
File Name : poj2420.cpp
*********************************************** */
#include <iostream>
#include <fstream>
#include <cstring>
#include <climits>
#include <deque>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <utility>
#include <sstream>
#include <complex>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <bitset>
#include <functional>
#include <algorithm>
using namespace std;
#define ll long long
#define N 111
int n;
struct node{
double x,y;
double dis(node a){
return sqrt((x-a.x)*(x-a.x)+(y-a.y)*(y-a.y));
}
}p[N];
double sum(double xx,double yy){
node a;
a.x = xx;
a.y = yy;
double d=0;
for(int i=1;i<=n;i++){
d+=a.dis(p[i]);
}
return d;
}
double cal(double xx){
double l = 0;
double r = 10000;
for(int i=1;i<=200;i++){
double mid = (l+r)/2;
double rmid = (mid+r)/2;
if(sum(xx,mid)<sum(xx,rmid)){
r = rmid;
}
else{
l = mid;
}
}
return sum(xx,l);
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%lf%lf",&p[i].x,&p[i].y);
}
double l = 0;
double r = 10000;
for(int i=1;i<=200;i++){
double mid = (l+r)/2;
double rmid = (mid+r)/2;
if(cal(mid)<cal(rmid)){
r = rmid;
}
else{
l = mid;
}
}
printf("%.0f\n",cal(l));
}