Guest User

wealth desparity

a guest
Mar 7th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.Arrays;
  5.  
  6. import static java.lang.Integer.MIN_VALUE;
  7. import static java.lang.Integer.max;
  8.  
  9. /**
  10.  * Created by bugkiller on 08/03/18.
  11.  */
  12. class WealthDisparity {
  13.  
  14.     static int a[] = new int[100001];
  15.     static int p[] = new int[100001];
  16.     static int diff[] = new int[100001];
  17.     static final int NOT_DEFINED = MIN_VALUE;
  18.  
  19.     public static void main(String[] args) throws IOException {
  20.  
  21.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  22.         String s[];
  23.         int n;
  24.         s = br.readLine().split("\\s");
  25.         n = Integer.parseInt(s[0]);
  26.         for (int i = 1,j=1; i < s.length; i++) {
  27.             if (i <= n) {
  28.                 a[i] = Integer.parseInt(s[i]);
  29.             }
  30.             else {
  31.                 p[j++] = Integer.parseInt(s[i]);
  32.             }
  33.         }
  34.         System.out.println(solve(a, p, n));
  35.     }
  36.  
  37.     private static int solve(int[] a, int[] p, int n) {
  38.  
  39.         if (n == 1) {
  40.             return 0;
  41.         }
  42.         int ans = MIN_VALUE;
  43.         Arrays.fill(diff, MIN_VALUE);
  44.         for (int i = 1; i <= n; i++) {
  45.             if (p[i] != -1) {
  46.                 ans = max(ans, getDiff(i));
  47.             }
  48.         }
  49.         return ans;
  50.     }
  51.  
  52.     private static int getDiff(int i) {
  53.  
  54.         if (p[p[i]] == -1) {
  55.             diff[i] = a[p[i]] - a[i];
  56.             return diff[i];
  57.         }
  58.         if (diff[i] != NOT_DEFINED) {
  59.             return diff[i];
  60.         }
  61.         if (diff[p[i]] != NOT_DEFINED) {
  62.             diff[p[i]] = getDiff(p[i]);
  63.         }
  64.         int temp = diff[p[i]] + a[p[i]];
  65.         diff[i] = temp - a[i];
  66.         diff[i] = max(diff[i], a[p[i]] - a[i]);
  67.         return diff[i];
  68.     }
  69.  
  70. }
Add Comment
Please, Sign In to add comment