题目:这里
题意:一条数轴上,有n个城市和m个塔,分别给出城市的位置和塔的位置,每个塔有个覆盖范围,问能将所有城市都覆盖的塔的最小范围是多少,一个城市只要被至少一个塔
覆盖就行。
可以利用贪心的思想模拟一下,注意一下细节就行,也可以二分。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std; typedef long long ll;
const int M = 1e5 + ;
int a[M],b[M];
ll max(ll x,ll y){return x>y?x:y;} int main()
{
int n,m;
scanf("%d%d",&n,&m);
for (int i= ; i<=n ; i++) scanf("%d",&a[i]);
for (int i= ; i<=m ; i++) scanf("%d",&b[i]);
if (a[]>=b[m])
{
printf("%I64d\n",(ll)(a[n]-b[m]));
return ;
}
if (b[]>=a[n])
{
printf("%I64d\n",(ll)(b[]-a[]));
return ;
}
int j=;ll ans=;
for (int i= ; ; i++)
{
bool flag=false;
if (i>m) i=m;
while (i!=&&abs(a[j]-b[i])>=abs(a[j]-b[i-])&&j<=n)
j++,flag=true;
if (flag) ans=max(ans,abs(a[j-]-b[i-]));
if (j==n+) break;
ll dis=abs(b[i]-a[j]);
while (abs(b[i]-a[j])<=dis&&i<=m)
dis=abs(b[i]-a[j]),i++;
i--;
while (abs(a[j]-b[i])<=dis&&j<=n)
j++;
ans=max(ans,dis);
//cout<<ans<<endl;
if (j==n+) break;
}
printf("%I64d\n",ans);
return ;
}
二分
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std; typedef long long ll;
const int M = 1e5 + ;
ll a[M],b[M],n,m;
ll max(ll x,ll y){return x>y?x:y;} bool judge(ll x)
{
int j=;
for (int i= ; i<=m ; i++)
{
while (a[j]>=b[i]-x&&a[j]<=b[i]+x&&j<=n)
j++;
if (j==n+) return true;
}
return false;
} ll sreach ()
{
ll l=,r=3e9,ans=;
while (l<=r)
{
ll mid=(l+r)/;
if (judge(mid)) ans=mid,r=mid-;
else l=mid+;
}
return ans;
} int main()
{
scanf("%d%d",&n,&m);
for (int i= ; i<=n ; i++) scanf("%I64d",&a[i]);
for (int i= ; i<=m ; i++) scanf("%I64d",&b[i]);
if (a[]>=b[m])
{
printf("%I64d\n",(ll)(a[n]-b[m]));
return ;
}
if (b[]>=a[n])
{
printf("%I64d\n",(ll)(b[]-a[]));
return ;
} printf("%I64d\n",sreach());
return ;
}