1085. Perfect Sequence (25)

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 = -1;

        for (int i = 0; i < v.size(); i++)

        {

            long long int count = 1;

            for (int j = i + 1; j < v.size(); j++)

            {

                if (v[i] * p >= v[j])

                    count += 1;

                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.csdn.net/nan327347465/article/details/39104721. he uses the binary search and successfully reduces the

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

你可能感兴趣的:(sequence)