### Problem Statement There are $N$ houses number...
Créé le : 12 juillet 2025
Créé le : 12 juillet 2025
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.
To minimize the total signal strength, observe that each base‐station of strength covers an interval of length . Since you have intervals to cover all house‐points, you want to partition the sorted list of house coordinates into contiguous groups so as to minimize the sum of the spans of those groups.
Algorithmic steps in time:
text1. Read N, M and array X of length N. 2. Sort X. 3. Build array D of length N−1 with D[i] = X[i+1] − X[i]. 4. Sort D in descending order. 5. Sum up D[M], D[M+1], …, D[N−1] (i.e. skip the largest M−1 gaps). That sum is your answer.
This greedy “break at the largest gaps” is optimal because any reduction in total covered length comes precisely from not spanning the largest empty stretches between houses.
C++ Code
cpp#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, M; cin >> N >> M; vector<ll> X(N); for (int i = 0; i < N; i++) { cin >> X[i]; } if (M >= N) { // We can place at least one station per house cout << 0 << "\n"; return 0; } sort(X.begin(), X.end()); // Compute gaps between consecutive houses vector<ll> gaps; gaps.reserve(N - 1); for (int i = 1; i < N; i++) { gaps.push_back(X[i] - X[i - 1]); } // Sort gaps descending sort(gaps.begin(), gaps.end(), greater<ll>()); // We want to skip the largest M-1 gaps, summing the rest ll answer = 0; for (int i = M - 1; i < (int)gaps.size(); i++) { answer += gaps[i]; } cout << answer << "\n"; return 0; }
How it works: