【一隻蒟蒻的刷題歷程】【PAT】A1085 完美序列

給定一個正整數序列和另一個正整數p。 如果M≤m×p,則該序列被認爲是理想序列,其中M和m分別是序列中的最大數和最小數。

現在給定一個序列和一個參數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


思路:

先將數組進行排序,然後從這個數組的每一個位置都往後遍歷一遍找到滿足條件的最大值,不斷更新最大值。


代碼一(two pointers):

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <set>
#include <map>
using namespace std;  
int main() 
{ 
  int n,p,a[100100];
  cin>>n>>p;
  for(int i=0;i<n;i++)
   cin>>a[i];
  sort(a,a+n); //先排序
  int z=0,y=0,ans=0; //z左 y右 ans答案
  while(z<n) //左邊位置小於n
  {
  	  while(a[y]<=(long long)a[z]*p && y<n) //加longlong測試點5
  	  //滿足條件時就一直往後,直到不滿足了,就是本次最大值
     {
     	ans = max(ans,y-z+1); //更新最大值
  	    y++;  //右邊 繼續往後
     }
     z++; //左邊往後一個
  }
  cout<<ans;
  return 0;
}

代碼二(二分 upper_bound):

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <set>
#include <map>
using namespace std;  
int main() 
{ 
  int n,p,a[100100];
  cin>>n>>p;
  for(int i=0;i<n;i++)
   cin>>a[i];
  sort(a,a+n); //排序
  int ans=0;
  for(int i=0;i<n;i++)
  {
  	 int position=upper_bound(a+i,a+n,(long long)a[i]*p)-a;
  	 //找到第一個大於條件的數,然後更新最大值
  	 ans = max(ans , position-i);
  }
  cout<<ans;
  return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章