1085. Perfect Sequence 解析

来源:互联网 发布:地产销售数据报告范文 编辑:程序博客网 时间:2024/06/05 02:42

最佳序列。

就是从给的序列里面,找最长的序列,满足最大值小于等于最小值*p

先给序列排序。从最小的开始,找能找到的最大值的位置,计算长度。

这里不能直接循环,会超时,需要二分查找,找小于等于理想值的位置。

关于二分查找贴个链接,讲了很细节的查找最后位置的各种方法。值得一看。

http://tianyanshentong.blog.51cto.com/3356396/1560237/

#include <iostream>#include <vector>#include <algorithm>using namespace std;long int n, p;vector <int> seq;int BinSerch(long int x ,int st, int ed) {int low = st, high = ed;while (low < high) {int mid = (low + high + 1) / 2;if (seq[mid] > x) {high = mid - 1;}elselow = mid;}return low;}int main() {cin >> n >> p;seq.resize(n);for (int i = 0; i < n; i++) {scanf("%d", &seq[i]);}sort(seq.begin(), seq.end());int pos = 0;int max = 0;int len = seq.size() - pos;while (pos < seq.size() && len > max) {long int pm = p * seq[pos];int pos2 = BinSerch(pm, pos, seq.size() - 1);if (pos2 - pos + 1 > max) {max = pos2 - pos + 1;}pos++;len = seq.size() - pos;}cout << max << endl;return 0;}


0 0
原创粉丝点击