【PAT】A1085. Perfect Sequence(二分查找总结)
@(PAT)
链接:https://www.patest.cn/contests/pat-a-practise/1085
最近刷PAT遇到了二分法的部分,现在来总结一下二分查找。
思路:
题目说意思很简单,就是找到满足条件M <= m * p(M为子集最大值,m为子集的最小值)的最大子集,输出子集的大小。
思路就是将序列从小到大排序后,遍历序列,固定m的情况下使用二分查找法,找到满足条件的M(不使用二分查找会超时)。
My AC code:
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
int n, p, a[100001];
int binarySearch(int left, int right, long long c) {
if (a[n - 1] <= c) return n;
while (left <= right) {
int mid = (left + right) / 2;
if (a[mid] > c) {
right = mid - 1;
}
else if (a[mid] < c) {
left = mid + 1;
}
else {
return mid;
}
}
return left;
}
int main() {
scanf("%d%d", &n, &p);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
sort(a, a+ n);
int ans = 1;
for (int i = 0; i < n; i++) {
long long c = (long long)a[i] * p;
int j = binarySearch(i + 1, n - 1, c);
ans = max(ans, j - i);
}
printf("%d\n", ans);
return 0;
}
重点在于binarySearch函数,需要注意的地方是:
1. 二分查找的过程中,改变的是left和right两个index,mid是通过left和right计算得到的。
2. 二分查找的过程中,判断语句最好使用大于、小于和等于,等于的时候直接返回,思路清晰一些。
3. 对于这道题,当数组的最后一个数都小于c,就返回n。返回n的原因是n- i恰好是子序列的大小,比如大小为1的数组,i= 0,n= 1,子序列就为n- i= 1。
另外,在C++的库中,还有两个已经实现了的二分查找的函数:upper_bound和lower_bound,关于它们的用法:
http://www.cplusplus.com/reference/algorithm/upper_bound/
https://blog.youkuaiyun.com/u011008379/article/details/50725670
总结如下:
对于升序序列,在一个左闭右开的有序区间里进行二分查找:
- upper_bound:返回的是被查序列中第一个大于查找值的指针,也就是返回指向被查值>查找值的最小指针。即将第三个参数插入序列中,其最后能插入到数组中的位置。
- lower_bound:返回的是被查序列中第一个大于等于查找值的指针,也就是返回指向被查值>=查找值的最小指针。即将第三个参数插入序列中,其最前能插入到数组中的位置。
// default (1)
template <class ForwardIterator, class T>
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,
const T& val);
// custom (2)
template <class ForwardIterator, class T, class Compare>
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);
- 第一个参数:数组首地址
- 第二个参数:数组末尾的地址
- 第三个参数:需要查找的数
- 第四个参数:比较函数,不传默认数组从小到大排列。
所以这题可以使用upper_bound函数,其AC code如下:
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
int n, p, a[100001];
int main() {
scanf("%d%d", &n, &p);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
sort(a, a+ n);
int ans = 1;
for (int i = 0; i < n; i++) {
int j = upper_bound(a + i + 1, a + n, (long long)a[i] * p) - a;
ans = max(ans, j - i);
}
printf("%d\n", ans);
return 0;
}
特别注意的是,其返回的是地址,我们需要的是index,所以要将得到的结果减去数组的头地址,得到我们要的index。
希望能帮到你。