二分练习

来源:互联网 发布:ubuntu 16.04 下载 编辑:程序博客网 时间:2024/05/16 11:20

Home

ContestsProblemsRanklistStatus16110572096Logout

二分练习
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
给你一个序列,然后给你m个元素,让你从序列中找出与每个元素最接近的数字输出来,如果有两个就输出两个。

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

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

8 4
1 2 3 4 5 6 8 11
4
9
2
7

Example Output

4
8
2
6 8

Hint

Author
lwn
SDUTACM运维技术中心
Copyright © 2013-2014 SDUTACM Team. All Rights Reserved.
2017/2/22 下午10:55:43

#include <stdio.h>#include <stdio.h>#include <algorithm>#include <string.h>using namespace std;int a[10000000]= {0}; /// 储存 数字出现的个数int cmd(int a,int b)///递增{    return a<b;}int find (int left,int right,int key)///二分查找{    while(left<=right)    {        int mid=(left+right)/2;        if(a[mid]==key)return mid;        else if(a[mid]<key)left=mid+1;        else right=mid-1;    }    return -1;}int main(){    int n,m;    while(~scanf("%d%d",&n,&m))    {        for(int i=0; i<n; i++)        {            scanf("%d",&a[i]);        }        sort(a,a+n,cmd);/// 快排        while(m--)        {            int key;            scanf("%d",&key);            int t=find(0,n-1,key);            if(t!=-1)///找到该数据            {                printf("%d\n",key);            }            else ///未找到 查找 与给数字相近的值            {                for(int i=1;; i++) /// i 便是 "相近的值"与 key的差值                {                    int flag=0;///标记是否 已经被找到                    int t1=key-i;///左边的差值                    int t=find(0,n-1,t1);                    if(t!=-1)                    {                        printf("%d",t1);                        flag++;                    }                    int t2=key+i;///右边的差值                    t=find(0,n-1,t2);                    if(t!=-1)                    {                        if(flag)printf(" ");                        flag++;                        printf("%d",t2);                    }                    if(flag)                    {                        printf("\n");                        break;                    }                }            }        }        printf("\n");/// 组与组之间有一个空行    }    return 0;}
0 0
原创粉丝点击