### Problem Statement There are $N$ houses number...
創建於:2025年7月12日
創建於:2025年7月12日
There are houses numbered from to on a number line. House is located at coordinate . Multiple houses may be located at the same coordinate.
You place base stations at arbitrary real coordinates on the number line. Then, you set a non-negative integer signal strength for each base station.
When the signal strength of a base station is set to , The signal from that base station reaches a house if and only if the distance between the base station and the house is at most . Particularly, when , the signal reaches only houses located at the same coordinate as the base station.
Find the minimum possible sum of signal strengths when the positions and signal strengths of the base stations are set such that at least one base station's signal reaches every house.
It can be proved that the answer is an integer for any input satisfying the constraints.### Constraints
Output the answer as an integer in one line.
C++ code 用中文回答我,仔细思考
思路说明(中文)
将房屋坐标排序
设排序后序列为 。
“一条基站线”下的代价
如果只有一座基站覆盖所有房屋,则最小信号强度为
——把基站放在 处即可。
这是因为每段的信号强度 对应的覆盖半径是 ,
要让最左与最右两栋房屋都被覆盖,半径至少是 ,从而 。
拆分成多段的收益
若我们把序列在若干位置“断开”,每段的花费是
。
全部段花费之和 = 减去 每一次断开造成的“空隙”大小。
记相邻房屋间的间隔
若要放置 个基站,就能断开最多 处,于是总花费为
算法步骤
复杂度分析
cpp#include <bits/stdc++.h> using namespace std; using int64 = long long; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, M; if (!(cin >> N >> M)) return 0; vector<int64> x(N); for (int i = 0; i < N; ++i) cin >> x[i]; sort(x.begin(), x.end()); // 步骤 1 if (M >= N) { // 特判:基站足够多 cout << 0 << '\n'; return 0; } vector<int64> gaps; gaps.reserve(N - 1); for (int i = 0; i < N - 1; ++i) // 步骤 2 gaps.push_back(x[i + 1] - x[i]); sort(gaps.rbegin(), gaps.rend()); // 步骤 3:降序 int64 save = 0; // 可以节省的总空隙 for (int i = 0; i < M - 1; ++i) save += gaps[i]; int64 ans = (x.back() - x.front()) - save;// 步骤 4 cout << ans << '\n'; return 0; }
解释小结