pat 完美数列

分析

首先用动态数组存放给定的数列

为了方便寻找完美数列,将数列从小到大排序

用变量result 记录完美数列的元素个数,用temp去不断地尝试更新,如果存在更多个数字的完美数列,则更新result

具体代码如下

// pat 完美数列.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
	int n;
	long long p;
	scanf_s("%d%lld", &n,&p);   //注意第二个元素为长整型。
	vector<int>v(n);
	for (int i = 0;i < n;i++)
		cin >> v[i];           //初始化动态数列
	sort(v.begin(), v.end());  //  排序
	int result = 0, temp = 0;  //temp用于更新result值
	for (int i = 0;i < n;i++) 
	{
		for (int j = i + result;j < n;j++)   //优化,直接从符合条件的数字个数开始遍历,加速遍历
		{
			if (v[j] <= v[i] * p) 
			{

				temp = j - i + 1;   //符合条件的数列数字个数
				if (temp > result)
					result = temp;

			}
			else {
				break;
			}
		}
	}
	cout << result;
	system("pause");
    return 0;
}

发布了32 篇原创文章 · 获赞 1 · 访问量 5393

猜你喜欢

转载自blog.csdn.net/Li060703/article/details/89214776
今日推荐