{ "cells": [ { "cell_type": "markdown", "source": [ "Given a set of `N` people (numbered `1, 2, ..., N`), we would like to split\n", "everyone into two groups of **any** size.\n", "\n", "Each person may dislike some other people, and they should not go into the\n", "same group.\n", "\n", "Formally, if `dislikes[i] = [a, b]`, it means it is not allowed to put the\n", "people numbered `a` and `b` into the same group.\n", "\n", "Return `true` if and only if it is possible to split everyone into two groups\n", "in this way.\n", "\n", "\n", "\n", "**Example 1:**\n", "\n", "\n", "\n", " Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]\n", " Output: true\n", " **Explanation** : group1 [1,4], group2 [2,3]\n", "\n", "\n", "**Example 2:**\n", "\n", "\n", "\n", " Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]\n", " Output: false\n", "\n", "\n", "**Example 3:**\n", "\n", "\n", "\n", " Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]\n", " Output: false\n", "\n", "\n", "\n", "\n", "**Constraints:**\n", "\n", " * `1 <= N <= 2000`\n", " * `0 <= dislikes.length <= 10000`\n", " * `dislikes[i].length == 2`\n", " * `1 <= dislikes[i][j] <= N`\n", " * `dislikes[i][0] < dislikes[i][1]`\n", " * There does not exist `i != j` for which `dislikes[i] == dislikes[j]`." ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "possible_bipartition (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "\n", "using DataStructures\n", "function possible_bipartition(n::Int, dislikes::Vector{Vector{Int}})\n", " int_ds = IntDisjointSets(n)\n", " graph = [Int[] for _ in 1:n]\n", " for (a, b) in dislikes\n", " push!(graph[a], b)\n", " push!(graph[b], a)\n", " end\n", " for i in 1:n\n", " for j in graph[i]\n", " union!(int_ds, graph[i][1], j)\n", " DataStructures.in_same_set(int_ds, i, j) && return false\n", " end\n", " end\n", " return true\n", "end\n", "# @lc code=end" ], "metadata": {}, "execution_count": 1 }, { "cell_type": "markdown", "source": [ "---\n", "\n", "*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*" ], "metadata": {} } ], "nbformat_minor": 3, "metadata": { "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.10.1" }, "kernelspec": { "name": "julia-1.10", "display_name": "Julia 1.10.1", "language": "julia" } }, "nbformat": 4 }