查找
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+100;
int a[N],n,m,b[N],c[N];
int main()
{
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]);
for (int i = 1; i <= m; i++)
{
int x=b[i],l=1,r=n;
while(l<r)
{
int mid=l+r>>1;
if(a[mid]>=x)
r=mid;
else
l=mid+1;
}
if(a[l]!=x)
c[i]=-1;
else
c[i]=l;
}
for (int i = 1; i <= m; i++)
printf("%d ",c[i]);
return 0;
}
l+r>>1相当于(l+r)/2,用二分法可以节省时间
进击的奶牛
#include <bits/stdc++.h>
using namespace std;
int A[1000010];
int n,c;
bool check(int x){
int num=1;
int a=A[0];
for(int i=1;i<n;i++){
if(A[i]-a>=x) a=A[i],num++;//num来计算在此时的最大距离mid下能放几只奶牛
if(num>=c) return true;//如果此时放的奶牛数大于等于我现有的奶牛,就返回true
}
return false;
}
int main(){
cin>>n>>c;
for(int i=0;i<n;i++){
cin>>A[i];
}
sort(A,A+n);
int L=0,R=A[n-1]-A[0],ans=0;
while(L<=R){
int mid=(L+R)/2;
if(check(mid)) ans=mid,L=mid+1;//当mid满足题意时,把它存放在ans中,继续找有没有比此时的mid更大的最近距离
else R=mid-1;
}
cout<<ans;
return 0;
}
跳石头
#include <bits/stdc++.h>
#define N (50000+10)
using namespace std;
int a[N];
int d,n,m,ans;
bool judge(int x){
int tot=0,i=0,now=0;
while (i<n+1){
i++;
if (a[i]-a[now]<x){
tot++;
}
else{
now=i;
}
}
if (tot>m) return false;
else return true;
}
int main(){
scanf("%d%d%d",&d,&n,&m);
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
a[n+1]=d;
int l=1,r=d,mid;
while (l<=r){
mid=(l+r)/2;
if (judge(mid)){
ans=mid;
l=mid+1;
}
else r=mid-1;
}
printf("%d",ans);
}
判断跳跃距离与mid的大小,如果前者小,则tot++(移走一块石头),反之,继续判断下一步跳跃距离与mid大小,当跳到终点时,如果tot(移走石头数量)多于规定值,返回false,反之,返回true