1085 Perfect Sequence (25 分)
Given a sequence of positive integers and another positive integer p. The sequence is said to be a perfect sequence if M≤m×p where M and m are the maximum and minimum numbers in the sequence, respectively.
Now given a sequence and a parameter p, you are supposed to find from the sequence as many numbers as possible to form a perfect subsequence.
Input Specification:
Each input file contains one test case. For each case, the first line contains two positive integers N and p, where N (≤105) is the number of integers in the sequence, and p (≤109) is the parameter. In the second line there are N positive integers, each is no greater than 109.
Output Specification:
For each test case, print in one line the maximum number of integers that can be chosen to form a perfect subsequence.
Sample Input:
Sample Output:
还熟悉二分的写法就很简单,不要怕,暴力基础上做一点优化即可。 若记得api upper_bound就更简单了
手写:
API:
思路没错,分析得也对,a[i]*p->a[j] a[j]是第一个大于p*a[i]的数(中间都小于等于) j-i就是答案
直接二重循环肯定超时,10^5*10^5
二分的话可以 n*logn=5*10^5 不会超时
二分其实也很简单,每次寻找a[j]的代码换用二分法查找即可记住upper_bound(a,a+n,val) a[0~n-1]范围内(其实是[a,a+n)) 第一个大于val的位置指针 返回值-a就是下标
lower_bound(a,a+n,val) 同上,不过找的是第一个大于等于val的位置,返回值后面可能有等于val的,但没有大于val的
two pointer做法 也很妙,每次保证i,j的距离最大 j能加就j++。i不到万不得已不i++ 时间复杂度O(N)更短