hiho#1128 : 二分·二分查找
input
1<=n<=1e6 1<=k<=2*1e9
a1 a2 ... an 1<=an<=2*1e9
output
k存在则输出k是第几大的数,否则输出-1
做法,从两端开始找到中间,把比b大的和比b小的交换
1 #include <cstdio> 2 #include <queue> 3 #include <cstring> 4 #include <iostream> 5 #include <cstdlib> 6 #include <algorithm> 7 #include <vector> 8 #include <map> 9 #include <set> 10 #include <ctime> 11 #include <cmath> 12 13 using namespace std; 14 15 const int N=1e6; 16 int a[N+10],n,b; 17 18 int main() 19 { 20 //freopen("/home/user/桌面/in","r",stdin); 21 while(scanf("%d%d",&n,&b)==2) 22 { 23 for(int i=0;i<n;i++) 24 scanf("%d",&a[i]); 25 int i=0,j=n-1,find=0; 26 while(1) 27 { 28 for(;i<j;i++) 29 if(a[i]>=b) break; 30 for(;j>i;j--) 31 if(a[j]<b) break; 32 else if(a[j]==b) find=1;//else少了会WA 33 if(a[i]==b) find=1; 34 if(i>=j) break; 35 swap(a[i],a[j]); 36 } 37 find?printf("%d\n",i+1):puts("-1"); 38 } 39 //printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC); 40 return 0; 41 }