二分练习

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<bits/stdc++.h>

using namespace std;

int a[10000000];

void bin_search(int n, int l, int r, int k)
{
   int mid = (l + r) / 2;
   while(l <= r)
   {
       if(a[mid] == k) break;
       else if(a[mid] > k)
           r = mid - 1;
       else
           l = mid + 1;
       mid = (l + r) / 2;
   }
   if(a[mid] == k) cout << k << endl;
   else if(k - a[mid] < a[mid + 1] - k) cout << a[mid] << endl;
   else if(k - a[mid] > a[mid + 1] - k) cout << a[mid + 1] << endl;
   else cout << a[mid] << " " << a[mid + 1] << endl;
}
int main()
{
   ios::sync_with_stdio(0);
   int n, m, k;
   while(cin >> n >> m)
   {
       for(int i = 0; i < n; i++)
           cin >> a[i];
           sort(a, a + n);
       while(m--)
       {
           cin >> k;
           if(k <= a[0]) cout << a[0] << endl;//对两种情况先处理
           else if(k >= a[n - 1]) cout << a[n - 1] << endl;
           else bin_search(n, 0, n - 1, k);
       }
       cout << endl;
   }
   return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值