|
| 1 | +```java |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | +import java.io.*; |
| 5 | + |
| 6 | +class Main { |
| 7 | + |
| 8 | + // IO field |
| 9 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 10 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 11 | + static StringTokenizer st; |
| 12 | + |
| 13 | + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} |
| 14 | + static int nextInt() {return Integer.parseInt(st.nextToken());} |
| 15 | + static long nextLong() {return Long.parseLong(st.nextToken());} |
| 16 | + static void bwEnd() throws Exception {bw.flush();bw.close();} |
| 17 | + |
| 18 | + // Additional field |
| 19 | + static int[] C; |
| 20 | + static List<Integer>[] V; |
| 21 | + static int N; |
| 22 | + static int[] cnt, mn; |
| 23 | + static long[] sum; |
| 24 | + static long ans = 0; |
| 25 | + |
| 26 | + |
| 27 | + public static void main(String[] args) throws Exception { |
| 28 | + |
| 29 | + ready(); |
| 30 | + solve(); |
| 31 | + |
| 32 | + bwEnd(); |
| 33 | + } |
| 34 | + |
| 35 | + static void ready() throws Exception{ |
| 36 | + |
| 37 | + N = Integer.parseInt(br.readLine()); |
| 38 | + V = new List[N+1]; |
| 39 | + for(int i=1;i<=N;i++) V[i] = new ArrayList<>(); |
| 40 | + C = new int[N+1]; |
| 41 | + cnt = new int[N+1]; |
| 42 | + mn = new int[N+1]; |
| 43 | + sum = new long[N+1]; |
| 44 | + |
| 45 | + nextLine(); |
| 46 | + for(int i=2;i<=N;i++) V[nextInt()].add(i); |
| 47 | + nextLine(); |
| 48 | + for(int i=2;i<=N;i++) C[i] = nextInt(); |
| 49 | + |
| 50 | + } |
| 51 | + |
| 52 | + static void solve() throws Exception{ |
| 53 | + |
| 54 | + dfs(1); |
| 55 | + bw.write(ans+"\n"); |
| 56 | + |
| 57 | + } |
| 58 | + |
| 59 | + static void dfs(int n) { |
| 60 | + mn[n] = Integer.MAX_VALUE; |
| 61 | + cnt[n] = 1; |
| 62 | + sum[n] = C[n]; |
| 63 | + int mxCnt = 0; |
| 64 | + for(int i:V[n]) { |
| 65 | + dfs(i); |
| 66 | + cnt[n] += cnt[i]; |
| 67 | + sum[n] += sum[i]; |
| 68 | + mxCnt = Math.max(mxCnt, cnt[i]); |
| 69 | + mn[n] = Math.min(mn[n], mn[i]); |
| 70 | + } |
| 71 | + ans += sum[n] - C[n]; |
| 72 | + if(mxCnt > cnt[n]-1-mxCnt) { |
| 73 | + long rem = cnt[n]-1 - (cnt[n]-1-mxCnt)*2; |
| 74 | + int minValue = Integer.MAX_VALUE; |
| 75 | + for(int i:V[n]) { |
| 76 | + if(cnt[i] == mxCnt) continue; |
| 77 | + minValue = Math.min(minValue, mn[i]); |
| 78 | + } |
| 79 | + ans += rem * minValue; |
| 80 | + } |
| 81 | + else { |
| 82 | + if((cnt[n]-1) % 2 != 0) { |
| 83 | + ans += mn[n]; |
| 84 | + } |
| 85 | + } |
| 86 | + mn[n] = Math.min(mn[n], C[n]); |
| 87 | + } |
| 88 | + |
| 89 | +} |
| 90 | + |
| 91 | +``` |
0 commit comments