最多邀请的个数
难度:
标签:
题目描述
代码结果
运行时间: 96 ms, 内存: 18.5 MB
/*
* Leetcode Problem 1820: Maximum Number of Invitations
*
* Problem Description: Given an array of integers where each integer represents the index of another person that can be invited to a party, the task is to find the maximum number of people that can be invited such that no two people invite each other.
*
* Approach using Java Streams:
* 1. Convert the invitations array to a list of pairs representing the graph edges.
* 2. Use Streams to process and find cycles and maximum path lengths.
* 3. Combine the results to find the maximum number of invites.
*/
import java.util.*;
import java.util.stream.*;
public class MaxInvitationsStream {
public int maximumInvitations(int[] favorite) {
int n = favorite.length;
List<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for (int i = 0; i < n; i++) {
graph[favorite[i]].add(i);
}
int[] dp = new int[n];
boolean[] visited = new boolean[n];
boolean[] inStack = new boolean[n];
return IntStream.range(0, n).filter(i -> !visited[i]).map(i -> dfs(i, graph, dp, visited, inStack)).max().orElse(0);
}
private int dfs(int node, List<Integer>[] graph, int[] dp, boolean[] visited, boolean[] inStack) {
if (visited[node]) {
return dp[node];
}
visited[node] = true;
inStack[node] = true;
int maxLength = 1;
for (int nextNode : graph[node]) {
if (!visited[nextNode]) {
maxLength = Math.max(maxLength, 1 + dfs(nextNode, graph, dp, visited, inStack));
} else if (inStack[nextNode]) {
maxLength = 0; // Cycle detected
}
}
dp[node] = maxLength;
inStack[node] = false;
return dp[node];
}
public static void main(String[] args) {
MaxInvitationsStream mis = new MaxInvitationsStream();
int[] favorite = {2, 2, 1, 2};
System.out.println(mis.maximumInvitations(favorite)); // Output: 3
}
}
解释
方法:
这道题可以使用匈牙利算法来求解二分图的最大匹配。首先,将给定的网格视为一个二分图,其中每个行和列分别代表二分图的两个部分。如果网格中的某个位置是1,那么就在对应的行和列之间添加一条边。接着,使用匈牙利算法来找出二分图的最大匹配。匈牙利算法的核心思想是通过增广路径来不断地增加匹配的数量。当找不到增广路径时,算法结束,此时的匹配数量就是二分图的最大匹配。
时间复杂度:
O((m+n) * E)
空间复杂度:
O(E + V)
代码细节讲解
🦆
为什么需要将网格问题转换成二分图来解决,这样的转换有什么好处?
▷🦆
在匈牙利算法中,如何确定一个路径是增广路径,它的具体标准是什么?
▷🦆
匈牙利算法中提到的‘增广路径’是在哪一步操作中被寻找的,能否详细解释其过程?
▷