题解:P16430 危机重重
0x00AC3375
·
·
题解
::::warning[前言]{open}
这道题赛时更改了数据使得用 long long 能 AC,但是主题库的版本依然需要开 __int128。
::::
1. 题意
有数组 P=\{p_i\} 和 W=\{w_i\}。
求至少需要多少代价,才能让 $\{p_i\}$ 中至少有 $k$ 个一样的元素。
## 2. 分析
设 $k$ 个选定的元素构成 $P$ 的一个子集,记为 $K$,那么显然最终这 $k$ 个数值(记为 $t$)必须大于他们各自的初始 $p_i$。
既然要最小化代价,我们就让这个 $t$ 取成这 $k$ 个元素当中的初始值的最大值(条件最大值)即可。换句话说,**最优的 $t$ 必然是原数组中的某个 $p_i$**。
于是可以用枚举法,将所有人按初始勤劳度 $p_i$ 从小到大排序。然后依次枚举第 $i$ 个人作为“基准”(即令最终目标值 $t = p_i$)。此时只能从下标 $1 \sim i$ 的人中选(因为下标大于 $i$ 的人初始 $p_i > t$,无法降级)。
对于固定的 $t = p_i$,前 $i-1$ 个人中的第 $j$ 人升级到 $t$ 的花费为 $(p_i-p_j)w_j$。
因此内部循环只需计算出这些花费,并贪心地选取其中最小的 $k$ 个累加,即可得到以 $p_i$ 为目标时的最小开销,也就是局部最优。
外层循环遍历所有可能的 $i$(满足 $i \ge k-1$),取所有局部最优中的最小值即为全局最优。
特别地,C++ 里的 `nth_element` 的时间复杂度是 $O(n)$,因此总体的时间复杂度是 $O(n^2)$。
注意这个题答案最大可能达到 $10^{21}$ 量级,因此 C++ 必须用 __int128。
## 3. 代码
::::warning[比赛代码]
```cpp
#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;
}
```
::::
::::info[Deepseek 重构的 128 位版本]
```cpp
#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;
}
```
::::