leetcode 886. Possible Bipartition(可能的二分组)

遥感新手别纠结!实测ENVI 5.3、5.6、6.0三个免费版,教你混搭安装避坑 本文为遥感新手提供ENVI 5.3、5.6、6.0三个免费版的实测对比与混搭安装指南,帮助用户构建零成本高效工作流。详细解析各版本功能差异、共存安装技巧及常见问题解决方案,特别适合课程作业、毕业论文分析和遥感入门练习。 阅读详情

Given a set of N people (numbered 1, 2, …, N), we would like to split everyone into two groups of any size.

Each person may dislike some other people, and they should not go into the same group.

Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group.

Return true if and only if it is possible to split everyone into two groups in this way.

Example 1:

Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]
Output: true
Explanation: group1 [1,4], group2 [2,3]

Constraints:
1 <= N <= 2000
0 <= dislikes.length <= 10000
dislikes[i].length == 2
1 <= dislikes[i][j] <= N
dislikes[i][0] < dislikes[i][1]
There does not exist i != j for which dislikes[i] == dislikes[j].

有N个人,可以分成任意数量的两组,但是dislike里面的每一对都不能分到一个组里

思路:
只要保证dislike里面的不在一个组,剩下的人可以随意分组。
所以用dislike里面的边构造无向图,然后给图染两种颜色,dislike里面同一条边的两个端点不能是同一种颜色。

和785题同为给图染色

先用标准BFS,每一层染一种颜色,用color数组记录下每个节点的颜色,当出现颜色冲突时返回false
注意是无向图,两个方向都要加

//28ms
    public boolean possibleBipartition(int N, int[][] dislikes) {
        if(dislikes == null || dislikes.length == 0) {
            return true;
        }
        
        HashMap<Integer, List<Integer>> graph = new HashMap<>();
        for(int[] dislike : dislikes) {
            if(!graph.containsKey(dislike[0])) {
                graph.put(dislike[0], new ArrayList<Integer>());
            }
            graph.get(dislike[0]).add(dislike[1]);
            if(!graph.containsKey(dislike[1])) {
                graph.put(dislike[1], new ArrayList<Integer>());
            }
            graph.get(dislike[1]).add(dislike[0]);
        }
        
        
        int[] color = new int[N+1];
        
        for(int i = 1; i <= N; i++) {
            if(color[i] == 0 && !bfs(i, graph, color)) {
                return false;
            }
        }
        return true;
    }
    
    boolean bfs(int start, HashMap<Integer, List<Integer>> graph, int[] color) {
        Queue<Integer> queue = new LinkedList<Integer>();
        queue.offer(start);
        if(color[start] == 0) color[start] = 1;
        
        while(!queue.isEmpty()){
            int p1 = queue.poll();
            if(!graph.containsKey(p1)) continue;
            int nextColor = color[p1] == 1 ? 2 : 1;
            for(int p2 : graph.get(p1)) {
                if(color[p2] == 0) {
                    color[p2] = nextColor;
                    queue.offer(p2);
                } else {
                    if(color[p2] != nextColor) return false;
                }
            }
        }
        return true;
    }

上面的方法耗时较长,用简易版BFS能缩短3ms

//25ms
    public boolean possibleBipartition(int N, int[][] dislikes) {
        if(dislikes == null || dislikes.length == 0) {
            return true;
        }
        
        HashMap<Integer, List<Integer>> graph = new HashMap<>();
        for(int[] dislike : dislikes) {
            if(!graph.containsKey(dislike[0])) {
                graph.put(dislike[0], new ArrayList<Integer>());
            }
            graph.get(dislike[0]).add(dislike[1]);
            if(!graph.containsKey(dislike[1])) {
                graph.put(dislike[1], new ArrayList<Integer>());
            }
            graph.get(dislike[1]).add(dislike[0]);
        }
        
        
        int[] color = new int[N+1];
        
        for(int i = 1; i <= N; i++) {
            if(color[i] == 0 && !bfs(i, graph, color, 1)) {
                return false;
            }
        }
        return true;
    }
    
    boolean bfs(int cur, HashMap<Integer, List<Integer>> graph, int[] color, int curColor) {
        if(color[cur] != 0) return color[cur] == curColor;
        if(!graph.containsKey(cur)) return true;
        color[cur] = curColor;
        
        for(int p2 : graph.get(cur)) {
            if(!bfs(p2, graph, color, -curColor)) return false;
        }
        return true;
    }

