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

    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] 不能移除,因为它没有与另一块石头同行/列。

    并查集,注意用~y取反,防止x,y相同(开始考虑用-y,没有考虑到0)

    class Solution:
        def removeStones(self, stones: List[List[int]]) -> int:
            parent=dict()
    
            def find(x):
                parent.setdefault(x, x)
                if parent[x]!=x:
                    parent[x]=find(parent[x])
                return parent[x]
            
            def union(x, y):
                x, y=find(x), find(y)
                parent[x]=y
            
            for x, y in stones:
                union(x, ~y)
            print(parent)
            return len(stones)-len(set(find(i) for i in parent.values()))
  • 相关阅读:
    [Luogu P4779] 单源最短路径(标准版)
    [Luogu P1659] 拉拉队排练
    [Luogu P3435] OKR-Periods of Words
    [Poj #2127] Greatest Common Increasing Subsequence
    [Poj #2019] Cornfields
    [Poj #1949] Chores
    关于我
    划水记录
    [AGC006C] Rabbit Exercise
    [AGC007C] Pushing Balls
  • 原文地址:https://www.cnblogs.com/lzk-seven/p/14281838.html
Copyright © 2011-2022 走看看