PAT 1030 完美數列

1030 完美數列(25 分)

給定一個正整數數列,和正整數 p,設這個數列中的最大值是 M,最小值是 m,如果 M≤mp,則稱這個數列是完美數列。

現在給定參數 p 和一些正整數,請你從中選擇儘可能多的數構成一個完美數列。

輸入格式:

輸入第一行給出兩個正整數 N 和 p,其中 N(≤10​5​​)是輸入的正整數的個數,p(≤10​9​​)是給定的參數。第二行給出 N 個正整數,每個數不超過 10​9​​。

輸出格式:

在一行中輸出最多可以選擇多少個數可以用它們組成一個完美數列。

輸入樣例:

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

輸出樣例:

8

一開始總想從最小最大入手,無思路

 思路:

兩個循環,一個個遍歷

i從 1->n 找最小值,j從i到n找最大值,滿足等式 儲存個數temp,直到不滿足等式 退出循環

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	int n, p;//n爲輸入正整數個數,p爲係數參數
	vector<int> num;
	int temp;
	cin >> n >> p;
	for (int i = 0; i < n; i++)
	{
		cin >> temp;
		num.push_back(temp);
	}
	sort(num.begin(), num.end());//從小到大
	
	int result = 0;
	temp = 0;
	for (int i = 0; i < n; i++)
	{
		for (int j = i; j < n; j++)
		{
			if (num[j] <= num[i] * p)
				temp = j - i + 1;//符合的個數
			else
				break;
		}
		if (temp > result)
			result = temp;
	}
	cout << result;

	system("pause");
	return 0;
}

 

 測試點5,應該是大數<=10^9,用long long格式

運行超時優化:

將第二個for循環的初始化j設爲i+result,從之前滿足條件的最多個數開始

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	int n;
	long long p;//n爲輸入正整數個數,p爲係數參數
	vector<long long> num;
	long long temp;
	cin >> n >> p;
	for (int i = 0; i < n; i++)
	{
		cin >> temp;
		num.push_back(temp);
	}
	sort(num.begin(), num.end());//從小到大
	
	int result = 0;
	temp = 0;
	for (int i = 0; i < n; i++)
	{
		for (int j = i + result; j < n; j++)
		{
			if (num[j] <= num[i] * p)
				temp = j - i + 1;//符合的個數
			else
				break;
		}
		if (temp > result)
			result = temp;
	}
	cout << result;

	system("pause");
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章