From 9ba65d70afb7cf4fd29d1d6e8648279b7676c4d4 Mon Sep 17 00:00:00 2001 From: oncsr Date: Mon, 10 Feb 2025 16:09:06 +0900 Subject: [PATCH] =?UTF-8?q?[20250210]=20BOJ=20/=20=ED=94=8C=EB=9E=985=20/?= =?UTF-8?q?=20OMOI=20/=20=EA=B6=8C=ED=98=81=EC=A4=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- khj20006/202502/10 BOJ P5 OMOI.md | 91 +++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 khj20006/202502/10 BOJ P5 OMOI.md diff --git a/khj20006/202502/10 BOJ P5 OMOI.md b/khj20006/202502/10 BOJ P5 OMOI.md new file mode 100644 index 00000000..18128820 --- /dev/null +++ b/khj20006/202502/10 BOJ P5 OMOI.md @@ -0,0 +1,91 @@ +```java + +import java.util.*; +import java.io.*; + +class Main { + + // IO field + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); + static StringTokenizer st; + + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} + static int nextInt() {return Integer.parseInt(st.nextToken());} + static long nextLong() {return Long.parseLong(st.nextToken());} + static void bwEnd() throws Exception {bw.flush();bw.close();} + + // Additional field + static int[] C; + static List[] V; + static int N; + static int[] cnt, mn; + static long[] sum; + static long ans = 0; + + + public static void main(String[] args) throws Exception { + + ready(); + solve(); + + bwEnd(); + } + + static void ready() throws Exception{ + + N = Integer.parseInt(br.readLine()); + V = new List[N+1]; + for(int i=1;i<=N;i++) V[i] = new ArrayList<>(); + C = new int[N+1]; + cnt = new int[N+1]; + mn = new int[N+1]; + sum = new long[N+1]; + + nextLine(); + for(int i=2;i<=N;i++) V[nextInt()].add(i); + nextLine(); + for(int i=2;i<=N;i++) C[i] = nextInt(); + + } + + static void solve() throws Exception{ + + dfs(1); + bw.write(ans+"\n"); + + } + + static void dfs(int n) { + mn[n] = Integer.MAX_VALUE; + cnt[n] = 1; + sum[n] = C[n]; + int mxCnt = 0; + for(int i:V[n]) { + dfs(i); + cnt[n] += cnt[i]; + sum[n] += sum[i]; + mxCnt = Math.max(mxCnt, cnt[i]); + mn[n] = Math.min(mn[n], mn[i]); + } + ans += sum[n] - C[n]; + if(mxCnt > cnt[n]-1-mxCnt) { + long rem = cnt[n]-1 - (cnt[n]-1-mxCnt)*2; + int minValue = Integer.MAX_VALUE; + for(int i:V[n]) { + if(cnt[i] == mxCnt) continue; + minValue = Math.min(minValue, mn[i]); + } + ans += rem * minValue; + } + else { + if((cnt[n]-1) % 2 != 0) { + ans += mn[n]; + } + } + mn[n] = Math.min(mn[n], C[n]); + } + +} + +```