码迷,mamicode.com
首页 > 其他好文 > 详细

1085 Perfect Sequence (25分)

时间:2020-04-25 01:04:46      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:otto   include   arc   sed   printf   ext   html   math   long   

Given a sequence of positive integers and another positive integer p. The sequence is said to be a perfect sequence if Mm×p where M and m are the maximum and minimum numbers in the sequence, respectively.

Now given a sequence and a parameter p, you are supposed to find from the sequence as many numbers as possible to form a perfect subsequence.

Input Specification:

Each input file contains one test case. For each case, the first line contains two positive integers N and p, where N (≤) is the number of integers in the sequence, and p (≤) is the parameter. In the second line there are N positive integers, each is no greater than 1.

Output Specification:

For each test case, print in one line the maximum number of integers that can be chosen to form a perfect subsequence.

Sample Input:

10 8
2 3 20 4 5 1 6 7 8 9
 

Sample Output:

8



#include<iostream>
#include<algorithm>
using namespace std;

int binarysearch(int a[], long long x,int size,int i)
{//查找第一个大于x的数的位置
    int left = i+1, right = size-1, mid;
    if(a[size-1]<=x)
        return size;
    while(left < right)
    {
        mid = (left + right)/2;

        if(a[mid]<=x)
            left = mid+1;
        else
            right = mid;
    }

    return left;
}

int main()
{
    long long n,p;
    scanf("%lld %lld",&n,&p);

    int a[n];
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }

    sort(a,a+n);

    int cnt =0;
    for(int i=0;i<n;i++)
    {
//i从0——n-1,寻找大于p*a[i]的数在数组中的下标
int j = binarysearch(a,a[i]*p,n,i)-i;//a[i]是最小值 if(cnt<j) cnt = j; } cout<<cnt; return 0; }

解法二:two_point大法

#include<iostream>
#include<algorithm>
using namespace std;

int main()
{
    int n,p;
    scanf("%d %d",&n,&p);

    long long a[n];
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
    }

    sort(a,a+n);
    int cnt =1;
    int i=0,j=0;//i,j是两个下标或者说是指针,i,j分别向右边移动
    while(i<n&&j<n)
    {
        while(j<n&&a[j]<=a[i]*p)//满足条件j就往后移动
        {

            cnt=max(cnt,j-i+1);//cnt取最大值,所以j不需要从i+1开始
            j++;
        }
        i++;

    }

    printf("%d",cnt);

    return 0;

}

 

1085 Perfect Sequence (25分)

标签:otto   include   arc   sed   printf   ext   html   math   long   

原文地址:https://www.cnblogs.com/qinmin/p/12771174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!