(in-package :cl-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx opt
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (set-dispatch-macro-character #\# #\> #'cl-debug-print:debug-print-reader)

(macrolet ((def-int (b)
             `(progn (deftype ,(intern (format nil "UINT~A" b)) () '(unsigned-byte ,b))
                     (deftype ,(intern (format nil "INT~A" b)) () '(signed-byte ,b))))
           (defs (&rest bits) `(progn ,@(mapcar (lambda (b) `(def-int ,b)) bits))))
  (defs 2 4 7 8 15 16 31 32 62 63 64))

(defconstant +mod+ 1000000007)

(defmacro dbg (&rest forms)
  #+swank (if (= (length forms) 1)
              `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
              `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

(declaim (inline println))
(defun println (obj &optional (stream *standard-output*))
  (let ((*read-default-float-format* 'double-float))
    (prog1 (princ obj stream) (terpri stream))))

;; BEGIN_INSERTED_CONTENTS
(defpackage :cp/modify-macro
  (:use :cl)
  (:export #:minf #:maxf #:mulf #:divf #:iorf #:xorf #:andf))
(in-package :cp/modify-macro)

(macrolet ((def (name fname)
             `(define-modify-macro ,name (new-value) ,fname)))
  (def minf min)
  (def maxf max)
  (def mulf *)
  (def divf /)
  (def iorf logior)
  (def xorf logxor)
  (def andf logand))

;; BEGIN_USE_PACKAGE
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/modify-macro :cl-user))
(in-package :cl-user)

;;;
;;; Body
;;;

(defconstant +inf+ most-positive-fixnum)
(defun main ()
  (let* ((n (read))
         (as (make-array n :element-type 'int32 :initial-element 0))
         (graph (make-array n :element-type 'list :initial-element nil))
         (sizes (make-array n :element-type 'uint31 :initial-element 0))
         (gs (make-array n :element-type 'uint62 :initial-element +inf+)))
    (dotimes (i n)
      (setf (aref as i) (read)))
    (dotimes (i (- n 1))
      (let ((u (- (read) 1))
            (v (- (read) 1)))
        (push u (aref graph v))
        (push v (aref graph u))))
    (sb-int:named-let dfs ((v 0) (parent -1))
      (let ((size 1))
        (dolist (child (aref graph v))
          (unless (= child parent)
            (dfs child v)
            (incf size (aref sizes child)))
          (setf (aref sizes v) size))))
    (labels ((%merge (dp1 dp2 child)
               (declare ((simple-array fixnum (*)) dp1 dp2))
               (let* ((n1 (length dp1))
                      (n2 (length dp2))
                      (res-dp (make-array (+ n1 n2) :element-type 'fixnum :initial-element 0)))
                 
                 (dotimes (y (length res-dp))
                   (let ((value +inf+))
                     (declare (fixnum value))
                     (loop for i from (max (+ 1 (- y n2)) 0) to (min y (- n1 1))
                           for j = (- y i)
                           do (assert (and (<= 0 i (- n1 1))
                                           (<= 0 j (- n2 1))))
                              (minf value (+ (aref dp1 i) (aref dp2 j))))
                     (loop for i from (max (+ 1 (- y n2)) 0) to (min (- y 1) (- n1 1))
                           for j = (- y i 1)
                           do (assert (and (<= 0 i (- n1 1))
                                           (<= 0 j (- n2 1))))
                           when (< (aref dp2 j) 0)
                           do (minf value (aref dp1 i)))
                     (when (<= 0 (- y (aref gs child) 1) (- n1 1))
                       (minf value (aref dp1 (- y (aref gs child) 1))))
                     (setf (aref res-dp y) value)))
                 res-dp)))
      (let ((dp (sb-int:named-let dfs ((v 0) (parent -1))
                  (let ((g 0)
                        (dp (make-array 1 :element-type 'fixnum :initial-element (aref as v))))
                    (declare (uint62 g))
                    (dolist (child (aref graph v))
                      (unless (= child parent)
                        (let ((child-dp (dfs child v)))
                          (setq dp (%merge dp child-dp child))
                          (incf g (min (aref gs child)
                                       (loop for y below (length child-dp)
                                             when (< (aref child-dp y) 0)
                                             do (return (+ y 1))
                                             finally (return +inf+)))))))
                    (when (> (aref as v) 0)
                      (setf (aref gs v) g))
                    (dbg v g dp)
                    dp))))
        (println (min (aref gs 0)
                      (dotimes (y (length dp) +inf+)
                        (when (< (aref dp y) 0)
                          (return y)))))))))

#-swank (main)

;;;
;;; Test and benchmark
;;;

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    #+os-windows (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)
    #+os-unix (run-program "xsel" '("-b" "-o") :output out :search t)))

#+swank (defparameter *this-pathname* (uiop:current-lisp-file-pathname))
#+swank (defparameter *dat-pathname* (uiop:merge-pathnames* "test.dat" *this-pathname*))

#+swank
(defun run (&optional thing (out *standard-output*))
  "THING := null | string | symbol | pathname

null: run #'MAIN using the text on clipboard as input.
string: run #'MAIN using the string as input.
symbol: alias of FIVEAM:RUN!.
pathname: run #'MAIN using the text file as input."
  (let* ((*standard-output* (or out (make-string-output-stream)))
         (res (etypecase thing
                (null
                 (with-input-from-string (*standard-input* (delete #\Return (get-clipbrd)))
                   (main)))
                (string
                 (with-input-from-string (*standard-input* (delete #\Return thing))
                   (main)))
                (symbol (5am:run! thing))
                (pathname
                 (with-open-file (*standard-input* thing)
                   (main))))))
    (if out res (get-output-stream-string *standard-output*))))

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (format out "")))

#+swank
(defun bench (&optional (out (make-broadcast-stream)))
  (time (run *dat-pathname* out)))

#-swank
(eval-when (:compile-toplevel)
  (when (and (boundp 'sb-c::*compiler-warning-count*)
             (> sb-c::*compiler-warning-count* 0))
    (sb-ext:quit :unix-status 1)))

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (5am:is
   (equal "1
"
          (run "7
-2 7 5 6 -8 3 4
1 2
2 3
2 4
1 5
5 6
5 7
" nil)))
  (5am:is
   (equal "0
"
          (run "4
1 2 3 4
1 2
1 3
1 4
" nil)))
  (5am:is
   (equal "5
"
          (run "6
10 -1 10 -1 10 -1
1 2
2 3
3 4
4 5
5 6
" nil)))
  (5am:is
   (equal "3
"
          (run "8
-2 3 6 -2 -2 -5 3 2
3 4
7 6
6 2
8 2
5 3
1 8
3 7
" nil)))
  (5am:is
   (equal "3
"
          (run "10
3 4 9 6 1 5 -1 10 -10 -10
7 4
5 6
8 1
9 5
7 1
10 3
2 8
4 10
9 2
" nil))))


Measured memory_bytes: 101376