前言
这道题赛时更改了数据使得用 long long 能 AC,但是主题库的版本依然需要开 __int128。
1. 题意
有数组 和 。
里的第 个元素可以花费 的代价加 。
求至少需要多少代价,才能让 中至少有 个一样的元素。
2. 分析
设 个选定的元素构成 的一个子集,记为 ,那么显然最终这 个数值(记为 )必须大于他们各自的初始 。
既然要最小化代价,我们就让这个 取成这 个元素当中的初始值的最大值(条件最大值)即可。换句话说,最优的 必然是原数组中的某个 。
于是可以用枚举法,将所有人按初始勤劳度 从小到大排序。然后依次枚举第 个人作为“基准”(即令最终目标值 )。此时只能从下标 的人中选(因为下标大于 的人初始 ,无法降级)。
对于固定的 ,前 个人中的第 人升级到 的花费为 。
因此内部循环只需计算出这些花费,并贪心地选取其中最小的 个累加,即可得到以 为目标时的最小开销,也就是局部最优。
外层循环遍历所有可能的 (满足 ),取所有局部最优中的最小值即为全局最优。
特别地,C++ 里的 nth_element 的时间复杂度是 ,因此总体的时间复杂度是 。
注意这个题答案最大可能达到 量级,因此 C++ 必须用 __int128。
3. 代码
比赛代码
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int n, k;
long long ans = -1;
vector<pair<long long, long long>> people;
int main()
{
cin >> n >> k;
people.resize(n);
for (int i = 0; i < n; ++i)
{
cin >> people[i].first;
}
for (int i = 0; i < n; ++i)
{
cin >> people[i].second;
}
sort(people.begin(), people.end());
for (int i = k - 1; i < n; ++i)
{
long long target = people[i].first;
vector<long long> costs;
costs.reserve(i + 1);
for (int j = 0; j <= i; ++j)
{
costs.push_back((target - people[j].first) * people[j].second);
}
nth_element(costs.begin(), costs.begin() + k, costs.end());
long long cur = 0;
for (int j = 0; j < k; ++j)
{
cur += costs[j];
}
if (ans == -1 || cur < ans)
{
ans = cur;
}
}
cout << ans;
}Deepseek 重构的 128 位版本
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
using int128 = __int128;
int128 read() {
int128 x = 0;
bool negative = false;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') negative = true;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = x * 10 + (c - '0');
c = getchar();
}
return negative ? -x : x;
}
void print(int128 x) {
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) print(x / 10);
putchar(x % 10 + '0');
}
int n, k;
int128 ans = -1;
vector<pair<int128, int128>> people;
int main()
{
n = read();
k = read();
people.resize(n);
for (int i = 0; i < n; ++i)
{
people[i].first = read();
}
for (int i = 0; i < n; ++i)
{
people[i].second = read();
}
sort(people.begin(), people.end());
for (int i = k - 1; i < n; ++i)
{
int128 target = people[i].first;
vector<int128> costs;
costs.reserve(i + 1);
for (int j = 0; j <= i; ++j)
{
costs.push_back((target - people[j].first) * people[j].second);
}
nth_element(costs.begin(), costs.begin() + k, costs.end());
int128 cur = 0;
for (int j = 0; j < k; ++j)
{
cur += costs[j];
}
if (ans == -1 || cur < ans)
{
ans = cur;
}
}
print(ans);
return 0;
}