#-swank (unless (member :child-sbcl *features*) (quit :unix-status (process-exit-code (run-program *runtime-pathname* `("--control-stack-size" "128MB" "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options" "--eval" "(push :child-sbcl *features*)" "--script" ,(namestring *load-pathname*)) :output t :error t :input t)))) (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 (cl-syntax:use-syntax cl-debug-print:debug-print-syntax) (defmacro define-int-types (&rest bits) `(progn ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~A" b)) () '(unsigned-byte ,b))) bits) ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~A" b)) () '(signed-byte ,b))) bits))) (define-int-types 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 ;;; ;;; Lowest common ancestor of tree (or forest) by binary lifting ;;; build: O(nlog(n)) ;;; query: O(log(n)) ;;; (defpackage :cp/lca (:use :cl) (:export #:lca-table #:lca-table-p #:make-lca-table #:lca-max-level #:lca-depths #:lca-parents #:lca-query #:two-vertices-disconnected-error #:lca-get-lca #:lca-distance)) (in-package :cp/lca) ;; PAY ATTENTION TO THE STACK SIZE! THE CONSTRUCTOR DOES DFS. (deftype lca-vertex-number () '(signed-byte 32)) (defstruct (lca-table (:constructor %make-lca-table (size &aux ;; requires 1 + log_2{size-1} (max-level (+ 1 (integer-length (- size 2)))) (depths (make-array size :element-type 'lca-vertex-number :initial-element -1)) (parents (make-array (list size max-level) :element-type 'lca-vertex-number)) (children (make-array (list size max-level) :element-type 'lca-vertex-number :initial-element -1)) (mins (make-array (list size max-level) :element-type 'list :initial-element nil)))) (:conc-name lca-) (:copier nil)) (max-level nil :type (integer 0 #.most-positive-fixnum)) (depths nil :type (simple-array lca-vertex-number (*))) (parents nil :type (simple-array lca-vertex-number (* *))) (children nil :type (simple-array lca-vertex-number (* *))) (mins nil :type (simple-array list (* *)))) (defun %merge (node1 node2 deleted &optional deleted2) (declare (optimize (speed 3)) (list node1 node2) (inline sort sb-impl::stable-sort-list)) (let ((res (delete deleted (concatenate 'list node1 node2) :key #'car :test #'eq))) (when deleted2 (setq res (delete deleted2 res :key #'car :test #'eq))) (setq res (sort res #'< :key #'cdr)) (when (cdddr res) (setf (cdddr res) nil)) res)) (defun make-lca-table (graph tree &key root (key #'identity)) "GRAPH := vector of adjacency lists ROOT := null | non-negative fixnum If ROOT is null, this function traverses each connected component of GRAPH from an arbitrarily picked vertex. Otherwise this function traverses GRAPH only from ROOT; GRAPH must be tree in the latter case." (declare (optimize (speed 3)) (vector graph) (function key) (inline sort sb-impl::stable-sort-list) ((or null (integer 0 #.most-positive-fixnum)) root)) (let* ((size (length graph)) (lca-table (%make-lca-table size)) (depths (lca-depths lca-table)) (parents (lca-parents lca-table)) (mins (lca-mins lca-table)) (children (lca-children lca-table)) (max-level (lca-max-level lca-table))) (labels ((dfs (v parent depth) (declare (lca-vertex-number v parent)) (setf (aref depths v) depth (aref parents v 0) parent) (dolist (edge (aref graph v)) (let ((dest (funcall key edge))) (declare (lca-vertex-number dest)) (unless (= dest parent) (dfs dest v (+ 1 depth))))))) (if root (dfs root -1 0) (dotimes (v size) (when (= (aref depths v) -1) (dfs v -1 0)))) (dotimes (k (- max-level 1)) (dotimes (v size) (if (= -1 (aref parents v k)) (setf (aref parents v (+ k 1)) -1) (setf (aref parents v (+ k 1)) (aref parents (aref parents v k) k))))) (dotimes (v size) (let ((parent (aref parents v 0))) (unless (= parent -1) (setf (aref mins v 0) (%merge (aref tree parent) (aref tree v) v))))) (dotimes (v size) (setf (aref children v 0) v)) (dotimes (k (- max-level 1)) (dotimes (v size) (let ((parent (aref parents v k))) (unless (= -1 parent) (setf (aref children v (+ k 1)) (aref children parent k)))))) (loop for k from 0 below (- max-level 1) do (dotimes (v size) (let* ((parent (aref parents v k))) (unless (= -1 parent) (let ((merged (%merge (aref mins parent k) (aref mins v k) v))) (setf (aref mins v (+ k 1)) merged)))))) lca-table))) (define-condition two-vertices-disconnected-error (error) ((lca-table :initarg :lca-table :accessor two-vertices-disconnected-error-lca-table) (vertex1 :initarg :vertex1 :accessor two-vertices-disconnected-error-vertex1) (vertex2 :initarg :vertex2 :accessor two-vertices-disconnected-error-vertex2)) (:report (lambda (c s) (format s "~W and ~W are disconnected on lca-table ~W" (two-vertices-disconnected-error-vertex1 c) (two-vertices-disconnected-error-vertex2 c) (two-vertices-disconnected-error-lca-table c))))) (declaim (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional)) lca-get-lca)) (defun lca-get-lca (lca-table vertex1 vertex2) "Returns the lowest common ancestor of the vertices VERTEX1 and VERTEX2." (declare (optimize (speed 3)) ((and lca-vertex-number (integer 0)) vertex1 vertex2)) (let* ((u vertex1) (v vertex2) (depths (lca-depths lca-table)) (parents (lca-parents lca-table)) (max-level (lca-max-level lca-table))) (declare (lca-vertex-number u v)) ;; Ensures depth[u] <= depth[v] (when (> (aref depths u) (aref depths v)) (rotatef u v)) (dotimes (k max-level) (when (logbitp k (- (aref depths v) (aref depths u))) (setf v (aref parents v k)))) (if (= u v) u (loop for k from (- max-level 1) downto 0 unless (= (aref parents u k) (aref parents v k)) do (setq u (aref parents u k) v (aref parents v k)) finally (if (= (aref parents u 0) -1) (error 'two-vertices-disconnected-error :lca-table lca-table :vertex1 vertex1 :vertex2 vertex2) (return (aref parents u 0))))))) (defun lca-query (lca-table vertex1 vertex2) (declare (optimize (speed 3)) ((and lca-vertex-number (integer 0)) vertex1 vertex2)) (let* ((u vertex1) (v vertex2) (depths (lca-depths lca-table)) (parents (lca-parents lca-table)) (children (lca-children lca-table)) (mins (lca-mins lca-table)) (max-level (lca-max-level lca-table))) (declare (lca-vertex-number u v)) ;; Ensures depth[u] <= depth[v] (when (> (aref depths u) (aref depths v)) (rotatef u v)) (let ((res-u (aref mins u 0)) (res-v (aref mins v 0))) (dotimes (k max-level) (when (logbitp k (- (aref depths v) (aref depths u))) (let ((deleted-v (aref children v k)) (min-v (aref mins v k))) (setq res-v (%merge res-v min-v deleted-v) v (aref parents v k))))) (when (= u v) (return-from lca-query (car res-v))) (cl-user::dbg res-u res-v) (loop for k from (- max-level 1) downto 0 unless (= (aref parents u k) (aref parents v k)) do (let ((deleted-u (aref children u k)) (deleted-v (aref children v k)) (min-u (aref mins u k)) (min-v (aref mins v k))) (setq u (aref parents u k) v (aref parents v k) res-u (%merge res-u min-u deleted-u) res-v (%merge res-v min-v deleted-v))) (cl-user::dbg k res-u res-v) finally (if (= (aref parents u 0) -1) (error 'two-vertices-disconnected-error :lca-table lca-table :vertex1 vertex1 :vertex2 vertex2) (return (car (%merge res-u res-v u v)))))))) (declaim (inline lca-distance)) (defun lca-distance (lca-table u v) "Returns the distance between two vertices U and V." (declare (optimize (speed 3))) (let ((depths (lca-depths lca-table)) (lca (lca-get-lca lca-table u v))) (+ (- (aref depths u) (aref depths lca)) (- (aref depths v) (aref depths lca))))) (defpackage :cp/read-fixnum (:use :cl) (:export #:read-fixnum)) (in-package :cp/read-fixnum) (declaim (ftype (function * (values fixnum &optional)) read-fixnum)) (defun read-fixnum (&optional (in *standard-input*)) "NOTE: cannot read -2^62" (macrolet ((%read-byte () `(the (unsigned-byte 8) #+swank (char-code (read-char in nil #\Nul)) #-swank (sb-impl::ansi-stream-read-byte in nil #.(char-code #\Nul) nil)))) (let* ((minus nil) (result (loop (let ((byte (%read-byte))) (cond ((<= 48 byte 57) (return (- byte 48))) ((zerop byte) ; #\Nul (error "Read EOF or #\Nul.")) ((= byte #.(char-code #\-)) (setq minus t))))))) (declare ((integer 0 #.most-positive-fixnum) result)) (loop (let* ((byte (%read-byte))) (if (<= 48 byte 57) (setq result (+ (- byte 48) (* 10 (the (integer 0 #.(floor most-positive-fixnum 10)) result)))) (return (if minus (- result) result)))))))) (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)) (eval-when (:compile-toplevel :load-toplevel :execute) (use-package :cp/read-fixnum :cl-user)) (eval-when (:compile-toplevel :load-toplevel :execute) (use-package :cp/lca :cl-user)) (in-package :cl-user) ;;; ;;; Body ;;; (defun main () (let* ((n (read)) (graph (make-array n :element-type 'list :initial-element nil)) (tree (make-array n :element-type 'list :initial-element nil)) (parent-extras (make-array n :element-type 'uint62 :initial-element most-positive-fixnum)) (dists (make-array n :element-type 'fixnum :initial-element 0))) (dotimes (i (- n 1)) (let ((u (- (read-fixnum) 1)) (v (- (read-fixnum) 1)) (w (read-fixnum))) (push (cons u w) (aref graph v)) (push (cons v w) (aref graph u)))) (sb-int:named-let dfs ((v 0) (parent -1) (dist 0)) (setf (aref dists v) dist) (loop for (child . w) in (aref graph v) unless (= child parent) do (push (cons child w) (aref tree v)) (setf (aref parent-extras child) w) (dfs child v (+ dist w))) (setf (aref tree v) (sort (aref tree v) #'< :key #'cdr))) (let ((lca-table (make-lca-table graph tree :key #'car :root 0)) (q (read))) #>lca-table (write-string (with-output-to-string (*standard-output* nil :element-type 'base-char) (dotimes (_ q) (let* ((x (- (read-fixnum) 1)) (y (- (read-fixnum) 1)) (lca (lca-get-lca lca-table x y)) (dist (- (+ (aref dists x) (aref dists y)) (* 2 (aref dists lca)))) (extra (cdr (lca-query lca-table x y))) (parent-cost (aref parent-extras lca)) (min (min (or extra most-positive-fixnum) parent-cost))) (dbg dist min) (println (if (< min most-positive-fixnum) (+ dist (* 2 min)) -1))))))))) #-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))) ;; To run: (5am:run! :sample) #+swank (it.bese.fiveam:test :sample (it.bese.fiveam:is (equal "11 -1 " (run "3 1 2 3 2 3 4 2 1 2 1 3 " nil))) (it.bese.fiveam:is (equal "42 176 152 14 " (run "5 1 4 10 2 3 100 1 2 38 1 5 2 4 1 2 2 3 3 4 1 4 " nil))) (it.bese.fiveam:is (equal "22 36 31 49 21 " (run "6 1 3 19 1 2 20 1 4 1 5 1 10 4 6 8 5 1 2 3 4 5 3 6 2 3 1 " nil))))