結果

問題 No.898 tri-βutree
ユーザー sansaquasansaqua
提出日時 2019-10-04 23:13:15
言語 Common Lisp
(sbcl 2.3.8)
結果
AC  
実行時間 317 ms / 4,000 ms
コード長 11,843 bytes
コンパイル時間 261 ms
コンパイル使用メモリ 43,520 KB
実行使用メモリ 52,480 KB
最終ジャッジ日時 2024-11-08 22:24:07
合計ジャッジ時間 7,107 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
外部呼び出し有り
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 149 ms
52,480 KB
testcase_01 AC 18 ms
25,088 KB
testcase_02 AC 18 ms
25,216 KB
testcase_03 AC 18 ms
25,088 KB
testcase_04 AC 18 ms
25,088 KB
testcase_05 AC 18 ms
25,216 KB
testcase_06 AC 18 ms
25,344 KB
testcase_07 AC 306 ms
42,752 KB
testcase_08 AC 302 ms
42,624 KB
testcase_09 AC 313 ms
42,624 KB
testcase_10 AC 317 ms
42,752 KB
testcase_11 AC 312 ms
42,624 KB
testcase_12 AC 317 ms
42,624 KB
testcase_13 AC 306 ms
42,496 KB
testcase_14 AC 308 ms
42,624 KB
testcase_15 AC 300 ms
42,624 KB
testcase_16 AC 312 ms
42,624 KB
testcase_17 AC 307 ms
42,624 KB
testcase_18 AC 312 ms
42,624 KB
testcase_19 AC 310 ms
42,624 KB
testcase_20 AC 311 ms
42,624 KB
testcase_21 AC 307 ms
42,624 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
; compiling file "/home/judge/data/code/Main.lisp" (written 08 NOV 2024 10:23:59 PM):

; file: /home/judge/data/code/Main.lisp
; in: DEFUN MAIN
;     (+ (CALC-DIST X Y) (CALC-DIST Z LCA-YZ))
; 
; note: doing unsigned word to integer coercion (cost 20), for:
;       the first result of inline (unsigned-byte 64) arithmetic

;     (+ (CALC-DIST X Y) (CALC-DIST Z LCA-ZX))
; 
; note: doing unsigned word to integer coercion (cost 20), for:
;       the first result of inline (unsigned-byte 64) arithmetic
; 
; compilation unit finished
;   printed 2 notes


; wrote /home/judge/data/code/Main.fasl
; compilation finished in 0:00:00.074

ソースコード

diff #

#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "256MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))

