当前位置:网站首页>7-1 range of numbers

7-1 range of numbers

2022-06-26 13:23:00 White -

7-1 The range of numbers

Given a length in ascending order is n Array of integers for , as well as q A query .

For each query , Returns an element k Starting and ending positions of ( Location slave 0 Start counting ).

If the element does not exist in the array , Then return to -1 -1.

Input format :
The first line contains integers n and q, Represents the length of the array and the number of queries .

The second line contains n It's an integer ( Both in 1∼10000 Within the scope of ), Represents a complete array .

Next q That's ok , Each line contains an integer k, Represents a query element .

1≤n≤100000

1≤q≤10000

1≤k≤10000

Output format :
common q That's ok , Each line contains two integers , Represents the starting and ending positions of the desired element .

If the element does not exist in the array , Then return to -1 -1.

sample input :
Here's a set of inputs . for example :

6 3
1 2 2 3 3 4
3
4
5

sample output :
Here is the corresponding output . for example :

3 4
5 5
-1 -1

Code :

#include <stdio.h>
#include <stdlib.h>
int n,q;
int x;
int a[100010];
int start,end;
void findsande(int mid)
{
    
    int start=mid,end=mid;
    for(int i=mid;i>=0;i--)
    {
    
        if(a[i]!=x)
        {
    
            start=i+1;
            break;
        }
    }
    for(int i=mid;i<=n-1;i++)
    {
    
        if(a[i]!=x)
        {
    
            end=i-1;
            break;
        }
    }
    printf("%d %d\n",start,end);
}
int find(int left,int right)
{
    
    if(left>right)
        return -1;
    int mid=(left+right)/2;
    if(a[mid]==x)
    {
    
         findsande(mid);
         return 1;
    }
    else if(x>a[mid])
        find(mid+1,right);
    else
        find(left,mid-1);
}
int main()
{
    
    scanf("%d%d",&n,&q);
    for(int i=0;i<n;i++)
    {
    
        scanf("%d",&a[i]);
    }
    for(int i=0;i<q;i++)
    {
    
        scanf("%d",&x);
        if(find(0,n-1)==-1)
            printf("-1 -1\n");
    }
    return 0;
}

202206260911 Japan

原网站

版权声明
本文为[White -]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261124055938.html