zoukankan      html  css  js  c++  java
  • LintCode "Post Office Problem" !!!

    * 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 oddeven. 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)

  • 相关阅读:
    边缘检测
    图片融合
    毛玻璃
    图像添加马赛克
    图像颜色反转
    图像灰度处理
    图像仿射变换/旋转
    图像剪切/位移
    图像缩放/插值
    神经网络逼近股票价格
  • 原文地址:https://www.cnblogs.com/tonix/p/4971601.html
Copyright © 2011-2022 走看看