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:
10 8
2 3 20 4 5 1 6 7 8 9
Sample Output:
8
一,注意点
1,本题要注意数组内的数值的范围是10^9,而p的范围也是10^9,所以两者相乘的范围是10^18,所以实参应当用long long进行强制类型转换。写法如下:
vir_ans = binary_search(arr, pos, N + 1,(long long)arr[pos] * p);
二,我的代码:
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long LL;
const int max_n = 100100;
int arr[max_n];
bool cmp(int a, int b) {
return a < b;
}
int binary_search(int A[], int left, int right, LL num) {
int mid;
while (left < right) {
mid = (left + right) / 2;
if (A[mid] > num) {
right = mid;
}
else {
left = mid + 1;
}
}
return left;
}
int main() {
int N = 0, p = 0;
int pos = 1, ans = 1, vir_ans = 1;
scanf("%d %d", &N, &p);
for (int i = 1; i <= N; i++) {
scanf("%d", &arr[i]);
}
sort(arr + 1, arr + N + 1, cmp);
while (N +1 - pos > ans) {
vir_ans = binary_search(arr, pos, N + 1,(long long)arr[pos] * p);
if (vir_ans - pos > ans) {
ans = vir_ans - pos;
}
pos++;
}
printf("%d", ans);
return 0;
}