You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Print minimal r so that each city will be covered by cellular network.
3 2 -2 2 4 -3 0
4
5 3 1 5 10 14 17 4 11 15
3
那个题是贪心,这个看题知道是二分可是不知道怎么写,看了师父代码才明白,还是做题太少了!
题解:算出距每个城市最近的塔的距离,然后取这些距离的最大值就行了。找距离的时候用二分去查找
另外有一点,找到一个塔的坐标pos大于该城市,应该再看看塔的坐标小于该城市的那个塔距离是多少,而pos - 1就是坐标小于那个城市的塔的坐标。然后就又出现了一个新问题,如果找到的是 最后一个塔或者是第一个塔(他们后面和前面没有灯塔)的时候呢?这样赋值一下:b [ 0 ] = b [ 1 ] b [ m+ 1 ] = b [ m ]
#include<cstdio>
#include<cstring>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
int main()
{
int n,m;
int a[100010],b[100010];
while(~scanf("%d %d",&n,&m))
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=m;i++)
scanf("%d",&b[i]);
b[0]=b[1]; //第一个灯塔前面赋一个一样的值
b[m+1]=b[m]; //最后一个灯塔后也是附一个和它一样的值
int dis,ans=0;
for(int i=1;i<=n;i++)
{
int t=lower_bound(b+1,b+1+m,a[i])-b; //找到在a[i]那个点前一个或者就在a[i]上的灯塔
dis=min(abs(b[t]-a[i]),abs(b[t-1]-a[i])); //取a[i]前一个灯塔和后一个灯塔到他距离的最小值
ans=max(ans,dis); //取所有满足的最大值
}
printf("%d\n",ans);
}
return 0;
}