PAT 1085. Perfect Sequence

1. 将数组vt排序。O(nlogn)

2. 之后遍历数组。取数组的第i个元素作为最小值,m*p可得最大值target. 在vt[i, n)中寻找满足vt[index] <= target的最大下标,试着更新最大步长(即所求结果)。O(nlogn)


 代码:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int n, maxx=0;
long long p, tmp;
vector<long long> vt;

void init()
{
	cin >> n >> p;
	for (int i = 0; i < n; ++ i)
	{
		cin >> tmp;
		vt.push_back( tmp );
	}
	sort(vt.begin(), vt.end());	
}

void gao(int begin)
{
	long long target = vt[begin] * p;
	int left=begin, right=vt.size()-1;
	while (left <= right)
	{
		int mid = (left+right) >> 1;
		if (vt[mid] < target)
		{
			maxx = max(maxx, mid-begin+1);
			left = mid + 1;
		} else if (vt[mid] > target)
		{
			right = mid - 1;
		} else
		{
			maxx = max(maxx, mid-begin+1);
			left = mid + 1;
		}
	}
}

int main()
{
	init();

	for (int i = 0; i < n; ++ i)
	{
		gao(i);
	}
	cout << maxx << endl;

	return 0;
}


你可能感兴趣的:(C++,pat)