【题意】
找到给出的数字集合中满足最小数字乘以一正整数p不小于最大数字的子集的最大容量(= =感觉说的有点拗口。。。)
【思路】
此题可用DP做,先对所有数字由小到大排个序,放在num数组中,然后用 dp[i] 表示 num[i] 为最大数字的数字串中最小数字的下标,
① 若 num[dp[i-1]]*p>=num[i],则 dp[i] = dp[i-1];
② 否则从 dp[i-1] 位置往右找,直到找到满足 num[index]*p>=num[i] 的下标 index,则 dp[i] = index
数字串的长度就是 i-dp[i]+1, 每次更新一个 dp[i] 与之前的最多数字的数量比较并更新一下即可
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char const *argv[])
{
vector<int> num,dp;//dp[i]代表以i为结尾的满足要求最长数字串的第一个数字下标
long long n,p;
cin >> n >> p;
num.resize(n);
dp.resize(n);
for(int i=0; i<n; i++){
cin >> num[i];
}
sort(num.begin(),num.end());
int maxLen = 1;
dp[0] = 0;
for(int i=1; i<n; i++){
if(num[dp[i-1]]*p>=num[i]){
dp[i] = dp[i-1];
}
else{
int index = dp[i-1]+1;
while(num[index]*p<num[i]){
index++;
}
dp[i] = index;
}
if(i-dp[i]+1>maxLen){
maxLen = i-dp[i]+1;
}
}
cout << maxLen;
system("pause");
return 0;
}