二十三 3465. 病毒溯源 (邻接表|DFS)

3465. 病毒溯源 (邻接表|DFS)
image

数组模拟邻接表讲解,h表示每个结点的第一条邻边的编号,e表示每条边的终点,ne表示每条边下一条邻边的编号。

import java.util.*;

public class Main {
    private static final int N = 10010, M = 10010;
    private static int n, idx;
    private static int[] h = new int[N];
    private static int[] e = new int[M], ne = new int[M];
    private static int[] son = new int[N];
    private static boolean[] st = new boolean[N];
    
    private static void add(int a, int b) {
        e[idx] = b;
        ne[idx] = h[a];
        h[a] = idx++;
    }
    
    private static int dfs(int u) {
        int res = 0;
        son[u] = -1;
        for (int i = h[u]; i != -1; i = ne[i]) {
            int j = e[i];
            int d = dfs(j);
            if (res < d) {
                res = d;
                son[u] = j;
            }
            else if (res == d) {
                son[u] = Math.min(son[u], j);
            }
        }
        return res + 1;
    }
    
    public static void main(String[] args) {
        Arrays.fill(h, -1);
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        
        for (int i = 0; i < n; i++) {
            int cnt;
            cnt = sc.nextInt();
            while(cnt-- > 0) {
                int x;
                x = sc.nextInt();
                add(i, x);
                st[x] = true;
            }
        }
        
        int root = 0;
        while(st[root]) {
            root++;
        }
        
        System.out.println(dfs(root));
        System.out.print(root);
        while (son[root] != -1) {
            root = son[root];
            System.out.print(" " + root);
        }
    }
}
posted @   he0707  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示