;; -*- coding: utf-8 -*-
(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)) (read s nil nil t))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
;; Should we do this with UNWIND-PROTECT?
(defmacro with-buffered-stdout (&body body)
  "Buffers all outputs to *STANDARD-OUTPUT* in BODY and flushes them to
*STANDARD-OUTPUT* after BODY has been done (without error). Note that only
BASE-CHAR is allowed."
  (let ((out (gensym)))
    `(let ((,out (make-string-output-stream :element-type 'base-char)))
       (let ((*standard-output* ,out))
         ,@body)
       (write-string (get-output-stream-string ,out)))))

(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)

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (declare #.OPT)
  (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 #\-))
                                  (setf 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))))))))

;;;
;;; Lowest common ancestor of tree by binary lifting
;;; build: O(nlog(n))
;;; query: O(log(n))
;;;

;; PAY ATTENTION TO THE STACK SIZE! BUILD-LCA-TABLE 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))
                 (parents (make-array (list size max-level)
                                      :element-type 'lca-vertex-number))
                 (weights (make-array size :element-type '(unsigned-byte 62)
                                      :initial-element 0))))
            (:conc-name lca-))
  (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 (* *)))
  (weights nil :type (simple-array (unsigned-byte 62) (*))))

(defun build-lca-table (root graph)
  "GRAPH := vector of adjacency lists"
  (declare (optimize (speed 3))
           ((simple-array list (*)) graph))
  (let* ((size (length graph))
         (lca-table (make-lca-table size))
         (depths (lca-depths lca-table))
         (weights (lca-weights lca-table))
         (parents (lca-parents lca-table))
         (max-level (lca-max-level lca-table)))
    (labels ((dfs (v prev-v depth weight)
               (declare (lca-vertex-number v prev-v)
                        (uint62 weight))
               (setf (aref depths v) depth)
               (setf (aref weights v) weight)
               (setf (aref parents v 0) prev-v)
               (dolist (node (aref graph v))
                 (let ((dest (car node))
                       (dweight (cdr node)))
                   (declare (lca-vertex-number dest)
                            (uint62 dweight))
                   (unless (= dest prev-v)
                     (dfs dest v (+ 1 depth) (+ weight dweight)))))))
      (dfs root -1 0 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)))))
      lca-table)))

(defun get-lca (u v lca-table)
  "Returns the lowest common ancestor of the vertices U and V."
  (declare (optimize (speed 3))
           (lca-vertex-number u v))
  (let* ((depths (lca-depths lca-table))
         (parents (lca-parents lca-table))
         (max-level (lca-max-level lca-table)))
    ;; 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 (setf u (aref parents u k)
                       v (aref parents v k))
              finally (return (aref parents u 0))))))

(declaim (inline distance-on-tree))
(defun distance-on-tree (u v lca-table)
  "Returns the distance of U and V."
  (declare (optimize (speed 3)))
  (let ((weights (lca-depths lca-table))
        (lca (get-lca u v lca-table)))
    (+ (- (aref weights u) (aref weights lca))
       (- (aref weights v) (aref weights lca)))))

(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))))

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         ;; to . weight
         (graph (make-array n :element-type 'list :initial-element nil)))
    (declare (uint31 n))
    (dotimes (i (- n 1))
      (let ((u (read-fixnum))
            (v (read-fixnum))
            (w (read-fixnum)))
        (push (cons u w) (aref graph v))
        (push (cons v w) (aref graph u))))
    (let* ((table (build-lca-table 0 graph))
           (depths (lca-depths table))
           (q (read)))
      (declare (uint31 q))
      (labels ((calc-dist (u v)
                 (declare (values uint62))
                 (let ((weights (lca-weights table))
                       (lca (get-lca u v table)))
                   (- (+ (aref weights u)
                         (aref weights v))
                      (* 2 (aref weights lca))))))
        (with-buffered-stdout
          (dotimes (_ q)
            (println
             (let* ((x (read-fixnum))
                    (y (read-fixnum))
                    (z (read-fixnum)))
               (labels ((frob (x y z)
                          (let* ((lca-xy (get-lca x y table))
                                 (lca-yz (get-lca y z table))
                                 (lca-zx (get-lca z x table))
                                 (shallow (min (aref depths lca-xy)
                                               (aref depths lca-yz)
                                               (aref depths lca-zx)))
                                 (deep (max (aref depths lca-xy)
                                            (aref depths lca-yz)
                                            (aref depths lca-zx))))
                            (if (/= shallow (aref depths lca-xy))
                                (frob y z x)
                                (cond ((= deep (aref depths lca-yz))
                                       ;; yzのlcaが深い
                                       (+ (calc-dist x y)
                                          (calc-dist z lca-yz)))
                                      ((= deep (aref depths lca-zx))
                                       ;; zxのlcaが深い
                                       (+ (calc-dist x y)
                                          (calc-dist z lca-zx)))
                                      (t (error "Huh?")))))))
                 (frob x y z))))))))))

#-swank (main)

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

#+swank
(defun io-equal (in-string out-string &key (function #'main) (test #'equal))
  "Passes IN-STRING to *STANDARD-INPUT*, executes FUNCTION, and returns true if
the string output to *STANDARD-OUTPUT* is equal to OUT-STRING."
  (labels ((ensure-last-lf (s)
             (if (eql (uiop:last-char s) #\Linefeed)
                 s
                 (uiop:strcat s uiop:+lf+))))
    (funcall test
             (ensure-last-lf out-string)
             (with-output-to-string (out)
               (let ((*standard-output* out))
                 (with-input-from-string (*standard-input* (ensure-last-lf in-string))
                   (funcall function)))))))

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    (run-program "C:/msys64/usr/bin/cat.exe" '("/dev/clipboard") :output out)))

#+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* out))
    (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))))))

#+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
(5am:test :sample
  (5am:is (io-equal "5
0 1 5
1 2 40
2 3 7
3 4 1
6
0 1 2
0 2 1
1 2 0
1 0 2
2 0 1
2 1 0
"
                    "45
45
45
45
45
45
"))
  (5am:is (io-equal "8
0 1 7
0 6 8
1 2 1
1 3 100
3 4 2
3 7 4
7 5 11
36
2 3 0
0 2 3
2 0 3
3 0 2
0 3 2
3 2 0
6 3 4
6 4 3
3 4 6
3 6 4
4 6 3
4 3 6
2 7 4
2 4 7
4 7 2
4 2 7
7 2 4
7 4 2
2 6 7
2 7 6
6 2 7
6 7 2
7 2 6
7 6 2
3 4 7
3 7 4
4 3 7
4 7 3
7 3 4
7 4 3
6 4 7
6 7 4
4 6 7
4 7 6
7 6 4
7 4 6
"
                    "108
108
108
108
108
108
117
117
117
117
117
117
107
107
107
107
107
107
120
120
120
120
120
120
6
6
6
6
6
6
121
121
121
121
121
121
"))
  (5am:is (io-equal "6
0 5 8
0 1 7
1 4 100
1 2 1
1 3 2
6
2 3 4
2 4 3
3 2 4
3 4 2
4 2 3
4 3 2
"
                    "103
103
103
103
103
103
")))
0