但是在构建无向图这个过程还是耗时较长,
用Union-Find方法来归类,
首先每个节点的root/parent是它自己,然后遍历dislike的每条边,当一条边右端点的parent是它自己时,更新parent为左端点。把左端点当作右端点的parent。

当右端点的parent不是它自己时,说明它连接的有另一个节点,顺藤摸瓜一直摸到它的root。另外初始颜色设为1,每经过一个parent就换反向的颜色。
这样一个端点找到它的root时,也会得到对应的颜色
当dislike中有一条边,它的左端点和右端点顺藤摸瓜得到的root和颜色都是相同的,说明存在颜色冲突,返回false

//5ms
    public boolean possibleBipartition(int N, int[][] dislikes) {
        int[] color = new int[N+1];
        for(int i = 1; i <= N; i++) color[i] = i;
        for(int[] p : dislikes) {
            int p1 = p[0];
            int p2 = p[1];
            if(color[p2] == p2) {
                color[p2] = p1;
            } else {
                int[] rc1 = find(color, p1);
                int[] rc2 = find(color, p2);
                if(rc1[0] == rc2[0] && rc1[1] == rc2[1]) return false;
            }
        }
        return true;
    }
    
    int[] find(int[] colors, int p) {
        int color = 1;
        while(colors[p] != p) { //not root
            p = colors[p];
            color = color == 1 ? 2 : 1;
        }
        return new int[]{p, color};
    }
【气候极端指数】MATLAB计算各种气候极端指数 简介各类气候极端指数,及其MATLAB计算代码 阅读详情

相关推荐

合成孔径雷达Chirp Scaling(CS)算法MATLAB仿真实现

本人也是初学《合成孔径雷达成像算法与实现》,在GitHub上下载的关于CS算法的代码,仔细读了读,发现中间有一些不合理之处,动手改了一改,重新写了一个代码供初学者学习,有什么问题留言即可。 非常感谢源代码的作者,虽然中间有少许不正确的地方,但是对我理解cs算法的帮助非常大,非常感谢!!! 代码中提到的(4.31)这种均是在《合成孔径雷达成像算法与实现》中的公式 以下是MATLAB的仿真程序,直接复...

weixin_41700188的博客 7861

[leetcode]886. Possible Bipartition

[leetcode]886. Possible Bipartition Analysis Still raining outside…—— [每天刷题并不难0.0] Given a set of N people (numbered 1, 2, …, N), we would like to split everyone into two groups of any size. Each ...

weixin_32135877的博客 410

半监督的医学分割数据集(LA, Pancreas, ACDC和PROMISE12)分享

这篇文章提供了四个常用的半监督医学分割数据集,所有数据集都已经被处理成了.h5文件。下载之后就可以直接使用

qq_45691955的博客 4210

LeetCode //C - 886. Possible Bipartition

Problem Summary: The task is to partition n people into two groups such that no two people who dislike each other are in the same group. The dislikes are given as pairs [a, b], indicating mutual dislike. Solution Approach: Graph Representation: Represent t

Made in Code 1443

Autoware1.14-摄像头目标检测YOLO-V3

在Autoware1.14中部署YOLOV3

weixin_43687753的博客 3150

紫光同创PGL50H开发板实战:盘古50KN网口板的高速通信与数据处理

