# IOI '00 P5 - Post Office

Jun 8th, 2022
700
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. #include <iostream>
2. #include <vector>
3. #include <algorithm>
4.
5. using namespace std;
6.
7. const int INF = 1e9;
8.
9. int main() {
10.     int n, m;
11.     cin >> n >> m;
12.     vector<int> x(n);
13.     for (int &a : x) cin >> a;
14.     auto d = [&x](int i, int j) {
15.         return abs(x[i]-x[j]);
16.     };
17.
18.     vector<vector<int>> dp(1+m, vector<int>(n, INF));
19.     vector<vector<int>> prev(1+m, vector<int>(n, -1)); // previous post office used
20.     // one post office
21.     for (int i = 0; i < n; ++i) {
22.         dp[1][i] = 0;
23.         for (int j = 0; j < n; ++j) dp[1][i] += d(i, j);
24.     }
25.
26.     // more post offices
27.     for (int k = 2; k <= m; ++k) { // number of post offices
28.         for (int i = k-1; i < n; ++i) { // position of last post office
29.             int firstCloser = i; // leftmost village closer to i than to j
30.             int sumDistToI = 0; // sum of distances to i for all in range [firstCloser, i]
31.             for (int j = i-1; j >= k-2; --j) { // position of previous post office
32.                 // update firstCloser
33.                 while (firstCloser && d(firstCloser-1, i) <= d(firstCloser-1, j)) {
34.                     sumDistToI += d(--firstCloser, i);
35.                 }
36.
37.                 int deltaCost = 2*sumDistToI - (n-firstCloser) * d(i, j);
38.                 int totalCost = dp[k-1][j] + deltaCost;
39.                 if (totalCost < dp[k][i]) {
40.                     dp[k][i] = totalCost;
41.                     prev[k][i] = j;
42.                 }
43.             }
44.         }
45.     }
46.
47.     int i = 0;
48.     for (int j = 1; j < n; ++j) {
49.         if (dp[m][j] < dp[m][i]) i = j;
50.     }
51.     cout << dp[m][i] << endl;
52.     vector<int> v;
53.     for (int k = m; k > 0; i=prev[k--][i]) v.push_back(i);
54.     for (int p = m-1; p >= 0; --p) cout << x[v[p]] << ' ';
55.     cout << endl;
56.     return 0;
57. }