zoukankan      html  css  js  c++  java
  • LeetCode "Best Meeting Point" !

    Interesting one.. I can feel sparkle in mind in the proposed solution - just pick the mid-point! (yes some boiler-plate code below)

    class Solution {
        //    Greedy solution
    public:
        int minTotalDistance(vector<vector<int>>& grid) {
            int n = grid.size();
        int m = grid[0].size();
        
        // Record - O(m*n)
        vector<int> hori(m);
        vector<int> vert(n);
        for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++)
        {
            if(grid[i][j])
            {
            hori[j]++;
            vert[i]++;
            }
        }
        
        // Expand records - O(k)
        vector<int> horis, verts;
        for(int i = 0; i < hori.size(); i ++)
        {
            int v = hori[i];
            if(v)
            {
            for(int j = 0; j < v; j++)
                horis.push_back(i);
            }
        }
        for(int i = 0; i < vert.size(); i ++)
        {
            int v = vert[i];
            if(v)
            {
            for(int j = 0; j < v; j++)
                verts.push_back(i);
            }
        }
        
        // Get point coords
        size_t hcnt = horis.size(), vcnt = verts.size();
        int mid_h = (hcnt % 2) ? horis[hcnt/2] : ((horis[hcnt/2] + horis[hcnt/2 - 1]) / 2);
        int mid_v = (vcnt % 2) ? verts[vcnt/2] : ((verts[vcnt/2] + verts[vcnt/2 - 1]) / 2);
        
        int ret = 0;
        
        for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++)
        {
            if(grid[i][j])
            {
            ret += abs(i - mid_v) + abs(j - mid_h);
            }
        }
        
        return ret;
        }
    };
  • 相关阅读:
    [POJ]poj2632(模拟)
    [EOJ]2019 ECNU XCPC March Selection #2
    [POJ]POJ1328(trie)
    卡特兰数相关总结
    2019海亮夏令营随笔
    树上数数 题解
    护卫小队 题解
    洛谷 P2966 [USACO09DEC]牛收费路径Cow Toll Paths 题解
    洛谷 P4735 最大异或和
    登峰造极 题解
  • 原文地址:https://www.cnblogs.com/tonix/p/4904235.html
Copyright © 2011-2022 走看看