本文详细介绍了紫光同创PGL50H开发板(盘古50KN网口板)在高速通信与数据处理领域的实战应用。文章从开箱、核心芯片解析、开发环境搭建入手,重点讲解了如何配置与测试其8路千兆以太网接口和SFP光纤接口,并深入探讨了FPGA与DDR3协同进行多路数据汇聚处理的系统架构与调试方法,为网络通信与高速数据处理系统开发提供了宝贵的实践经验。

weixin_28256233的博客 468

LeetCode 886 Possible Bipartition

题目 Given a set of N people (numbered 1, 2, …, N), we would like to split everyone into two groups of any size. Each person may dislike some other people, and they should not go into the same group. F...

jackzee的博客 602

GRPO算法解析:从PPO到广义奖励惩罚优化,攻克稀疏奖励强化学习难题

在强化学习领域,策略优化算法是智能体从环境中学习决策的核心引擎。其基本原理是通过与环境交互收集数据,利用策略梯度等方法更新策略参数,以最大化累积奖励。然而,在稀疏奖励、高维连续动作空间等复杂场景下,传统算法如PPO(近端策略优化)常面临训练不稳定、数据效率低等挑战。GRPO(广义奖励惩罚优化)算法通过引入一个可灵活配置的惩罚项,显式约束当前策略与任意参考策略(如旧策略、先验策略或目标策略)之间的差异,从而在保持训练稳定性的同时,显著提升了在机器人灵巧操作等任务中的学习效率。该框架天然支持模仿学习、课程学习等

dengjuanshou7445的博客 451

886. 可能的二分法

在该方法中,首先创建了一个长度为n+1的整型数组color,用于标记节点的颜色,以及一个长度为n+1的List数组g,用于表示图的邻接表。接着,对每个节点进行深度优先搜索(dfs),如果发现有节点与相邻节点颜色相同,则返回false,表示无法进行二分。在该方法中,首先将当前节点标记为当前颜色,然后遍历当前节点的相邻节点,如果发现相邻节点与当前节点颜色相同,则返回false,表示无法进行二分。如果相邻节点未被标记颜色,则递归调用dfs方法,并将颜色取反后的值传入,直到遍历完所有与当前节点相邻的节点。

Wzideng@qq.com 552

of_graph_get_remote_port

