2732. 找到矩阵中的好子集

Powered by:NEFU AB-IN

Link

文章目录

  • [2732. 找到矩阵中的好子集](#2732. 找到矩阵中的好子集)

2732. 找到矩阵中的好子集

题意

给你一个下标从 0 开始大小为 m x n 的二进制矩阵 grid 。

从原矩阵中选出若干行构成一个行的 非空 子集,如果子集中任何一列的和至多为子集大小的一半,那么我们称这个子集是 好子集。

更正式的,如果选出来的行子集大小(即行的数量)为 k,那么每一列的和至多为 floor(k / 2) 。

请你返回一个整数数组,它包含好子集的行下标,请你将其 升序 返回。

如果有多个好子集,你可以返回任意一个。如果没有好子集,请你返回一个空数组。

一个矩阵 grid 的行 子集 ,是删除 grid 中某些(也可能不删除)行后,剩余行构成的元素集合。

思路

由于数组中的元素类型只有0和1,列最多五行,那么可以举行的个数的例子

比如如果一行全是0,是可行的;比如 0101010101这种互补的形式,或者0101000001这种,也是成立

如果答案是三行,那么肯定包括一行和两行的情况,所以只需要考虑1,2行,2行的时候考虑二进制逐位与运算

代码

python 复制代码
# import
from functools import cache
from sys import setrecursionlimit, stdin, stdout, exit
from collections import Counter, deque, defaultdict
from heapq import heapify, heappop, heappush, nlargest, nsmallest
from bisect import bisect_left, bisect_right
from datetime import datetime, timedelta
from string import ascii_lowercase, ascii_uppercase
from math import log, gcd, sqrt, fabs, ceil, floor
from types import GeneratorType
from typing import TypeVar, List, Dict, Any, Callable


# Data structure
class SA:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __lt__(self, other):
        return self.x < other.x


# Constants
N = int(2e5 + 10)  # If using AR, modify accordingly
M = int(20)  # If using AR, modify accordingly
INF = int(2e9)
E = int(100)

# Set recursion limit
setrecursionlimit(INF)

# Read
input = lambda: stdin.readline().rstrip("\r\n")  # Remove when Mutiple data
read = lambda: map(int, input().split())
read_list = lambda: list(map(int, input().split()))


# Func
class std:

    # Recursion
    @staticmethod
    def bootstrap(f, stack=None):
        if stack is None:
            stack = []

        def wrappedfunc(*args, **kwargs):
            if stack:
                return f(*args, **kwargs)
            else:
                to = f(*args, **kwargs)
                while True:
                    if isinstance(to, GeneratorType):
                        stack.append(to)
                        to = next(to)
                    else:
                        stack.pop()
                        if not stack:
                            break
                        to = stack[-1].send(to)
                return to

        return wrappedfunc

    letter_to_num = staticmethod(lambda x: ord(x.upper()) - 65)  # A -> 0
    num_to_letter = staticmethod(lambda x: ascii_uppercase[x])  # 0 -> A
    array = staticmethod(lambda x=0, size=N: [x] * size)
    array2d = staticmethod(
        lambda x=0, rows=N, cols=M: [std.array(x, cols) for _ in range(rows)])
    max = staticmethod(lambda a, b: a if a > b else b)
    min = staticmethod(lambda a, b: a if a < b else b)
    filter = staticmethod(lambda func, iterable: list(filter(func, iterable)))


# ---------------------------------------------------------------Division line ------------------------------------------------------------------


class Solution:

    def goodSubsetofBinaryMatrix(self, grid: List[List[int]]) -> List[int]:
        # 挑一行
        n, m = len(grid), len(grid[0])
        for i in range(n):
            row = grid[i]
            if sum(row) == 0:
                return [i]

        # 挑两行
        binary_map = {}
        for i in range(n):
            row_binary = int("".join(map(str, grid[i])), 2)
            for existing_row_binary, index in binary_map.items():
                if row_binary & existing_row_binary == 0:  # 逐位与运算
                    return sorted([index, i])
            binary_map[row_binary] = i

        return []
相关推荐
py有趣1 小时前
LeetCode学习之0矩阵
学习·leetcode·矩阵
郝学胜-神的一滴1 天前
Cesium绘制线:从基础到高级技巧
前端·javascript·程序人生·线性代数·算法·矩阵·图形渲染
前端小L1 天前
动态规划的“升维”之技:二维前缀和,让矩阵查询“降维打击”
线性代数·矩阵
爱学习的小鱼gogo2 天前
pyhton 螺旋矩阵(指针-矩阵-中等)含源码(二十六)
python·算法·矩阵·指针·经验·二维数组·逆序
智能化咨询2 天前
矩阵的奇异值分解(SVD)核心原理与图形学基础应用
矩阵
西***63472 天前
从信号处理到智能协同:高清混合矩阵全链路技术拆解,分布式系统十大趋势抢先看
网络·分布式·矩阵
AIGC_北苏2 天前
大语言模型,一个巨大的矩阵
人工智能·语言模型·矩阵
HVACoder2 天前
复习下线性代数,使用向量平移拼接两段线
c++·线性代数·算法
应用市场2 天前
楼灯光矩阵显示系统:从理论到实践的完整技术方案
线性代数·矩阵·wpf
然后,是第八天2 天前
【机械臂运动学基础】变换矩阵
线性代数·矩阵