二十三 3465. 病毒溯源 (邻接表|DFS)
数组模拟邻接表讲解,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);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构