CodeForces

来源:互联网 发布:数据分析python 编辑:程序博客网 时间:2024/06/09 16:51

* Cellular Network*
C. Cellular Network
time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.

Input
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.

Output
Print minimal r so that each city will be covered by cellular network.

Examples
input
3 2
-2 2 4
-3 0
output
4
input
5 3
1 5 10 14 17
4 11 15
output
3

题目大意:n个城市,m个塔,要求求出塔的最短辐射半径,使城市都被覆盖到,这题是在x轴上的,所以不是很复杂。网上大多都是用二分做,奈何我二分很菜。。如果不用lower_bound的话自己写的代码怎么也过不了。这里提供一种枚举城市,然后遍历一遍塔的方法。

解题思路:先对塔和城市位置进行排序,然后判断城市的位置是否在第一个塔的左侧或者最后一个塔的右侧,若不是,则从左到右遍历塔,找到一对能把当前城市“包住”的相邻的两个塔。

重点是:在遍历塔的时候,因为是有序的,所以数组的下角标不用更新,这样就能保证时间复杂度只有n*m

#include <iostream>#include <cstdio>#include <algorithm>#include <cmath>using namespace std;const int maxn = 1e5 + 10;int n, m;long long a[maxn], b[maxn];int main(){    long long dis, ans = -1;    scanf("%d%d", &n, &m);    for(int i = 0; i < n; i++)    {        scanf("%lld", a+i);    }    sort(a, a+n);    for(int i = 0; i < m; i++)    {        scanf("%lld", b+i);    }    sort(b, b+m);    int j = 0;    for(int i = 0; i < n; i++)    {        if(a[i]<=b[0])            ans = max(ans, b[0]-a[i]);        else if(a[i]>=b[m-1])            ans = max(ans, a[i]-b[m-1]);        else        {            while(!(b[j]<=a[i] && b[j+1]>=a[i]))                j++;            dis = min(a[i]-b[j], b[j+1]-a[i]);            ans = max(dis, ans);        }    }    printf("%lld\n", ans);    return 0;}
原创粉丝点击