AcWing 846. 树的重心(DFS)
题目连接:https://www.acwing.com/problem/content/description/848/
错误代码分析:
重点就在于这句话:
t2 += son[e[j]];
并不是每一个子节点都应该被加上,这个过程只能在深搜时进行,因为st数组在深搜后就无效了,所以这么写为错的。
错误代码:
import java.util.*;
public class Main {
static int N = (int) 1e5 + 10;
static int[] h = new int[N], ne = new int[N], e = new int[N];
static int[] st = new int[N], son = new int[N];
static int idx = 0;
static {
Arrays.fill(h, -1);
}
static void add(int x, int y) {
e[idx] = y;
ne[idx] = h[x];
h[x] = idx ++;
}
static void dfs(int x) {
st[x] = 1;
son[x] ++;
for (int i = h[x]; i != -1; i = ne[i]) {
int y = e[i];
if(st[y] == 0) {
dfs(y);
son[x] += son[y];
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n - 1; i ++ ) {
int x = sc.nextInt(), y = sc.nextInt();
add(x, y);
add(y, x);
}
dfs(1);
// for (int i = 1; i <= n; i ++)
// System.out.println(i + ": " + son[i]);
// System.out.println("------------------------------------");
int res = N;
for (int i = 1; i <= n; i ++) {
int t = -1, t2 = 0;
for (int j = h[i]; j != -1; j = ne[j]) {
t2 += son[e[j]];
t = Integer.max(t, son[e[j]]);
}
// System.out.println(i + ": " + t);
t = Integer.max(t, n - t2 - 1);
// System.out.println(i + ": " + t);
res = Integer.min(res, t);
}
System.out.println(res);
}
}
AC代码:
import java.util.*;
public class Main {
static int N = (int) 1e5 + 10;
static int[] h = new int[N], ne = new int[N * 2], e = new int[N * 2];
static int[] st = new int[N];
static int idx = 0, res = N, n;
static {
Arrays.fill(h, -1);
}
static void add(int x, int y) {
e[idx] = y;
ne[idx] = h[x];
h[x] = idx ++;
}
static int dfs(int x) {
st[x] = 1;
int tn = 0, tmax = -1;
for (int i = h[x]; i != -1; i = ne[i]) {
int y = e[i];
if(st[y] == 0) {
int t = dfs(y);
tn += t;
tmax = Integer.max(tmax, t);
}
}
tmax = Integer.max(tmax, n - tn - 1);
res = Integer.min(res, tmax);
return tn + 1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (int i = 0; i < n - 1; i ++ ) {
int x = sc.nextInt(), y = sc.nextInt();
add(x, y);
add(y, x);
}
dfs(1);
System.out.println(res);
}
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法