1. 程式人生 > 其它 >PAT (Advanced Level) Practice 1085 Perfect Sequence (25 分) 凌宸1642

PAT (Advanced Level) Practice 1085 Perfect Sequence (25 分) 凌宸1642

PAT (Advanced Level) Practice 1085 Perfect Sequence (25 分) 凌宸1642

題目描述:

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.

譯:給定一個正整數序列和另一個正整數 p。如果滿足 M ≤ m × p , 其中 M 和 m 分別為這個序列中的最大值和最小值,則這個序列稱為完美序列。

現在給定一個序列和引數 p ,你應該儘可能多找出能夠組成完美序列的數字。


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.

譯:每個輸入檔案包含一個測試。對於每個用例,在第一行中給出兩個正整數 N 和 p , N (≤105) 是序列包含的數字個數, p (≤109) 是引數。在第二行中給出 N 個正整數,並且都不超過 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

The Idea:

首先對 N 個數字進行從小到大排序,然後從左到右遍歷,以左邊為最小值,找到滿足要求的最大值的位置,即可確定此時的完美序列的長度。當遍歷完整個數字,即可找到最大的完美序列長度。

The Codes:

#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
ll n , p , ans = 0 ;
int main(){
	cin >> n >> p ;
	ll v[n] ;
	for(int i = 0 ; i < n ; i ++) cin >> v[i] ; 
	sort(v , v + n) ;
	for(int i = 0 ; i < n ; i ++){
		ans = max(ans , (ll)(upper_bound(v, v + n , v[i] * p) - v) - i ) ; // 利用 upper_bound()函式找到當前滿足要求得最大值的位置
	}
	cout << ans  <<endl ; 
	return 0 ;
}