Home Backend Development PHP Tutorial Divide Nodes Into the Maximum Number of Groups

Divide Nodes Into the Maximum Number of Groups

Jan 30, 2025 am 10:03 AM

2493. Divide Nodes Into the Maximum Number of Groups

Difficulty: Hard

Topics: Breadth-First Search, Union Find, Graph

You are given a positive integer n representing the number of nodes in an undirected graph. The nodes are labeled from 1 to n.

You are also given a 2D integer array edges, where edges[i] = [ai, bi] indicates that there is a bidirectional edge between nodes ai and bi. Notice that the given graph may be disconnected.

Divide the nodes of the graph into m groups (1-indexed) such that:

  • Each node in the graph belongs to exactly one group.
  • For every pair of nodes in the graph that are connected by an edge [ai, bi], if ai belongs to the group with index x, and bi belongs to the group with index y, then |y - x| = 1.

Return the maximum number of groups (i.e., maximum m) into which you can divide the nodes. Return -1 if it is impossible to group the nodes with the given conditions.

Example 1:

Divide Nodes Into the Maximum Number of Groups

  • Input: n = 6, edges = [[1,2],[1,4],[1,5],[2,6],[2,3],[4,6]]
  • Output: 4
  • Explanation: As shown in the image we:
    • Add node 5 to the first group.
    • Add node 1 to the second group.
    • Add nodes 2 and 4 to the third group.
    • Add nodes 3 and 6 to the fourth group.
    • We can see that every edge is satisfied.
    • It can be shown that that if we create a fifth group and move any node from the third or fourth group to it, at least on of the edges will not be satisfied.

Example 2:

  • Input: n = 3, edges = [[1,2],[2,3],[3,1]]
  • Output: -1
  • Explanation: If we add node 1 to the first group, node 2 to the second group, and node 3 to the third group to satisfy the first two edges, we can see that the third edge will not be satisfied.
    • It can be shown that no grouping is possible.

Constraints:

  • 1
  • 1 4
  • edges[i].length == 2
  • 1 i, bi
  • ai != bi
  • There is at most one edge between any pair of vertices.

Hint:

  1. If the graph is not bipartite, it is not possible to group the nodes.
  2. Notice that we can solve the problem for each connected component independently, and the final answer will be just the sum of the maximum number of groups in each component.
  3. Finally, to solve the problem for each connected component, we can notice that if for some node v we fix its position to be in the leftmost group, then we can also evaluate the position of every other node. That position is the depth of the node in a bfs tree after rooting at node v.

Solution:

The problem, "Divide Nodes Into the Maximum Number of Groups", involves determining the maximum number of groups into which the nodes of an undirected graph can be divided, such that:

  1. Each node belongs to exactly one group.
  2. Adjacent nodes are in groups whose indices differ by exactly 1. If the graph is not bipartite, grouping is impossible, and the function must return -1.

Key Points

  • Graph Properties: The graph may be disconnected.
  • Validation: For each connected component, check if it is bipartite. If not, return -1.
  • Bipartite Nature: The solution involves BFS to validate bipartiteness.
  • Union-Find: Useful for grouping connected components efficiently.

Approach

  1. Preprocessing:

    • Represent the graph using an adjacency list.
    • Use Union-Find to identify connected components.
  2. BFS to Validate Bipartiteness:

    • For each connected component, use BFS to determine if it is bipartite.
    • If it is not bipartite, return -1.
  3. Calculate Group Count:

    • For each connected component, use BFS to determine the maximum depth, representing the maximum number of groups.
  4. Combine Results:

    • Sum the maximum group counts of all bipartite components.

Plan

  1. Construct the graph as an adjacency list.
  2. Use Union-Find to group connected components.
  3. For each node in the graph:
    • Use BFS to check if the graph is bipartite and calculate the maximum depth of that component.
  4. Return the sum of the depths of all components as the result. If any component is not bipartite, return -1.

Let's implement this solution in PHP: 2493. Divide Nodes Into the Maximum Number of Groups

<?php /**
 * @param Integer $n
 * @param Integer[][] $edges
 * @return Integer
 */
function magnificentSets($n, $edges) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

/**
 * @param $graph
 * @param $u
 * @return int
 */
private function bfs($graph, $u) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

class UnionFind {
    /**
     * @var array
     */
    private $id;
    /**
     * @var array
     */
    private $rank;

    /**
     * @param $n
     */
    public function __construct($n) {
       ...
       ...
       ...
       /**
        * go to ./solution.php
        */
    }

    /**
     * @param $u
     * @param $v
     * @return void
     */
    public function unionByRank($u, $v) {
       ...
       ...
       ...
       /**
        * go to ./solution.php
        */
    }

    /**
     * @param $u
     * @return mixed
     */
    public function find($u) {
       ...
       ...
       ...
       /**
        * go to ./solution.php
        */
    }
}


// Example usage:
$n = 6;
$edges = [[1,2], [1,4], [1,5], [2,6], [2,3], [4,6]];
echo maxGroups($n, $edges); // Output: 4

$n = 3;
$edges = [[1,2], [2,3], [3,1]];
echo maxGroups($n, $edges); // Output: -1
?>
Copy after login

Explanation:

1. Union-Find Class

The Union-Find (Disjoint Set Union) structure groups nodes into connected components and performs two main tasks:

  • Find: Identify the root of a node's connected component.
  • Union: Merge two connected components based on rank.

2. BFS for Bipartite Check and Depth Calculation

  • Bipartite Validation: Using BFS, assign alternating "colors" to nodes. If adjacent nodes share the same color, the graph is not bipartite.
  • Depth Calculation: Measure the depth of the BFS tree to determine the maximum number of groups.

3. Combine Results

  • Calculate the maximum depth for each connected component.
  • Add the depths for all components to determine the result.

Example Walkthrough

Example 1

Input:

$n = 6;  
$edges = [[1,2], [1,4], [1,5], [2,6], [2,3], [4,6]];
Copy after login

Steps:

  1. Construct adjacency list:
   1 -> [2, 4, 5]
   2 -> [1, 3, 6]
   3 -> [2]
   4 -> [1, 6]
   5 -> [1]
   6 -> [2, 4]
Copy after login
  1. Use BFS on connected components:
    • Component 1: Bipartite. Max depth = 4.
  2. Sum depths across all components: 4.

Output: 4

Example 2

Input:

$n = 3;  
$edges = [[1,2], [2,3], [3,1]];
Copy after login

Steps:

  1. Construct adjacency list:
   1 -> [2, 3]
   2 -> [1, 3]
   3 -> [1, 2]
Copy after login
  1. Use BFS:
    • Component 1: Not bipartite.

Output: -1

Time Complexity

  • Graph Construction: O(E), where E is the number of edges.
  • Union-Find: O(α(N)), where N is the number of nodes (almost constant due to path compression).
  • BFS: O(V E), where V is the number of vertices. Overall Complexity: O(N E)

Output for Examples

$n = 6;
$edges = [[1,2], [1,4], [1,5], [2,6], [2,3], [4,6]];
echo magnificentSets($n, $edges); // Output: 4

$n = 3;
$edges = [[1,2], [2,3], [3,1]];
echo magnificentSets($n, $edges); // Output: -1
Copy after login

This approach efficiently handles the grouping problem by leveraging BFS for bipartiteness checks and depth calculations while utilizing Union-Find to simplify component management. The solution handles both connected and disconnected graphs.

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

  • LinkedIn
  • GitHub

The above is the detailed content of Divide Nodes Into the Maximum Number of Groups. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles