此题与跳石头一题很像,得用二分法去解。
二分查找符合的最小距离。
第一次代码wa了,没考虑到二分无法逼近到最初的最大值,后面把基站数为2的情况单独考虑后就ac了
附代码:
#include <bits/stdc++.h>
using namespace std;
int pl[100005];
int main()
{
int s,l;
while(scanf("%d%d",&s,&l)&&s!=0&&l!=0)
{
memset(pl,0,sizeof(pl));
for(int i=0;i<s;i++)
{
scanf("%d",&pl[i]);
}
sort(pl,pl+s);
int mint=1,maxt=pl[s-1]-pl[0];
if(l==2)
{
printf("%d\n",maxt);
}
else{
int t=(mint+maxt)/2;
while(t!=maxt&&t!=mint)
{
int jizhanshu=1;
int la=0,now=1;
while(now<=s-1)
{
if(pl[now]-pl[la]>=t)
{
jizhanshu++;
la=now;
now++;
}
else now++;
}
if(jizhanshu>=l)
{
mint=t;
t=(t+maxt)/2;
}
else if(jizhanshu<l)
{
maxt=t;
t=(t+mint)/2;
}
}
printf("%d\n",t);
}
}
return 0;
}