二分练习

Description

给你一个序列,然后给你m个元素,让你从序列中找出与每个元素最接近的数字输出来,如果有两个就输出两个。

Input

 多组输入,第一行给你两个数n(0 < n < 10000000),m(0 < m < n),接下来是数列的n个数,然后再输入m个元素,让你找出最接近每个元素的值。如果有两个,按从小到大输出。

Output

 这m个数分别输出最接近每个元素的值,组与组之间输出一个空行。

Sample

Input 

8 4

1 2 3 4 5 6 8 11

4

9

2

7

Output 

4

8

2

6 8

Hint

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>

using namespace std;

int n,m,a[10000001];

void Search(int p)
{
    int l=0,r=n-1,m;
    if(p<=a[l])
        printf("%d\n",a[l]);
    else if(p>=a[r])
        printf("%d\n",a[r]);
    else
    {
        while(l<r)
        {
            m=(l+r)/2;
            if(a[m]>=p)
                r=m;
            else
                l=m+1;
        }
        if(a[l]==p)
        {
            printf("%d\n",p);
            return ;
        }
        else if(a[l]>p)
            l--;
        int ld=p-a[l];
        int rd=a[l+1]-p;
        if(ld==rd)
            printf("%d %d\n",a[l],a[l+1]);
        else if(ld<rd)
            printf("%d\n",a[l]);
        else printf("%d\n",a[l+1]);
    }
}

int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for(int i=0; i<n; i++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        while(m--)
        {
            int p;
            scanf("%d",&p);
            Search(p);
        }
        printf("\n");
    }
    return 0;
}
发布了108 篇原创文章 · 获赞 3 · 访问量 2566

猜你喜欢

转载自blog.csdn.net/weixin_43307431/article/details/104592555