原文地址:zoj problem set - 2029the intervals-二分查找实例作者:我为音乐强说词the intervals time limit: 1 second memory limit:  kb cantor, the famo s mathematician, was working on a problem abo t intervals. let s start from a line segment of nit length. remove its middle 13. now remove the middle 13 s from the remaining two segments. now remove the middle 13 s from the remaining fo r segments. now remove the middle 13 s from the remaining eight segments. now remove ... well, yo get the idea. if yo co ld contin e this proced re thro gh infinitely many steps, what wo ld yo have left? now he assigns the following task to yo . (he asked me to pass his assignment to yo last night.) given two arrays of n mbers {a(n)} and {b(m)}. for each b(i) in {b(m)}, find 2 n mbers a and b from {a(n)}, s ch that b(i) is in [a,b) and b-a=|b -a | for all a and b from {a(n)} s ch that [a ,b ) contains b(i). inp t there are several test cases. in each test case, the first line gives n and m. the second line contains n n mbers, which are the elements of {a(n)}. the third line contains m n bmers, which are the elements of {b(m)}. o tp t for each b(i) in {b(m)}, o tp t a line containing the interval [a,b). if there is no s ch interval, o tp t "no s ch interval" instead. print a blank line after each test case. sample inp t 3 3 10 20 30 15 25 35 sample o tp t [10,20) [20,30) no s ch interval 问题解析:要查找一个数在一个输串中的位置,明显用二分查找,这道题如果用顺序查找无法ac.因为存在一样的数 二分法比较一个数在输出数串中的位置,返回位置k; code: #incl destdio.h #incl dealgorithm sing namespace std; int m,n; int a[1000]; int find(int k) 二分查找.只不过这里将二分查找的范围扩大了,不只是找相等的 { int low=0,high=m;int mid; while(low=high) { m(low+high)2; if(k=a[mid]&&ka[mid+1]) ret rn mid; else if(ka[mid]) high=mid-1; else low=mid+1; } ret rn -1; } int main { register int i,j; int q; int c[1000]; int b[1000]; while(scanf("%d%d",&m,&n)!=eof) { for(i=0;im;i) scanf("%d",&a[i]); for(j=0;jn;j) scanf("%d",&b[j]); sort(a,a+m); for(j=0;jn;j) { q=0; q=find(b[j]); if(q==-1) printf("no s ch intervaln"); else printf("[%d,%d)n",a[q],a[q+1]); } printf("n"); } ret rn 0; } 顺便写一下顺序查找code int find2(int k) { int i=1; while(i=m&&a[i]k)i; if(im)ret rn -1; else ret rn i-1; } 请指教哦!