PTA甲级1085 Perfect Sequence (25分)

时间:2020-03-26
本文章向大家介绍PTA甲级1085 Perfect Sequence (25分),主要包括PTA甲级1085 Perfect Sequence (25分)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先,先贴柳神的博客

https://www.liuchuo.net/ 这是地址

想要刷好PTA,强烈推荐柳神的博客,和算法笔记

题目原文

1085 Perfect Sequence (25分)

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 (≤105) is the number of integers in the sequence, and p (≤109) is the parameter. In the second line there are N positive integers, each is no greater than 109.

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

题目大意:

① 给你N个正整数,然后在给你一个P,要你任意的整合出一个数列,要求这些数列的最小的数m,和最大的数M,满足下面的要求

Mm×p,要你求出,这个数列最多能有多少

思路如下

① 先排序,然后在双重循环的解法肯定是不可以的,因为这样时间复杂度会超过

② 这题可以用upper_bound这个函数来解,就是求出第一个超过的数,这样他的邻接的那个数就肯定是最大的那个数了.

代码一览

算法笔记上的

#include<iostream>
#include<cstdio>
#include<algorithm>
const int maxn = 100010;
int n, p, a[maxn];
int binarySearch(int i, long long x) {
	if (a[n - 1] <= x)	return n;
	int l = i + 1, r = n - 1, mid;
	while (l < r) {
		mid = (l + r) / 2;
		if (a[mid] <= x)	l = mid + 1;
		else	r = mid;
	}
	return	l;
}
using namespace std;
int main(void) {
	scanf("%d%d", &n, &p);
	for (int i = 0; i < n; i++)	scanf("%d", &a[i]);
	sort(a, a + n);				//递增排序
	int ans = 1;				//最大长度,初值为1(表示有至少有一个数)
	for (int i = 0; i < n; i++) {
		int j = binarySearch(i, (long long)a[i] * p);
		ans = max(ans, j - i);
	}
	printf("%d", ans);	//输出结果
	return 0;
}

自己改了一下子的

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main(void) {
	int N,Max=1,P;
	scanf("%d%d", &N,&P);
	vector<int> data(N);
	for (int i = 0; i < N; i++)	scanf("%d", &data[i]);
	sort(data.begin(), data.end());
	for (int i = 0; i < N / 2; i++) {
		int t=upper_bound(data.begin(), data.end(), (long long)data[i] * P)-data.begin()-i;
		if (t > Max)	Max = t;
	}
	printf("%d", Max);
	return 0;
}

原文地址:https://www.cnblogs.com/a-small-Trainee/p/12574942.html