Author : Dipu Kumar Mohanto
CSE, Batch - 6
BRUR.
Problem Statement : 1478. Allocate Mailboxes
Source : leetcode.com
Category : Dynamic Programin
Algorithm : 3D DP
Verdict : Accepted
- class Solution {
- public:
- const int INF = 1e9;
- int dp[101][101][101];
-
- int minDistance(vector<int>& houses, int k) {
- int n = houses.size();
- sort(houses.begin(), houses.end());
- memset(dp, -1, sizeof dp);
-
- function <int(int, int)> get = [&](int l, int r) {
- int sum = 0;
- int median = (l + r) / 2;
- median = houses[median];
- for (int i = l; i <= r; i++) {
- sum += abs(houses[i] - median);
- }
- return sum;
- };
-
- function <int(int, int, int)> solve = [&](int now, int pre, int block) {
- if (block > k) {
- return INF;
- }
- if (now == n - 1) {
- if (block < k) {
- return INF;
- }
- return get(pre, now);
- }
- if (now == n) {
- return INF;
- }
- int &ret = dp[now][pre][block];
- if (~ret) {
- return ret;
- }
- ret = solve(now + 1, pre, block);
- int go = get(pre, now) + solve(now + 1, now + 1, block + 1);
- ret = min(ret, go);
- return ret;
- };
- int ans = solve(0, 0, 1);
- return ans;
- }
- };