您的位置:首页 > 其它

Codeforces Gym 101246J Buoys

2017-08-10 21:33 295 查看
题意为: 给定一个长度为n的序列,要求使得其间距相等,最短的总移动距离。

首先我们会发现这个间距过长或过短都会使得答案过大。那么便满足了三分的条件。

这时我们来考虑三分策略,首先三分间距长度,三分后对于间距长度,枚举固定某一个点,计算偏差距离,

更新答案。

下附AC代码。

#include<iostream>
#include<stdio.h>
#define maxn 405
using namespace std;
int n,p;
double pos[maxn];
const double eps=1e-15;
double myabs(double now)
{
return now>=0 ? now : -now;
}
double cal(double now)
{
double res=0,ans=100000000;
for(int i=1;i<=n;i++)
{
res=0;
for(int j=1;j<i;j++)
{
res+=myabs(pos[i]-(i-j)*now-pos[j]);
}
for(int j=i+1;j<=n;j++)
{
res+=myabs(pos[i]+(j-i)*now-pos[j]);
}
if(ans>res)
{
ans=res;
p=i;
}
}
return ans;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%lf",&pos[i]);
double l=0,r=100000000;
while(myabs(r-l)>eps)
{
double mid1=(l+r)/2.0;
double mid2=(mid1+r)/2.0;
if(cal(mid1)>cal(mid2))
l=mid1;
else
r=mid2;
}
double ans=cal(l)>cal(r) ? r : l;
double res=cal(ans);

printf("%.4f\n",res);
for(int i=1;i<p;i++)
printf("%.10f ",pos[p]-(p-i)*ans);
printf("%.10f ",pos[p]);
for(int i=p+1;i<=n;i++)
printf("%.10f ",pos[p]+(i-p)*ans);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: