【PAT】A1044. Shopping in Mars(二分查找)
@(PAT)
链接:https://www.patest.cn/contests/pat-a-practise/1044
思路:
1. 题目的意思总结来就是:在一个序列中,找到一个和比目标数大,相差最小的子序列。
2. 该题目中,可以记录累加和,然后子序列的和用减法得出。比如:
序列nums:4, 3, 2, 1, 5
累加和sums:0, 4, 7, 9, 10, 15
子序列[1, 2]的和:sums[2]- sums[1- 1]= 7- 0= 7
子序列[i, j]的和:sums[j]- sums[i- 1]
3. 找到每个子序列的方法是,遍历sums,固定子序列的i,然后通过二分查找的方法找到j。
4. 找到j之后,记录最小的差值min,然后将i对应的j记录进res。
5. 最后通过res,判断找到符合差值最小的输出。
My AC code:
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#define INF 999999999
using namespace std;
int main()
{
int n, m;
scanf("%d%d", &n, &m);
vector<int> nums(n);
vector<int> sums(n + 1);
vector<int> res(n + 1);
int sum = 0;
sums[0] = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &nums[i]);
sum += nums[i];
sums[i+ 1] = sum;
}
int min = INF;
for (int i = 1; i <= n; i++) {
int left = i;
int right = n;
while (left < right) {
int mid = (left + right) / 2;
int t = sums[mid] - sums[i- 1];
if (t >= m) {
right = mid;
}
else {
left = mid+ 1;
}
}
int temp = sums[right] - sums[i - 1];
if (temp >= m) {
if (temp < min) {
min = temp;
}
res[i] = right;
}
}
for (int i = 1; i <= n; i++) {
if (sums[res[i]] - sums[i - 1] == min) {
printf("%d-%d\n", i, res[i]);
}
}
return 0;
}