codeforces 702C 二分查詢
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
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
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 a
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.
OutputPrint minimal r so that each city will be covered by cellular network.
ExamplesinputCopy3 2 -2 2 4 -3 0outputCopy
4inputCopy
5 3 1 5 10 14 17 4 11 15outputCopy
3
一道二分查詢的,訓練的時候瘋狂wa,沒有注意到二分查詢的範圍除了要判斷大於小於之外,還要判斷等於。另外,需要注意二分查詢的條件的l <= r。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
const int p = 100009;
typedef long long LL;
int a[p],b[p];
int main ()
{
int n,m;
scanf("%d%d",&n,&m);
int cnt;
for (int i = 0; i < n; i++) scanf("%d",&a[i]);
for (int i = 0; i < m; i++)scanf("%d",&b[i]);
cnt = 0;
if (m == 1){
cnt = max(abs(a[0]-b[0]),abs(a[n-1]-b[0]));
printf("%d\n",cnt);
return 0;
}
for (int i = 0; i < n; i++){
int l = 0,r = m-1;
int mid;
if (a[i] < b[0])
cnt = max(cnt,b[0]-a[i]);
else if (a[i] > b[m-1])
cnt= max(cnt,a[i]-b[m-1]);
else {
while (l <= r){
mid = (l+r)/2;
if (b[mid] < a[i])
l = mid+1;
else
r = mid-1;
}
if (abs(b[r] - a[i]) < abs(b[l] - a[i]))
cnt = max(cnt,abs(b[r]-a[i]));
else cnt = max(cnt,abs(b[l]-a[i]));
}
}
printf("%d\n",cnt);
}
/************************************************
┆ ┏┓ ┏┓ ┆
┆┏┛┻━━━┛┻┓ ┆
┆┃ ┃ ┆
┆┃ ━ ┃ ┆
┆┃ ┳┛ ┗┳ ┃ ┆
┆┃ ┃ ┆
┆┃ ┻ ┃ ┆
┆┗━┓ ┏━┛ ┆
┆ ┃ ┃ ┆
┆ ┃ ┗━━━┓ ┆
┆ ┃ AC代馬 ┣┓┆
┆ ┃ ┏┛┆
┆ ┗┓┓┏━┳┓┏┛ ┆
┆ ┃┫┫ ┃┫┫ ┆
┆ ┗┻┛ ┗┻┛ ┆
*