1085. Perfect Sequence (25)

时间:2023-03-08 16:50:43

the problem is from PAT,which website is http://pat.zju.edu.cn/contests/pat-a-practise/1085

At first, i decide to write the code as follows:

/*
firstly: sort the array using the algorithm "sort"
secondly: traverse all the possible answer and find the most suitable one.
*/
#include<iostream>
#include<vector>
#include<algorithm> using namespace std; int main()
{
long long int n,p;
vector<long long int> v;
while (cin>>n>>p)
{
long long int temp;
while (n--)
{
cin>>temp;
v.push_back(temp);
}
sort(v.begin(),v.end());
long long int max = -;
for (int i = ; i < v.size(); i++)
{
long long int count = ;
for (int j = i + ; j < v.size(); j++)
{
if (v[i] * p >= v[j])
count += ;
else break;
}
if (count >= max)
{
max = count ;
}
}
cout<<max<<endl;
}
}

but the result of one example is time running out, so i evaluate the time complexity of the

code. i think the most time-consuming part is the double circulation,whose time complexity is

O(n*2). then i searched the web and found a better solution. its url is http://blog.****.net/nan327347465/article/details/39104721. he uses the binary search and successfully reduces the

tiem complexity down to O(n * log (n)).