zoukankan      html  css  js  c++  java
  • 947. 移除最多的同行或同列石头 并查集

    n 块石头放置在二维平面中的一些整数坐标点上。每个坐标点上最多只能有一块石头。

    如果一块石头的 同行或者同列 上有其他石头存在,那么就可以移除这块石头。

    给你一个长度为 n 的数组 stones ,其中 stones[i] = [xi, yi] 表示第 i 块石头的位置,返回 可以移除的石子 的最大数量。

    示例 1:

    输入:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
    输出:5
    解释:一种移除 5 块石头的方法如下所示:

    1. 移除石头 [2,2] ,因为它和 [2,1] 同行。
    2. 移除石头 [2,1] ,因为它和 [0,1] 同列。
    3. 移除石头 [1,2] ,因为它和 [1,0] 同行。
    4. 移除石头 [1,0] ,因为它和 [0,0] 同列。
    5. 移除石头 [0,1] ,因为它和 [0,0] 同行。
      石头 [0,0] 不能移除,因为它没有与另一块石头同行/列。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/most-stones-removed-with-same-row-or-column
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    
    
    
    class Solution {
    public:
        unordered_map <int, int> fa;
        unordered_map <int, int> rank;
    
        int find(int x) {
            if (!fa.count(x)) {
                fa[x] = x;
                rank[x] = 1;
            }
            return fa[x] == x ? fa[x] : find(fa[x]);
        }
    
        void unit(int x, int y) {
            int xx = find(x);
            int yy = find(y);
            if (same(xx, yy)) {
                return;
            }
            if (rank[xx] < rank[yy]) {
                swap(xx, yy);
            }
            rank[xx] += rank[yy];
            fa[yy] = xx;
        }
    
        bool same(int x, int y) {
            return find(x) == find(y);
        }
        
        int removeStones(vector<vector<int>>& stones) {
            int n = stones.size();
            for (int i = 0; i < n; i++) {
                unit(stones[i][0], stones[i][1] + 10000);
            }
    
            int num = 0;
            for (auto [x, y] : fa) {
                if (x == y) {
                    num++;
                }
            }
            
            return n - num;
        }
    };
    
  • 相关阅读:
    python并发编程之IO模型
    协程与concurent.furtrue实现线程池与进程池
    网络编程之线程进阶
    多线程讲解
    网络编程之进阶2
    网络编程之进阶
    网络编程之进程
    函数复习之2
    函数复习
    深克隆和浅克隆
  • 原文地址:https://www.cnblogs.com/xgbt/p/14301210.html
Copyright © 2011-2022 走看看