1030 完美數列 (25 分)
給定一個正整數數列,和正整數 p,設這個數列中的最大值是 M,最小值是 m,如果 M≤mp,則稱這個數列是完美數列。
現在給定參數 p 和一些正整數,請你從中選擇盡可能多的數構成一個完美數列。
輸入格式:
輸入第一行給出兩個正整數 N 和 p,其中 N(≤10?5??)是輸入的正整數的個數,p(≤10?9??)是給定的參數。第二行給出 N 個正整數,每個數不超過 10?9??。
輸出格式:
在一行中輸出最多可以選擇多少個數可以用它們組成一個完美數列。
輸入樣例:
10 8
2 3 20 4 5 1 6 7 8 9
輸出樣例:
8
思路
先對數列進行排序,然后枚舉左端點也就是最小值m,然后查找一個盡可能大的右端點M使得M<=m*p
,由于數列已經排序,所以可以使用二分查找。upper_bound()返回第一個大于待查找元素的數列元素的
下標,如果沒有找到,返回第n個元素(不存在),所以需要進行返回值判斷。
注意點是m*p會超過int。
code 1:手寫二分
#include<iostream> #include<string> #include<vector> #include<string> #include<cstdio> #include<cmath> #include<string.h> #include<algorithm> #include<unordered_map> #include<stack> using namespace std;int main() {int n,p;scanf("%d%d",&n,&p);long long int a[n];for(int i=0;i<n;i++)scanf("%lld",&a[i]);sort(a,a+n);int maxv=0;for(int i=0;i<n;i++){int left=i,right=n-1,ans=-1;while(left<=right){int mid=left+(right-left)/2;if(a[mid]<=a[i]*p){ans=mid;left=mid+1;}elseright=mid-1;}if(ans!=-1)maxv=max(maxv,ans-i+1);}cout<<maxv;return 0; }
code2 使用庫函數
#include<iostream> #include<string> #include<vector> #include<string> #include<cstdio> #include<cmath> #include<string.h> #include<algorithm> #include<unordered_map> #include<stack> using namespace std;int main() {int n;long long p;scanf("%d%lld",&n,&p);long long int a[n];for(int i=0;i<n;i++)scanf("%lld",&a[i]);sort(a,a+n);int maxv=0;for(int i=0;i<n;i++){int index=upper_bound(a+i,a+n,a[i]*p)-a;if(index==n)index--;while(a[index]>a[i]*p) index--;maxv=max(maxv,index-i+1);}cout<<maxv;return 0; }
?
?