2420题意:给出平面中一些点,求平面中的一个点,使得这个点到其他所有点的距离之和最短(这个点叫作费马点),并输出这个距离和。
1379题意:背景和2420相同,只是求一个坐标到其他所有点的最短距离最大。
思路:先随机取个点,再取一个步长,朝4个方向走。如果新位置到各点距离比原来小,就走过去;直到当前位置比四周都好,此时缩小步长。如此迭代,直到步长小于题目的精度(这道题是0.1)输出即可。实际上缩小步长蕴含了模拟退火的思想。不过模拟退火中还可以按照一定概率留在原地(即使移动可以获得更好的效益值)。
朝四个方向走可以改为朝四周所有方向走,(http://www.2cto.com/kf/201409/334851.html)采用的是这种方法。
while(L > EPS) {
double alpha = 2 * PI * Rand();//一个随机的角度
Point temp(now.x + cos(alpha) * T,now.y + sin(alpha) * T);
dE = Statistic(now) - Statistic(temp);
if(dE >= 0 || exp(dE / L) > Rand)
now = temp;
L *= .99;
}
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define N 105
struct point{
double x,y;
}s[N],now,tmp;
int n;
int ori[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
double dd(struct point a,struct point b){
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
double getdis(struct point now){
int i;
double res=0;
for(i = 0;i<n;i++)
res += dd(s[i],now);
return res;
}
int main(){
int i;
double j,left,right,up,down,diff,dis;
left = down = 10000;
right = up = 0;
scanf("%d",&n);
for(i = 0;i<n;i++){
scanf("%lf %lf",&s[i].x,&s[i].y);
left = min(left,s[i].x);
right = max(right, s[i].x);
up = max(up, s[i].y);
down = min(down, s[i].y);
}
now.x = (left+right)/2;//随机取个点,尽量往中间取
now.y = (up+down)/2;
diff = max(right-left,up-down) / 2;//取一个步长
dis = getdis(now);
while(diff > 0.1){
for(i = 0;i<4;i++){
tmp.x = now.x + ori[i][0]*diff;
tmp.y = now.y + ori[i][1]*diff;
if((j=getdis(tmp)) < dis){//如果四周优于当前点就走过去
now = tmp;
dis = j;
break;
}
}
if(i==4)//减小步长
diff *= 0.5;
}
printf("%.0f\n",dis);
return 0;
}
1379代码:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <ctime>
#include <cstdlib>
#define clr(s,t) memset(s,t,sizeof(s))
using namespace std;
#define INF 0x3fffffff
struct point{
double x,y;
}p[1005],res,now,tmp;
int n,m,h,T;
int ori[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
int check(double x,double y){
return x>=0 && y>=0 && x<=n && y<=m;
}
double dd(point a,point b){
return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y);
}
int dist(point a){
double res = 0x3fffffff;
for(int i = 1;i<=h;i++)
res = min(res,dd(a,p[i]));
return res;
}
int cmp(point a,point b){
if(a.x == b.x)
return a.y < b.y;
return a.x < b.x;
}
int eq(point a,point b){
return a.x==b.x && a.y==b.y;
}
int main(){
scanf("%d",&T);
srand((unsigned int)time(0));
while(T--){
int i,j,k;
double off;
res.x = res.y = 0;
scanf("%d %d %d",&n,&m,&h);
for(i = 1;i<=h;i++)
scanf("%lf %lf",&p[i].x,&p[i].y);
sort(p+1, p+1+h, cmp);
h = unique(p+1, p+1+h, eq)-p-1;
for(k = 1;k<=20;k++){//多取几次初始点可以增大AC概率
now.x = rand()%n;
now.y = rand()%m;
for(off = min(m,n);off>=0.001;){
for(j = 0;j<4;j++){
tmp.x = now.x+ori[j][0]*off;
tmp.y = now.y+ori[j][1]*off;
if(check(tmp.x,tmp.y) && dist(tmp)>dist(now)){
now = tmp;
break;
}
}
if(j==4)
off /= 2;
}
if(dist(res) < dist(now))
res = now;
}
printf("The safest point is (%.1lf, %.1lf).\n",res.x,res.y);
}
return 0;
}