Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

* Non-intuitive state design

class Solution 
{
public:
    /**
     * @param A an integer array
     * @param k an integer
     * @return an integer
     */
    int postOffice(vector<int>& A, int k) 
    {
        int n = A.size();
        sort(A.begin(), A.end());
    
    // Cost btw. 2 houses i-j with 1 post-office - built in the mid
    vector<vector<int>> w(n + 1, vector<int>(n + 1));
    for(int i = 1; i <= n; i ++)
    {
        w[i][i] = 0;
        for(int j = i + 1; j <= n; j ++)
        {
        // Check both odd\even. It holds.
        w[i][j] = w[i][j-1] + A[j - 1] - A[(i + j) / 2 - 1];
        }
    }
    
    // main DP    
    vector<vector<int>> dp(n + 1, vector<int>(k + 1));
    for(int i = 1; i <= n; i++)
    {
        dp[i][1] = w[1][i];
    }
    for(int i = 2; i <= k; i ++) // post-offices
    {
        for(int j = n; j > i; j --) // houses. Low j sets high j
        {
        dp[j][i] = INT_MAX;
        for(int x = i - 1; x < j; x ++)
        {
            dp[j][i] = min(dp[j][i], dp[x][i-1] + w[x + 1][j]);
        }
        }
    }
    
    return dp[n][k];
    }
};

TODO: DP optimized to O(n^2)

posted on 2015-11-17 14:25  Tonix  阅读(722)  评论(0编辑  收藏  举报