pat 1085. Perfect Sequence (25)

pat 1085. Perfect Sequence (25)
时间限制
300 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard
作者
CAO, Peng

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


这道题目,在时间上,就考察一个二分查找。还有就是一个long long因为乘法有可能超过int

[cpp] view plain copy print ?
  1. #include <stdio.h> 
  2. #include <vector> 
  3. #include <algorithm> 
  4. using namespace std; 
  5. vector<long long> nums; 
  6. int bSearch(long long num,int n) 
  7.     int l = 0,r = n-1,mid; 
  8.     while(l<=r) 
  9.     { 
  10.         mid = (l+r)/2; 
  11.         if(nums[mid]>num) 
  12.         { 
  13.             r = mid-1; 
  14.         }else if(nums[mid]<num) 
  15.         { 
  16.             l = mid+1; 
  17.         }else 
  18.         { 
  19.             return mid; 
  20.         } 
  21.     } 
  22.     return l; 
  23. int main() 
  24.     long long n,p,tmp1,m,index; 
  25.     long long i,j,tmpMax=0,resMax; 
  26.     scanf("%lld%lld",&n,&p); 
  27.     for(i=0;i<n;i++) 
  28.     { 
  29.         scanf("%lld",&tmp1); 
  30.         nums.push_back(tmp1); 
  31.     } 
  32.     sort(nums.begin(),nums.end()); 
  33.     for(i=0;i<n;i++) 
  34.     { 
  35.         m = nums[i]*p; 
  36.         index = bSearch(m, n); 
  37.         if(nums[n-1]<=m) 
  38.         { 
  39.             tmpMax = n-1-i+1; 
  40.         }else 
  41.         { 
  42.             tmpMax = index-i; 
  43.         } 
  44.         if(tmpMax>resMax) 
  45.         { 
  46.             resMax = tmpMax; 
  47.         } 
  48.     } 
  49.     printf("%lld\n",resMax); 
  50.     return 0; 


你可能感兴趣的:(pat 1085. Perfect Sequence (25))