Cf Edu 15 C 城市与信号塔[二分]

本文介绍了如何使用C++解决Codeforces上的一道编程问题,即找到覆盖所有城市的最小信号塔覆盖范围。通过二分查找策略,确定每个城市与最近信号塔的距离,并确保所有城市都在覆盖范围内。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目连接

http://codeforces.com/contest/702/problem/C

Description

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.

Sample Input

5 3
1 5 10 14 17
4 11 15

Sample Output

3

题意

一条直线上有城市和信号塔,保证每个城市都能接受到信号,每个城市与最近的信号塔距离为d,求出最小的ansd,保证所有的城市与最近的信号塔距离都是小于等于ansd的。

题解

对信号塔的位置进行二分,求出与每一个城市最近的信号塔,取其中的最大值,注意特判当信号塔数为1时,取该塔与最左与最右的较大值。

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn=100005;
int a[maxn];
int b[maxn];
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(int i=0;i<m;i++)
    {
        scanf("%d",&b[i]);
    }
    int ans=0;
    if(m==1){printf("%d",max(abs(a[0]-b[0]),abs(b[0]-a[n-1])));return 0;}
    for(int i=0;i<n;i++)
    {
        int le,ri,mi,tt;
        le=0;ri=m-1;

        while(le<ri)
        {
            mi=(le+ri)/2;
            tt=abs(a[i]-b[mi]);
            if(b[mi]>a[i])ri=mi;
            else le=mi;
            if(abs(le-ri)==1)
            {
                tt=min(abs(a[i]-b[le]),abs(a[i]-b[ri]));
                break;
            }
        }
        ans=max(ans,tt);
    }
    printf("%d\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值