isp { compatible = "isp"; core@0 { id = <0>; ports { #address-cells = <1>; #size-cells = <0>; port@0 { reg = <0>; ...

wmzjzwlzs的专栏 1171

verilog实现步进电机脉冲分配器(三相六拍)基于Nexys4DDR开发板

使用Verilog HDL设计的一个能够自启动、具有正反转功能的三相六拍步进电机脉冲分配器。已经写好Nexy4DDR的管脚约束文件 可以通过Nexys4DDR开发板的PMOD接口连接步进电机进行调试。 使用verilog语言 在vivado2018.2下运行编译下载都正确,(也可在ISE,QuartusII下使用)下面是工程截图: ...

QQ_778132974的博客 2601

【LeetCode】886. Possible Bipartition 解题报告(Python)

【LeetCode】886. Possible Bipartition 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/possible-bipartition/description/ 题目描述: Given a set of...

负雪明烛 2273

写给开发人员的实用密码学 - Hash算法

说到Hash(哈希),开发人员应该不陌生,比如Hash表是一种非常常用的数据结构,通过Hash表能够根据键值快速找到数据。哈希函数将文本(或其他数据)映射为整数,从而能够提高检索效率。密...

云水木石 1512

LeetCode 886. Possible Bipartition

文章目录题目描述结果知识点实现码前思考代码实现码后反思 题目描述 结果 知识点 图的遍历BFS+DFS,二分图 实现 码前思考 二分图题就是图顶点着色问题,就是在图DFS上增加一些额外的操作,模板还是DFS的! 注意非连通图的情况! 代码实现 //数组下标从1开始 class Solution { private: const static int maxn = 2010; ...

yc_cy1999的博客 178

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

inori mmd 7z

楪祈的模型资源....................................................................................................................................................................................................................

LeetCode 886. Possible Bipartition?

Given a set of N people (numbered 1, 2, …, N), we would like to split everyone into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Formally, if dislikes[i] = [a, b], it means it is not allowed

Tech in Pieces 438

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

[Swift]LeetCode886. 可能的二分法 | Possible Bipartition

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/stren...

weixin_30279751的博客 199

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

886. Possible Bipartition

886. Possible Bipartition方法1: dfs方法2: bfs方法3: Union find Given a set of N people (numbered 1, 2, …, N), we would like to split everyone into two groups of any size. Each person may dislike some other ...

wilzxu的博客 244

[leetcode] 886. Possible Bipartition

Description Given a set of N people (numbered 1, 2, …, N), we would like to split everyone into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Formally, if dislikes[i] = [a, b], it means it is

Learning from the mistakes 206

【Leetcode】886. Possible Bipartition

题目地址: https://leetcode.com/problems/possible-bipartition/ 给定一个无向图的一系列边,要求每个边的端点都不能涂上相同颜色,问是否存在涂色方法。题目保证不存在平行边和环。 本质上是判断图是否是二分图。 法1:DFS。从每个未访问的顶点开始做DFS,同时给每个顶点染色,遍历下一个顶点的时候则染成不一样的颜色。当发现本顶点和下一个顶点颜色相同的时候返回false。代码如下: import java.util.ArrayList; import java.ut

数学、算法爱好者的博客 415

LeetCode C++ 886. Possible Bipartition【DFS/二分图】中等

Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size. Each person may dislike some other people, and they should not go into the same group.  Formally, if dislikes[i] = [a, b], it means it i

memcpy0的博客 472

886. Possible Bipartition [JavaScript]

一、题目 Given a set of N people (numbered 1, 2, …, N), we would like to split everyone into two groups of any size. Each person may dislike some other people, and they should not go into the same group. ...

descire 197

LeetCode 27 May, Possible Bipartition, 图的可能分割

Possible Bipartition Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Formally, if dislikes[i] = [a, b], it

weixin_46391502的博客 247

LeetCode周赛97 890. Possible Bipartition C++ [自己开发的博客网站,欢迎访问](www.weiboke.online) www.weiboke.online

890. Possible Bipartition Given a set of N people (numbered 1, 2, …, N), we would like to split everyone into two groups of any size. Each person may dislike some other people, and they should not g...

WXM 559

LeetCode 3884.双端字符匹配:半次遍历

LeetCode 3884.双端字符匹配:半次遍历 给你一个长度为 n 的字符串 s,其中只包含小写英文字母。 返回最小的下标 i,使得 s[i] == s[n - i - 1]。 如果不存在这样的下标,返回 -1。

<font color="Pink">Tisfy的博客</font> 167

力扣 1201. 丑数 III

LeetCode 原题:1201. 丑数 III 今天的每日一题 只能说还可以,不是很难,虽然我一开始也没想到,我本来以为这个题类似归并排序的 那种,把每个数的前n个小的倍数放到一个优先对列中,不过这样有重复的,之后换成set 还是不行超时了。看到题解才恍然大悟,可以用二分和容斥原理来判断这个数前面有多少数比它小……给定四个整数 、、、。如果一个正整数能够被 、、 中的至少一个整除,那么它就是丑数。请返回第 个丑数。示例: 二、解题思路 这道题的核心是:二分答案 + 容斥原理。可以把它想象成三个社团分别招

yydschdyyds的博客 197

【LeetCode 热题 100】142. 环形链表 II|哈希表、快慢指针(Python)

【LeetCode 热题 100】【142. 环形链表 II】|哈希表、快慢指针(Python)

weixin_70673823的博客 346
上一篇: leetcode 872. Leaf-Similar Trees(叶子相似的树)
下一篇: leetcode 897. Increasing Order Search Tree(递增序二叉搜索树)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址