二分查找 (燕归来
1 3 5 10 11 20 27 50 80 88
956
二分查找
Problem:956
Time Limit:1000ms
Memory Limit:65536K
Description
有n(1<=n<=1000005)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请找出序列中第1个大于x的数的下标!
Input
输入数据包含多个测试实例,每组数据由两行组成,第一行是n和x,第二行是已经有序的n个整数的数列。
Output
对于每个测试实例,请找出序列中第1个大于x的数的下标!。
Sample Input
3 3
1 2 4
Sample Output
2
Hint
本题为多组数据,while(scanf("%d%d",&n,&m)!=-1)即可。
Source
upper_bound函数法(返回第一个大于的元素的下标)
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a[2000000],n,x;
while(cin>>n>>x)
{
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
int t=upper_bound(a+1,a+n+1,x)-a;
cout<<t-1<<endl;
}
return 0;
}
901
upper_bound(a,a+n,s2)-lower_bound(a,a+n,s1))
//308ms
#include <bits/stdc++.h>
using namespace std;
int i,n;
double a[100010],s1,s2;
int main()
{
ios::sync_with_stdio(false);
cin>>n;
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
while(cin>>s1>>s2)
printf("%d\n",upper_bound(a,a+n,s2)-lower_bound(a,a+n,s1));
return 0;
}
C++Copy
899
这也是裸的找
Problem:899
Time Limit:1000ms
Memory Limit:65536K
Description
我们现在都知道二分查找的主体是一个while循环,在每次循环里面进行询问,从而决定是找到了数据停止循环还是改变查找区间的范围。现在就是考验大家是否理解了原理的时候了!
运用二分查找在序列{1,2,3,……,n}中找到k需要循环多少次?
Input
输入多组数据, 每组输入两个整数n和k,占一行(0<= k <= n)。n为32位整数
Output
对每组输入,输出在序列{1,2,3,……,n}中找到k的循环次数。
Sample Input
5 2
5 1
10 3
Sample Output
3
2
3
Hint
Source
手写二分法
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int n,k,l,r,m,ans;
while(cin>>n>>k)
{
ans=0;l=1,r=n;
while(l<=r)
{
ans++;
m=l+(r-l)/2;
if(m>k)r=m-1;
if(m==k)break;
if(m<k)l=m+1;
}
printf("%d\n",ans);
}
return 0;
}
递归
自己调用自己
边界条件:确定递归何时终止
递归模式:大问题是如何分解成小问题的
递归要用栈来进行
fibnacci–递归版
Problem:1762
Time Limit:1000ms
Memory Limit:65535K
Description
已知数列 1 1 2 3 5 8 13
Input
计算第n项的值 (1<=n<=15)
Output
输出题意
Sample Input
3
Sample Output
2
Hint
Source
不够大,可以递归
#include <bits/stdc++.h>
using namespace std;
int f(int n)
{
if(n==1)
{
return 1;
}
if(n==2)
{
return 1;
}
return f(n-1)+f(n-2);
}
int main()
{
int n;
while(cin>>n)
{
cout<<f(n)<<endl;
}
return 0;
}
幂次方-递归
Problem:1754
Time Limit:1000ms
Memory Limit:65535K
Description
任何一个正整数都可以用2的幂次方表示。例如
137=27+23+2^0
由此可知,137可表示为:
2(7)+2(3)+2(0)
而7又可以表示为:2(2)+2+2(0)
3可以表示为:2+2(0)
因此137最终表示为:
2(2(2)+2+2(0))+2(2+2(0))+2(0)
Input
一个正整数n(n≤20000)。
Output
符合约定的n的0,2表示(在表示中不能有空格)
Sample Input
1315
Sample Output
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
Hint
Source
洛古
本文探讨了二分查找算法在不同场景下的应用,包括在有序数组中寻找第一个大于特定值的元素,以及如何使用C++实现。通过示例代码展示了如何利用`upper_bound`函数进行高效查找,并讨论了递归在二分查找中的作用。此外,还提到了二分查找在解决数列查找问题中的效率和循环次数计算。
1万+

被折叠的 条评论
为什么被折叠?



