Binary search related questions

Question A: Find x

http://codeup.cn/problem.php?cid=100000585&pid=0
Insert picture description here
Insert picture description here

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int solve(int left,int right,int x,int a[])
{
    
    
	int mid;
	while(left<=right)
	{
    
    
		mid=(left+right)/2;
		if(a[mid]==x)
			return mid;
		if(a[mid]>x)
		{
    
    
			right=mid-1;
		}
		else
		{
    
    
			left=mid+1;
		}
	}
	return -1;
}
int main(void)
{
    
    
	int n;
	while(cin>>n)
	{
    
    
		int a[205];
		for(int i=0;i<n;i++)
		{
    
    
			cin>>a[i];
		}
		sort(a,a+n);
		int x;
		cin>>x;
		printf("%d\n",solve(0,n-1,x,a));
	}
	return 0;
}

Question B: Print the subscripts of extreme points

http://codeup.cn/problem.php?cid=100000585&pid=1
Insert picture description here
Insert picture description here
Idea:
First look at the difference between the first and second ones. If they are not equal, output the subscripts and
see the middle part traverse one by one. If there is one to the left of a number If the number and the right one are not larger or smaller than this number, the current subscript is output.
Then, if the last one is not equal to the second one, the subscript will be output.

#include<iostream>
#include<cstdio>
using namespace std;
int main(void)
{
    
    
	int n;
	int N;
	while( scanf("%d",&n) != EOF)
	{
    
    
		for(int i=0;i<n;i++)
		{
    
    
			cin>>N;
			int a[85]={
    
    0};
			for(int i=0;i<N;i++)
				scanf("%d",&a[i]);
			if(a[0]!=a[1])
				printf("0 ");
			for(int i=1;i<N-1;i++)
			{
    
    
				if( ( a[i]>a[i-1] && a[i]>a[i+1] ) ||  (a[i]<a[i-1] && a[i+1]>a[i] ) )
				{
    
    
					printf("%d ",i);
				}
			}
			if(a[N-1]!=a[N-2])
				printf("%d\n",N-1);
		}
	}
	return 0;
}

Problem C: Find

http://codeup.cn/problem.php?cid=100000585&pid=2

Insert picture description here
Insert picture description here

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
bool flag(int a[],int left,int right,int number)
{
    
    
	int mid;
	while(left<=right)
	{
    
    
		mid=(left+right)/2;
		if(a[mid]==number)
			return true;
		if(a[mid]>number)
		{
    
    
			right=mid-1;
		}
		else
		{
    
    
			left=mid+1;
		}
	}
	return false;
}
int main(void)
{
    
    
	int n,m;
	int i;
	int a[105];
	while(cin>>n)
	{
    
    
		for(i=0;i<n;i++)
			cin>>a[i];
		sort(a,a+n);
		cin>>m;
		for(i=0;i<m;i++)
		{
    
    
			int number;
			cin>>number;
			if(flag(a,0,n-1,number))
				printf("YES\n");
			else
				printf("NO\n");
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/114978292