题目链接
https://vjudge.net/problem/POJ-3154
题目
Programming contests became so popular in the year 2397 that the governor of New Earck — the largest human-inhabited planet of the galaxy — opened a special Alley of Contestant Memories (ACM) at the local graveyard. The ACM encircles a green park, and holds the holographic statues of famous contestants placed equidistantly along the park perimeter. The alley has to be renewed from time to time when a new group of memorials arrives.
When new memorials are added, the exact place for each can be selected arbitrarily along the ACM, but the equidistant disposition must be maintained by moving some of the old statues along the alley.
Surprisingly, humans are still quite superstitious in 24th century: the graveyard keepers believe the holograms are holding dead people souls, and thus always try to renew the ACM with minimal possible movements of existing statues (besides, the holographic equipment is very heavy). Statues are moved along the park perimeter. Your work is to find a renewal plan which minimizes the sum of travel distances of all statues. Installation of a new hologram adds no distance penalty, so choose the places for newcomers wisely!
Input
Input file contains two integer numbers: n — the number of holographic statues initially located at the ACM, and m — the number of statues to be added (2 ≤ n ≤ 1000, 1 ≤ m ≤ 1000). The length of the alley along the park perimeter is exactly 10 000 feet.
Output
Write a single real number to the output file — the minimal sum of travel distances of all statues (in feet). The answer must be precise to at least 4 digits after decimal point.
Sample Input
sample input #1
2 1
sample input #2
2 3
sample input #3
3 1
sample input #4
10 10
Sample Output
sample output #1
1666.6667
sample output #2
1000.0
sample output #3
1666.6667
sample output #4
0.0
题意
在一个周长为10000的圆上等距分布着n个雕塑。现在又有m个新雕塑加入(位置可随意放),希望所有n+m个雕塑在圆周上均匀分布。这就需要移动一些原有的雕塑。要求n个雕塑移动的总距离尽量小。
题解
(1)构造一个数组a,用来存放n+m个雕塑的最终坐标(离散化处理后)。
a[i]=0, i=0;
a[i]=a[i-1]+1/(n+m), i>0.
(2)对原n个雕塑的坐标t,在a中找一个距离t最小的元素。用STL中lower_bound处理,pos=lower_bound(a,a+n+m,t)-a;则距t最小的元素为a[pos]或a[pos-1]。
(3)因为一个位置只能放一个雕塑,所以引入一个vis数组来判断该位置是否已被占用。
如果pos号被占用,则pos++;
如果pos-1号被占用,则pos-1- -。
(4)累加每一个t与距离t最小的位置与t的距离。
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn=2e3+100;
double a[maxn],t;
int n,m,vis[maxn];
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(a,0,sizeof(a));
memset(vis,0,sizeof(vis));
double ans=0.0;
double ave=1.0/(n+m)*10000;
for(int i=1;i<(n+m);i++)
a[i]=a[i-1]+ave;
t=0;
ave=1.0/n*10000;
for(int i=1;i<n;i++)
{
t+=ave;
int pos=lower_bound(a,a+n+m,t)-a;
int r=pos;
int l=pos-1;
while(vis[r]) r=(r+1)%(n+m);
while(vis[l]) l=(l-1)%(n+m);
if(fabs(t-a[l])<fabs(t-a[r]))
{
ans+=fabs(t-a[l]);
vis[l]=1;
}
else
{
ans+=fabs(t-a[r]);
vis[r]=1;
}
}
printf("%.4lf\n",ans);
}
return 0;
}