The Man who became a God

每添加一个分割点r就是从f(1, n)里减去f(r, r + 1),所以只要减去最大的k - 1个f(r, r + 1)即可,或者加上最小的 n - k 段也可以

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <string>
#include <map>
#include <cmath>
#include <iomanip>
#include <set>
#define endl '\n'

using namespace std;

typedef long long LL;
typedef pair<int, int> PII;

const int N = 105;
int n, k;
int a[N], b[N];

bool cmp(int a, int b)
{
return a > b;
}

void solve()
{
cin >> n >> k;
for (int i = 1; i <= n; i ++)
cin >> a[i];
for (int i = 2; i <= n; i++)
{
b[i] = abs(a[i] - a[i - 1]);
}

sort(b + 2, b + 1 + n);

int ans = 0;
for (int i = 2; i <= n - k + 1; i ++)
ans += b[i];
cout << ans << endl;
}

signed main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);

int t;
cin >> t;
while (t--)
{
solve();
}

return 0;
}

最接近的三数之和

排序加双指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size();
int best = 1e7;

// 根据差值的绝对值来更新答案
auto update = [&](int cur) {
if (abs(cur - target) < abs(best - target)) {
best = cur;
}
};

// 枚举 a
for (int i = 0; i < n; ++i) {
// 保证和上一次枚举的元素不相等
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
// 使用双指针枚举 b 和 c
int j = i + 1, k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
// 如果和为 target 直接返回答案
if (sum == target) {
return target;
}
update(sum);
if (sum > target) {
// 如果和大于 target,移动 c 对应的指针
int k0 = k - 1;
// 移动到下一个不相等的元素
while (j < k0 && nums[k0] == nums[k]) {
--k0;
}
k = k0;
} else {
// 如果和小于 target,移动 b 对应的指针
int j0 = j + 1;
// 移动到下一个不相等的元素
while (j0 < k && nums[j0] == nums[j]) {
++j0;
}
j = j0;
}
}
}
return best;
}
};