2360. Longest Cycle in a Graph

给定一个有向图,每个节点最多有一个出边。返回图中最长循环的长度,若无循环则返回-1。通过 BFS 更新节点的父节点及距离,当发现环路时,计算环路长度并更新答案。

You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.

The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.

Return the length of the longest cycle in the graph. If no cycle exists, return -1.

A cycle is a path that starts and ends at the same node.

Example 1:

Input: edges = [3,3,4,2,3]
Output: 3

Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.
The length of this cycle is 3, so 3 is returned.

Example 2:

Input: edges = [2,-1,3,1]
Output: -1

Explanation: There are no cycles in this graph.

Constraints:

  • n == edges.length
  • 2 <= n <= 105
  • -1 <= edges[i] < n
  • edges[i] != i

每一个 node 可能有多个 from, 但是 to 只有一个, 所以我们将每个 node 的 to 收集起来作为当前 node 的 parents, 同时记录下 node[i]与 parents[i]的距离, 我们 bfs 更新 parents, 假设 parents[i] = (parent, parent_distance), parents[parent] = (parent_of_parent, parent_of_parent_distance), 那我们就可以更新 parents[i] = (parent_of_parent, parent_distance + parent_of_parent_distance), 但是要注意, 如果 parent == parent_of_parent 则证明 parents[parent]已经形成环路了, 我们就没必要再更新当前 parents[i]了, 因为此时 parent_distance + parent_of_parent_distance 是当前节点到环路的入口节点之间的距离加上环路的长度, 对我们的答案没有任何用处。如果 parent_of_parent == i, 则证明当前节点形成环路了, 此时的 parent_distance + parent_of_parent_distance 就是环路的长度, 我们只需要收集该值的最大值就是最终答案了


impl Solution {
    pub fn longest_cycle(edges: Vec<i32>) -> i32 {
        let mut parents: Vec<(i32, i32)> = edges.into_iter().map(|v| (v, 1)).collect();
        let mut ans = 0;
        loop {
            let mut changed = false;
            for i in 0..parents.len() {
                if parents[i].0 < 0 {
                    continue;
                }
                let (p, pn) = parents[i];
                let (pp, ppn) = parents[p as usize];
                if p == pp {
                    continue;
                }
                parents[i] = (pp, pn + ppn);
                changed = true;
                if pp == i as i32 {
                    ans = ans.max(pn + ppn);
                }
            }
            if !changed {
                break;
            }
        }
        if ans == 0 {
            -1
        } else {
            ans
        }
    }
}

2.1 图模型定义 (类型:无向、加权/无权、是否含多重边等;顶点与边的实际含义(如:顶点=城市,边=公路)) 2.2 构建方法 (数据来源:真实数据(需注明出处)或仿真生成(如随机图模型);工具:Python的NetworkX) 2.3 可视化展示 3、图的性质分析与计算 输出点、边数量------- num_nodes = G.number_of_nodes() num_edges = G.number_of_edges() 输出一条边的属性 举例 判断是否有点 G.has_node(a) 判断是否有边 G.has_edge(u,v) 输出点a的所有邻居 G.neighbors(a) 输出图邻接对象 G.adj 输出度序列:非增序列 G.degree() 最大度: 最小度: 删除图上度最大的点 输出邻接矩阵 A adj_matrix = nx.adjacency_matrix(G) adj_dense = adj_matrix.todense() 输出关联矩阵 M inc_matrix = nx.incidence_matrix(G) inc_dense = inc_matrix.todense() 输出生成子图 edges_to_keep = [(1, 2), (2, 3), (3, 4), (4, 1)] H = nx.edge_subgraph(G, edges_to_keep) 输出最小生成树 mst = nx.minimum_spanning_tree(G) 输出点导出子图 H = G.subgraph(nodes_subset) 输出边导出子图 edges_subset = [(1, 2), (3, 4)] H = nx.edge_subgraph(G, edges_subset) 计算图的连通分支数目num_components = nx.number_connected_components(G) components = list(nx.connected_components(G)) print("各连通分支的节点集合:", components) 找出图的割点和割边 cut_vertices = list(nx.articulation_points(G)) cut_edges = list(nx.bridges(G)) 找出图的补图 G_complement = nx.complement(G) 计算所有节点对的最短路径长度 lengths = dict(nx.all_pairs_shortest_path_length(G)) 计算半径 r = nx.radius(G) 计算直径 d = nx.diameter(G) 获取中心点 center_nodes = nx.center(G) 计算周长 cycles = list(nx.simple_cycles(G.to_directed())) longest_cycle = max(cycles, key=len, default=[]) circumference = len(longest_cycle) 点连通度 # 图的整体点连通度 k_v = nx.node_connectivity(G) # 两点间的点连通度(如节点 0 和 33) k_v_pair = nx.node_connectivity(G, s=0, t=33) 边连通度 # 图的整体边连通度 k_e = nx.edge_connectivity(G) # 两点间的边连通度 k_e_pair = nx.edge_connectivity(G, s=0, t=33) 找出最小点割集 cut_set = nx.minimum_node_cut(G) 找出最小边割集 cut_edges = nx.minimum_edge_cut(G) 计算最大匹配 matching = nx.algorithms.matching.max_weight_matching(G, maxcardinality=True) # 输出结果(每条匹配边) print("最大匹配结果:") for u, v in matching: print(f"{u} -- {v}") 按照上面格式,根据代码写图模型定义,构建方法,可视化展示,图的性质分析与计算
最新发布
05-28
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值