AcWing 846. 樹的重心(DFS)
阿新 • • 發佈:2021-10-20
題目連線: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); } }