当前位置:网站首页>Leetcode0886. Possible dichotomy (medium)
Leetcode0886. Possible dichotomy (medium)
2022-04-21 19:34:00 【Slow ploughing of stupid cattle】
Catalog
2.3 Train of thought three : To color + Depth-first search
1. Problem description
Give a group n people ( The number is 1, 2, ..., n), We want to divide everyone into arbitrarily Two groups of size . Everyone may not like other people , So they shouldn't belong to the same group .
Given integer n And an array dislikes , among dislikes[i] = [ai, bi] , Indicates that numbering as... Is not allowed ai and bi All the people belong to the same group . When you can divide everyone into two groups in this way , return true; Otherwise return to false.
Example 1:
Input :n = 4, dislikes = [[1,2],[1,3],[2,4]] Output :true explain :group1 [1,4], group2 [2,3]
Example 2:
Input :n = 3, dislikes = [[1,2],[1,3],[2,3]] Output :false
Example 3:
Input :n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]] Output :false
Tips :
1 <= n <= 20000 <= dislikes.length <= 10^4dislikes[i].length == 21 <= dislikes[i][j] <= nai < bidislikesEach group in the group Different
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/possible-bipartition
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
2. Problem solving analysis
2.1 Train of thought
dislikes Representing a graph edges The list represents , Let's call this picture dislike-graph.
A simple idea , Build the complement of this graph like-graph, Then check the supplementary drawing like-graph Is the number of connected subgraphs less than or equal to 2. In supplementary drawing like-graph in , The nodes in two different connected subgraphs are obviously mutual dislike Of . So if like-graph The number of connected subgraphs exceeds 2 individual , Can't be divided into 2 A group , Make sure there is no mutual dislike People who . And if the like-graph The number of connected subgraphs is equal to 2, The node set contained in these two subgraphs is the only grouping method to meet the meaning of the question . If like-graph The number of connected subgraphs is equal to 1( That is, the whole connection diagram ), Then you can divide it arbitrarily .
Of course , This like-graph There is no need to explicitly create .
Just create dislike-graph Adjacency list of ( establish like-graph The adjacency list is better than creating dislike-graph The adjacency list is troublesome , Large storage requirements ), Then based on dislike-graph The adjacency list of like-graph Traversal of , Breadth first search or depth first search .
But I drew pictures , From example 3 I find that the above idea is not correct .
2.2 Train of thought two
In fact, this problem is equivalent to looking for this dislike-graph Whether there is a ring composed of an odd number of nodes in .
(1) If there is a ring composed of an odd number of nodes , It's impossible to divide them into two groups and avoid people who don't like being divided into one group . This is obvious .
(2) When there is no ring composed of odd nodes , Can they be divided into two groups that meet the conditions ?
Let's assume that the above idea is true ( It doesn't seem to be an easy thing to prove ).
Starting from any node , Path traversal of the graph , If the newly explored node on a path already exists on the path , It means finding a loop . After finding the loop, check the length of the loop .
then , Repeat the above process , Until the traversal of the whole graph is completed .
If you find a ring with an odd length, you can exit and return False. If no ring of odd length is found, return True.
however , Search for a path , Is to find a ring and quit , Or keep searching ? Neither seems to work .
Uh ... This road seems to be impassable
2.3 Train of thought three : To color + Depth-first search
Try to assign everyone to one of two groups . Suppose the people in the first group are red , The people in the second group are blue .
If the first person is red , Then the person you don't like must be blue . then , Anyone who doesn't like blue people is red , So anyone who doesn't like red people is blue , And so on . If there is a conflict at any time , Then this task is impossible to complete , Because from the first step, every step is logical . If there is no conflict , So coloring is effective , It shows that it is feasible to divide into two groups .
Consider by N Made up of individuals dislike-graph,dislikes The array represents the change of the graph edge list.
Based on the above ideas , We need to check whether each connected branch of the graph is a bipartite graph .
For each connected part , We just try to color it with two colors , You can check whether it is binary . You can do depth first search as follows ( The search of this question is related to the path , You can't use breadth first search ):
- Color any node red , Then paint all its neighbors blue , Then paint all the neighbors' neighbors red , And so on . If the search process finds that a node ready to be painted blue has been painted red before ( Or vice versa ) It shows that there is a conflict , Grouping cannot be established , The end of the search .
- After the above traversal , Start a new traversal by selecting any one of the remaining uncolored nodes .
- Repeat the above steps 2 Until all nodes are colored ( To be accessed ), Or withdraw early due to conflict .
3. Code implementation
import time
from typing import List
from collections import deque
class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
if n == 1:
return True
# construct adjacency list
adjlist = [[] for k in range(n+1)]
for dislike in dislikes:
adjlist[dislike[0]].append(dislike[1])
adjlist[dislike[1]].append(dislike[0])
color = (n+1) * [-1]
for k in range(1,n+1):
if color[k] < 0:
q = deque([k])
color[k] = 0
while len(q)>0:
node = q.pop()
for adj in adjlist[node]:
if color[adj] < 0:
color[adj] = 1 - color[node]
q.append(adj)
else:
if color[adj] == color[node]:
return False
return True
if __name__ == "__main__":
sln = Solution()
n = 4
dislikes = [[1,2],[1,3],[2,4]]
print(sln.possibleBipartition(n, dislikes))
n = 3
dislikes = [[1,2],[1,3],[2,3]]
print(sln.possibleBipartition(n, dislikes))
n = 5
dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
print(sln.possibleBipartition(n, dislikes))
Execution time :108 ms, In all Python3 Defeated in submission 91.64% Users of
Memory consumption :18.4 MB, In all Python3 Defeated in submission 89.10% Users of
Um. , Can perform well in both time and memory , It's worth a little pride .
Spit a small slot :n=1 When you press leetcode Your feedback should go back to True, But this is actually a question of definition .leetcode Take this as a testcase A little boring . It's better to define n>=2 Isn't it more refreshing .
Go back to the general catalogue : Slow ploughing by stupid cattle Leetcode General catalogue of daily questions ( Dynamic update ...)
版权声明
本文为[Slow ploughing of stupid cattle]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204211927525086.html
边栏推荐
- 使用mRemoteNG工具管理所有远程连接
- 山东大学项目实训(四)多个点标记添加点击事件
- Abbexa donkey anti goat IgG (H & L) antibody
- 【网络协议】ip addr
- Introduction to GPS Beidou satellite time synchronization system (clock device) technology of power grid
- 邮件在Exchange中的路由过程
- Redis installation and configuration startup
- 108. Convert an ordered array into a binary search tree (picture and text merging)
- Research Report on the development of auction industry in 2021
- MusicPlayer2.1版本
猜你喜欢

Rk3399 - add USB to serial driver

Linux Centos7 安装MySql8 (简单、实测可行)

Interviewer: a brief talk about go escape analysis?

im即时通讯开发技术:100到1000万高并发的架构演进

Joining Tsinghua full time, Qiu Chengtong: cultivating mathematics talents for the motherland and the global mathematics community

Alternative JC-1, mito-id series mitochondrial membrane potential detection kit

Using MCU Xpress to develop rt1060 (1) -- drive RGB interface LCD

Some keywords of the robotframework cannot be used or are black

Redis installation and configuration startup

MySQL数据库索引面试题(最新版)
随机推荐
面试官:简单聊聊 Go 逃逸分析?
静态链接与动态链接
OpenHarmony Sensor 模块Callback注册和回调全流程
Daily CISSP certification common mistakes (April 20, 2022)
Big guys, why is it 10 times slower to call functions in this way?
im即时通讯开发技术:100到1000万高并发的架构演进
Comparison of F (ab ') 2 IgG isotype in abbexa goat
Easygbs has closed the video recording plan. Why are video files still generated?
AAAI 2022 finer grained false information detection
若依集成actuator实现优雅关闭应用
C# 将dll打包到程序中
robotframework日志输出中文乱码
5.1 overview of triggers in fundamentals of digital electronic technology
switch分支
leetcode344. 反转字符串
Joining Tsinghua full time, Qiu Chengtong: cultivating mathematics talents for the motherland and the global mathematics community
邮件在Exchange中的路由过程
学完这篇Charles抓包教程,我直接把fiddler卸载了
Webrtc video cannot be played. How to add UDP hole drilling program in easycvr?
到底什么是外包?