Binary Search
f679
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,q;
cin>>n>>q;
int num[500000]={0};
for(int i=0;i<n;i++)
cin>>num[i];
}
while(cin>>q)
{
int first=0,last=n,mid;
bool out=false;
while(first<=last)
{
mid=(first+last)/2;
if(num[mid]<q)
first=mid+1;
else if(num[mid]>q)
last=mid-1;
else if(num[mid]==q)
{
cout<<"Yes\n";
out=true;
break;
}
}
if(out==false)
cout<<"No\n";
}
h084
5 3 7 5 1 7 5 3 8 4
5 3 7 5 1 7 5 3 8 4
5 3 7 5 1 7 5 3 8 4
#include<bits/stdc++.h>
using namespace std;
int n,k;//圍牆數 海報數
int high[200000],wide[5000];//圍牆高度 海報寬度
bool check(int h)
{
queue<int> q;
int count=0;
for(int i=0;i<n;i++)
{
if(high[i]>=h)
count++;
else
{
if(count!=0)
{
q.push(count);
count=0;
}
}
}
}
if(count!=0)
q.push(count);
int qs=q.size();
count=0;
for(int i=0;i<k;i++)
{
while(!q.empty()&&q.front()<wide[i])
q.pop();
if(!q.empty())
{
q.front()-=wide[i];
if(q.front()==0)
q.pop();
count++;
}
}
return(count==k);
int main()
{
cin>>n>>k;
int max=0;
for(int i=0;i<n;i++)
{
cin>>high[i];
if(high[i]>max)
max=high[i];
}
for(int i=0;i<k;i++)
cin>>wide[i];
int r=0,l=max,mid;
}
while(r<=l)
{
if(r==l)
{
mid=l;
break;
}
if(r+1==l)
{
if(check(l))
mid=l;
else
mid=r;
break;
}
mid=(r+l)/2;
if(check(mid))//如果海報可以貼上
r=mid;
else
l=mid-1;
}
cout<<mid<<endl;
return 0;