;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

;; BEGIN_INSERTED_CONTENTS
(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
                                  ;; (return-from read-fixnum 0)
                                  (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))))))))

(setf *print-circle* t)

(defconstant +op-identity+ most-positive-fixnum)

(declaim (inline op))
(defun op (x y)
  (min x y))

(defconstant +updater-identity+ most-positive-fixnum)

(declaim (inline updater-op))
(defun updater-op (a b)
  "Is the operator to compute and update LAZY value."
  (declare (fixnum a b))
  (min a b))

(declaim (inline modifier-op))
(defun modifier-op (a b size)
  "Is the operator to update ACCUMULATOR based on LAZY value."
  (declare (ignore size))
  (declare (fixnum a b))
  (min a b))

(declaim (inline treap-order))
(defun treap-order (x y)
  (declare (fixnum x y))
  (< x y))

;; Treap with explicit key
(defstruct (treap (:constructor %make-treap (key priority value accumulator &key left right lazy (count 1)))
                  (:copier nil)
                  (:conc-name %treap-))
  (key 0 :type fixnum)
  (value +op-identity+ :type fixnum)
  (accumulator +op-identity+ :type fixnum)
  (lazy +updater-identity+ :type fixnum)
  (priority 0 :type (integer 0 #.most-positive-fixnum))
  (count 0 :type (integer 0 #.most-positive-fixnum))
  (left nil :type (or null treap))
  (right nil :type (or null treap)))

(declaim (inline treap-count))
(defun treap-count (treap)
  "Returns the size of the (nullable) TREAP."
  (declare ((or null treap) treap))
  (if (null treap)
      0
      (%treap-count treap)))

(declaim (inline treap-accumulator))
(defun treap-accumulator (treap)
  (declare ((or null treap) treap))
  (if (null treap)
      +op-identity+
      (%treap-accumulator treap)))

(declaim (inline update-count))
(defun update-count (treap)
  (declare (treap treap))
  (setf (%treap-count treap)
        (+ 1
           (treap-count (%treap-left treap))
           (treap-count (%treap-right treap)))))

(declaim (inline update-accumulator))
(defun update-accumulator (treap)
  (declare (treap treap))
  (setf (%treap-accumulator treap)
        (if (%treap-left treap)
            (if (%treap-right treap)
                (let ((mid-res (op (%treap-accumulator (%treap-left treap))
                                   (%treap-value treap))))
                  (declare (dynamic-extent mid-res))
                  (op mid-res (%treap-accumulator (%treap-right treap))))
                (op (%treap-accumulator (%treap-left treap))
                    (%treap-value treap)))
            (if (%treap-right treap)
                (op (%treap-value treap)
                    (%treap-accumulator (%treap-right treap)))
                (%treap-value treap)))))

(declaim (inline force-self))
(defun force-self (treap)
  (declare (treap treap))
  (update-count treap)
  (update-accumulator treap))

(declaim (inline force-down))
(defun force-down (treap)
  (declare (treap treap))
  (unless (eql +updater-identity+ (%treap-lazy treap))
    (when (%treap-left treap)
      (setf (%treap-lazy (%treap-left treap))
            (updater-op (%treap-lazy (%treap-left treap))
                        (%treap-lazy treap)))
      (setf (%treap-accumulator (%treap-left treap))
            (modifier-op (%treap-accumulator (%treap-left treap))
                         (%treap-lazy treap)
                         (%treap-count (%treap-left treap)))))
    (when (%treap-right treap)
      (setf (%treap-lazy (%treap-right treap))
            (updater-op (%treap-lazy (%treap-right treap))
                        (%treap-lazy treap)))
      (setf (%treap-accumulator (%treap-right treap))
            (modifier-op (%treap-accumulator (%treap-right treap))
                         (%treap-lazy treap)
                         (%treap-count (%treap-right treap)))))
    (setf (%treap-value treap)
          (modifier-op (%treap-value treap)
                       (%treap-lazy treap)
                       1))
    (setf (%treap-lazy treap) +updater-identity+)))

(defun treap-find (key treap)
  "Finds the key that satisfies (and (not (funcall test key (%treap-key
sub-treap))) (not (funcall test (%treap-key sub-treap) key))) and returns
the corresponding value. Returns NIL if KEY is not contained."
  (declare #.OPT ((or null treap) treap))
  (labels ((recur (treap)
             (unless treap (return-from treap-find nil))
             (force-down treap)
             (prog1
                 (cond ((treap-order key (%treap-key treap))
                        (recur (%treap-left treap)))
                       ((treap-order (%treap-key treap) key)
                        (recur (%treap-right treap)))
                       (t (%treap-value treap)))
               (force-self treap))))
    (recur treap)))

(defun treap-split (key treap)
  "Destructively splits the TREAP with reference to KEY and returns two treaps,
the smaller sub-treap (< KEY) and the larger one (>= KEY)."
  (declare #.OPT ((or null treap) treap))
  (labels ((recur (treap)
             (if (null treap)
                 (values nil nil)
                 (progn
                   (force-down treap)
                   (if (treap-order (%treap-key treap) key)
                       (multiple-value-bind (left right)
                           (recur (%treap-right treap))
                         (setf (%treap-right treap) left)
                         (force-self treap)
                         (values treap right))
                       (multiple-value-bind (left right)
                           (recur (%treap-left treap))
                         (setf (%treap-left treap) right)
                         (force-self treap)
                         (values left treap)))))))
    (recur treap)))

(defun treap-insert (key value treap)
  "Destructively inserts KEY into TREAP and returns the resultant treap. You
cannot rely on the side effect. Use the returned value.

The behavior is undefined when duplicated keys are inserted."
  (declare ((or null treap) treap))
  (labels ((recur (node treap)
             (declare (treap node))
             (unless treap (return-from recur node))
             (force-down treap)
             (if (> (%treap-priority node) (%treap-priority treap))
                 (progn
                   (setf (values (%treap-left node) (%treap-right node))
                         (treap-split (%treap-key node) treap))
                   (force-self node)
                   node)
                 (progn
                   (if (treap-order (%treap-key node) (%treap-key treap))
                       (setf (%treap-left treap)
                             (recur node (%treap-left treap)))
                       (setf (%treap-right treap)
                             (recur node (%treap-right treap))))
                   (force-self treap)
                   treap))))
    (recur (%make-treap key (random most-positive-fixnum) value value) treap)))

(declaim (inline treap-ensure-key))
(defun treap-ensure-key (key value treap &key if-exists)
  "IF-EXISTS := nil | function

Ensures that TREAP contains KEY and assigns VALUE to it if IF-EXISTS is
false. If IF-EXISTS is function and TREAP contains KEY, TREAP-ENSURE-KEY updates
the value by the function instead of overwriting it with VALUE."
  (declare #.OPT
           ((or null function) if-exists)
           ((or null treap) treap))
  (labels ((find-and-update (treap)
             ;; Updates the value slot and returns T if KEY exists
             (unless treap (return-from find-and-update nil))
             (force-down treap)
             (cond ((treap-order key (%treap-key treap))
                    (when (find-and-update (%treap-left treap))
                      (force-self treap)
                      t))
                   ((treap-order (%treap-key treap) key)
                    (when (find-and-update (%treap-right treap))
                      (force-self treap)
                      t))
                   (t (setf (%treap-value treap)
                            (if if-exists
                                (funcall if-exists (%treap-value treap))
                                value))
                      (force-self treap)
                      t))))
    (if (find-and-update treap)
        treap
        (treap-insert key value treap))))

(defun treap-merge (left right)
  "Destructively merges two treaps. Assumes that all keys of LEFT are smaller
 (or larger, depending on the order) than those of RIGHT."
  (declare #.OPT ((or null treap) left right))
  (cond ((null left) (when right (force-down right) (force-self right)) right)
        ((null right) (when left (force-down left) (force-self left)) left)
        (t (force-down left)
           (force-down right)
         (if (> (%treap-priority left) (%treap-priority right))
             (progn
               (setf (%treap-right left)
                     (treap-merge (%treap-right left) right))
               (force-self left)
               left)
             (progn
               (setf (%treap-left right)
                     (treap-merge left (%treap-left right)))
               (force-self right)
               right)))))

(defun treap-map (function treap)
  "Successively applies FUNCTION to TREAP[0], ..., TREAP[SIZE-1]. FUNCTION must
take two arguments: KEY and VALUE."
  (declare (function function))
  (when treap
    (force-down treap)
    (treap-map function (%treap-left treap))
    (funcall function (%treap-key treap) (%treap-value treap))
    (treap-map function (%treap-right treap))
    (force-self treap)))

(defmethod print-object ((object treap) stream)
  (print-unreadable-object (object stream :type t)
    (let ((init t))
      (treap-map (lambda (key value)
                   (if init
                       (setf init nil)
                       (write-char #\  stream))
                   (format stream "<~A . ~A>" key value))
                 object))))

(defun treap-update (treap x left right)
  "Updates TREAP[KEY] := (OP TREAP[KEY] X) for all KEY in [l, r)"
  (declare #.OPT ((or null treap) treap))
  (assert (not (treap-order right left)))
  (multiple-value-bind (treap-0-l treap-l-n)
      (treap-split left treap)
    (multiple-value-bind (treap-l-r treap-r-n)
        (treap-split right treap-l-n)
      (when treap-l-r
        (setf (%treap-lazy treap-l-r)
              (updater-op (%treap-lazy treap-l-r) x)))
      (treap-merge treap-0-l (treap-merge treap-l-r treap-r-n)))))

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

(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 (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 (inline sort))
  (let* ((n (read))
         (q (read))
         (ds (make-array q :element-type 'uint32))
         (ss (make-array n :element-type 'uint32))
         (ts (make-array n :element-type 'uint32))
         (xs (make-array n :element-type 'uint32))
         treap)
    (declare (uint31 n q))
    (dotimes (i n)
      (let ((s (read-fixnum))
            (end (read-fixnum))
            (x (read-fixnum)))
        (setf (aref ss i) s
              (aref ts i) end
              (aref xs i) x)
        (setf treap (treap-ensure-key (- s x) most-positive-fixnum treap))
        (setf treap (treap-ensure-key (- end x) most-positive-fixnum treap))))
    (dotimes (i q)
      (let ((d (read-fixnum)))
        (setf (aref ds i) d)
        (setf treap (treap-ensure-key d most-positive-fixnum treap))))
    (dotimes (i n)
      (setf  treap
             (treap-update treap
                           (aref xs i)
                           (- (aref ss i) (aref xs i))
                           (- (aref ts i) (aref xs i)))))
    (dotimes (i q)
      (let ((d (aref ds i)))
        (let ((res (treap-find d treap)))
          (if (< (the fixnum res) most-positive-fixnum)
              (println res)
              (println -1)))))))

#-swank(main)

Score : 500 points

Problem Statement

There is an infinitely long street that runs west to east, which we consider as a number line.

There are N roadworks scheduled on this street.
The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5.

Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point.

Find the distance each of the Q people will walk.

Constraints

All values in input are integers.

1 \leq N, Q \leq 2 \times 10^5

0 \leq S_i < T_i \leq 10^9

1 \leq X_i \leq 10^9

0 \leq D_1 < D_2 < ... < D_Q \leq 10^9

If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap.

Input

Input is given from Standard Input in the following format:

N Q
S_1 T_1 X_1
:
S_N T_N X_N
D_1
:
D_Q

Output

Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever.

Sample Input 1

4 6
1 3 2
7 13 10
18 20 13
3 4 2
0
1
2
3
5
8

Sample Output 1

2
2
10
-1
13
-1

The first person starts coordinate 0 at time 0 and stops walking at coordinate 2 when reaching a point blocked by the first roadwork at time 2.

The second person starts coordinate 0 at time 1 and reaches coordinate 2 at time 3. The first roadwork has ended, but the fourth roadwork has begun, so this person also stops walking at coordinate 2.

The fourth and sixth persons encounter no roadworks while walking, so they walk forever. The output for these cases is -1.


(defun solve (a b)
  (cond
    ((< a 6) 0)
    ((<= 6 a 12) (floor b 2))
    (t           b)))

(let ((a (read))
      (b (read)))
     (cond
       (princ (solve a b))))

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 100 points

Problem Statement

Takahashi, who is A years old, is riding a Ferris wheel.

It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is 12 years old, and the cost of the Ferris wheel is the half of 100 yen, that is, 50 yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is 0 years old, and he can ride the Ferris wheel for free.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


(defun answer (age price)
  (if (< age 6)
      0
      (if (< age 13)
          (/ price 2)
          price)))

(defparameter a (car (read)))
(defparameter b (second (read)))

(print (answer a b))


(setq r(read))(setq d(read))(setq x(read))
(loop for i from 1 to 10 do(princ(setq x(-(* x r)d))))

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


(defparameter mod-number 1000000007)

(defun unfold (p f g seed &optional (tail-gen (lambda () '())))
  (if (p seed)
      (tail-gen seed)
	  (cons (f seed)
	        (unfold p f g (g seed) tail-gen))))

(defun iota (c &optional (s 0) (step 1) (acc nil))
  (if (zerop c)
      (reverse acc)
      (iota (1- c) (+ s step) step (cons s acc))))

(defun sum (list &optional (init 0))
  (reduce #'+ list :initial-value init))

(defmacro debug-print (x)
  `(let ((y ,x))
    (format t "~A: ~A~%" ',x y)
	y))

(defparameter n (read))
(defparameter m (read))

(defparameter l nil)
(defparameter r nil)

(dotimes (i m)
  (push (read) l)
  (push (read) r))

(let ((l-max (apply #'max l))
      (r-min (apply #'min r)))
  (format t "~A~%" (max 0 (1+ (- r-min l-max)))))

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


(defparameter mod-number 1000000007)

(defun unfold (p f g seed &optional (tail-gen (lambda () '())))
  (if (p seed)
      (tail-gen seed)
	  (cons (f seed)
	        (unfold p f g (g seed) tail-gen))))

(defun iota (c &optional (s 0) (step 1) (acc nil))
  (if (zerop c)
      (reverse acc)
      (iota (1- c) (+ s step) step (cons s acc))))

(defun sum (list &optional (init 0))
  (reduce #'+ list :initial-value init))

(defmacro debug-print (x)
  `(let ((y ,x))
    (format t "~A: ~A~%" ',x y)
	y))

(defparameter n (read))
(defparameter m (read))

(defparameter l nil)
(defparameter r nil)

(dotimes (i m)
  (push (read) l)
  (push (read) r))

(defparameter l-max (apply #'max l))
(defparameter r-mix (apply #'min r))

(format t "~A~%" (1+ (- r-mix l-max)))


(let* ((n (read))
       (m (read))
       (lst (sort (loop :repeat n :collect (read)) #'<))
       (lst-l (sort (loop :repeat m :collect (cons (read) (read))) #'> :key #'cdr))
       (fil 0))
  (loop :for k :in lst-l :do (loop :for j :from fil :upto (+ fil (car k) -1)
                                   :do (cond ((< (1- (length lst)) j))
                                             ((< (elt lst j) (cdr k)) (setf (elt lst j) (cdr k))))
                                   :do (incf fil)))
  (princ (reduce #'+ lst)))

Score : 400 points

Problem Statement

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

By replacing the integer on the second card with 5, the sum of the integers written on the three cards becomes 5 + 5 + 4 = 14, which is the maximum result.

Sample Input 2

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Sample Output 4

10000000001

The output may not fit into a 32-bit integer type.


(defun calc (l v count current)
  (if (= count 0)
      (values l current)
      (let ((tmp l))
        (if (< (nth current tmp) v)
            (progn (setf (nth current tmp) v)
                   (calc tmp v (- count 1) (incf current)))
            (calc l v (- count 1) current)))))

(defun main ()
  (let ((N (read))
        (M (read))
        (A (list nil))
        (CB (list nil))
        (current 0))
    (dotimes (n N)
      (push (read) A))
    (setq A (sort (cdr (reverse A)) #'<))
    (dotimes (n M)
      (let ((B (read))
            (C (read)))
        (push (cons C B) CB)))
    (setq CB (sort (cdr (reverse CB)) (lambda (x y) (> (car x) (car y)))))
    (dolist (i CB)
      (multiple-value-bind (a c) (calc A (car i) (cdr i) current)
        (setq A a)
        (setq current c)))
    (print (reduce '+ A))))

(main)


(defmacro defsolver (name vars &body body)
  `(defun ,name ()
     (let (,@(mapcar #'list
            vars
            (mapcar (constantly '(read))
                vars)))
       ,@body)))

(defsolver after-solution-d (n m)
  (let ((l (loop repeat n collect (read))))
    (dotimes (i m l)
      (let ((max (read))
	    (num (read)))
	(nconc l (loop repeat max collect num))
	(setf l (sort l #'<))
	(setf l (last l n))))
    (princ (loop for x in l sum x))))


(defmacro defsolver (name vars &body body)
  `(defun ,name ()
     (let (,@(mapcar #'list
            vars
            (mapcar (constantly '(read))
                vars)))
       ,@body)))

(defsolver solution-d (n m)
  (let ((a (make-array n)))
    (dotimes (i n a)
      (setf (svref a i) (read)))
    (dotimes (i m a)
      (sort a #'<)
      (let* ((max (read))
	     (num (read))
	     (p (position-if #'(lambda (x) (>= x num)) a)))
	(dotimes (j (if (> p max) max p) a)
	  (let ((val (svref a j)))
	    (when (< val num)
	      (setf (svref a j) num))))))
    (let ((sum 0))
      (dotimes (i n sum)
	(incf sum (svref a i))))))

(solution-d)


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

;; BEGIN_INSERTED_CONTENTS
(setf *print-circle* t)

;; Treap with implicit key for updating and querying interval.

(declaim (inline op))
(defun op (a b)
  (+ a b))

(defconstant +op-identity+ 0)

(defstruct (inode (:constructor %make-inode (value priority &key left right (count 1) (accumulator +op-identity+)))
                  (:copier nil)
                  (:conc-name %inode-))
  (value +op-identity+ :type fixnum)
  (accumulator +op-identity+ :type fixnum)
  (priority 0 :type (integer 0 #.most-positive-fixnum))
  (count 1 :type (integer 0 #.most-positive-fixnum))
  (left nil :type (or null inode))
  (right nil :type (or null inode)))

(declaim (inline inode-count))
(defun inode-count (inode)
  (declare ((or null inode) inode))
  (if inode
      (%inode-count inode)
      0))

(declaim (inline inode-accumulator))
(defun inode-accumulator (inode)
  (declare ((or null inode) inode))
  (if inode
      (%inode-accumulator inode)
      +op-identity+))

(declaim (inline update-count))
(defun update-count (inode)
  (declare (inode inode))
  (setf (%inode-count inode)
        (+ 1
           (inode-count (%inode-left inode))
           (inode-count (%inode-right inode)))))

(declaim (inline update-accumulator))
(defun update-accumulator (inode)
  (declare (inode inode))
  (setf (%inode-accumulator inode)
        (if (%inode-left inode)
            (if (%inode-right inode)
                (let ((mid (op (%inode-accumulator (%inode-left inode))
                               (%inode-value inode))))
                  (declare (dynamic-extent mid))
                  (op mid (%inode-accumulator (%inode-right inode))))
                (op (%inode-accumulator (%inode-left inode))
                    (%inode-value inode)))
            (if (%inode-right inode)
                (op (%inode-value inode)
                    (%inode-accumulator (%inode-right inode)))
                (%inode-value inode)))))

(declaim (inline force-self))
(defun force-self (inode)
  (declare (inode inode))
  (update-count inode)
  (update-accumulator inode))

(defun inode-split (inode index)
  "Destructively splits the INODE into two nodes [0, INDEX) and [INDEX, N), where N
  is the number of elements of the INODE."
  (declare #.OPT ((integer 0 #.most-positive-fixnum) index))
  (unless inode
    (return-from inode-split (values nil nil)))
  (let ((implicit-key (1+ (inode-count (%inode-left inode)))))
    (if (< index implicit-key)
        (multiple-value-bind (left right)
            (inode-split (%inode-left inode) index)
          (setf (%inode-left inode) right)
          (force-self inode)
          (values left inode))
        (multiple-value-bind (left right)
            (inode-split (%inode-right inode) (- index implicit-key))
          (setf (%inode-right inode) left)
          (force-self inode)
          (values inode right)))))

(defun inode-merge (left right)
  "Destructively merges two INODEs."
  (declare #.OPT ((or null inode) left right))
  (cond ((null left) (when right (force-self right)) right)
        ((null right) (when left (force-self left)) left)
        (t (if (> (%inode-priority left) (%inode-priority right))
               (progn
                 (setf (%inode-right left)
                       (inode-merge (%inode-right left) right))
                 (force-self left)
                 left)
               (progn
                 (setf (%inode-left right)
                       (inode-merge left (%inode-left right)))
                 (force-self right)
                 right)))))

(declaim (inline inode-insert))
(defun inode-insert (inode index obj)
  "Destructively inserts OBJ into INODE at INDEX."
  (declare ((or null inode) inode)
           ((integer 0 #.most-positive-fixnum) index))
  (assert (<= index (inode-count inode)))
  (let ((obj-inode (%make-inode obj (random most-positive-fixnum))))
    (multiple-value-bind (left right)
        (inode-split inode index)
      (inode-merge (inode-merge left obj-inode) right))))

(defun inode-map (function inode)
  "Successively applies FUNCTION to INODE[0], ..., INODE[SIZE-1]."
  (declare (function function))
  (when inode
    (inode-map function (%inode-left inode))
    (funcall function (%inode-value inode))
    (inode-map function (%inode-right inode))
    (force-self inode)))

(defmethod print-object ((object inode) stream)
  (print-unreadable-object (object stream :type t)
    (let ((size (inode-count object))
          (index 0))
      (declare ((integer 0 #.most-positive-fixnum) index))
      (inode-map (lambda (x)
                   (princ x stream)
                   (incf index)
                   (when (< index size)
                     (write-char #\  stream)))
                 object))))

(declaim (inline inode-ref))
(defun inode-ref (inode index)
  (declare ((integer 0 #.most-positive-fixnum) index))
  (assert (< index (inode-count inode)))
  (labels ((%ref (inode index)
             (declare ((integer 0 #.most-positive-fixnum) index))
             (prog1
                 (let ((left-count (inode-count (%inode-left inode))))
                   (cond ((< index left-count)
                          (%ref (%inode-left inode) index))
                         ((> index left-count)
                          (%ref (%inode-right inode) (- index left-count 1)))
                         (t (%inode-value inode))))
               (force-self inode))))
    (%ref inode index)))

(defun inode-bisect-left (threshold treap &key (test #'<))
  "Returns the smallest index and the corresponding key that satisfies
KEY[index] >= THRESHOLD. Returns the size of TREAP and THRESHOLD if KEY[size-1]
< THRESHOLD."
  (declare #.OPT (function test))
  (labels ((recur (count treap)
             (declare ((integer 0 #.most-positive-fixnum) count))
             (cond ((null treap) nil)
                   ((funcall test (%inode-value treap) threshold)
                    (recur count (%inode-right treap)))
                   (t (let ((left-count (- count (inode-count (%inode-right treap)) 1)))
                        (let ((idx (recur left-count (%inode-left treap))))
                          (if idx
                              idx
                              left-count)))))))
    (or (recur (inode-count treap) treap)
        (inode-count treap))))

;; FIXME: might be problematic when two priorities collide.
(declaim (inline inode-query))
(defun inode-query (inode l r)
  (declare ((integer 0 #.most-positive-fixnum) l r))
  (unless (< l r)
    (return-from inode-query 0))
  (assert (<= r (inode-count inode)))
  (multiple-value-bind (inode-0-l inode-l-n)
      (inode-split inode l)
    (multiple-value-bind (inode-l-r inode-r-n)
        (inode-split inode-l-n (- r l))
      (prog1 (%inode-accumulator inode-l-r)
        (inode-merge inode-0-l (inode-merge inode-l-r inode-r-n))))))

(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
                                  ;; (return-from read-fixnum 0)
                                  (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))))))))

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

(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 (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* ((q (read))
         (const 0)
         inode)
    (declare (uint32 q) (fixnum const))
    (dotimes (i q)
      (let ((id (read-fixnum)))
        (if (= id 1)
            (let ((a (read-fixnum))
                  (b (read-fixnum)))
              (setf inode (inode-insert inode (inode-bisect-left a inode) a))
              (incf const b))
            (let ((count (inode-count inode)))
              (if (oddp count)
                  (let* ((mid (floor count 2))
                         (at (inode-ref inode mid)))
                    (format t
                            "~D ~D~%"
                            at
                            (+ const
                               (inode-query inode (+ mid 1) (inode-count inode))
                               (- (inode-query inode 0 mid)))))
                  (let* ((mid (floor count 2))
                         (at (inode-ref inode (- mid 1))))
                    (format t
                            "~D ~D~%"
                            at
                            (+ const
                               (inode-query inode mid (inode-count inode))
                               (- (inode-query inode 0 mid))))))))))))

#-swank(main)

Score : 600 points

Problem Statement

There is a function f(x), which is initially a constant function f(x) = 0.

We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:

An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).

An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.

We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.

Constraints

All values in input are integers.

1 \leq Q \leq 2 \times 10^5

-10^9 \leq a, b \leq 10^9

The first query is an update query.

Input

Input is given from Standard Input in the following format:

Q
Query_1
:
Query_Q

See Sample Input 1 for an example.

Output

For each evaluation query, print a line containing the response, in the order in which the queries are given.

The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.

Sample Input 1

4
1 4 2
2
1 1 -8
2

Sample Output 1

4 2
1 -3

In the first evaluation query, f(x) = |x - 4| + 2, which attains the minimum value of 2 at x = 4.

In the second evaluation query, f(x) = |x - 1| + |x - 4| - 6, which attains the minimum value of -3 when 1 \leq x \leq 4. Among the multiple values of x that minimize f(x), we ask you to print the minimum, that is, 1.

Sample Input 2

4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2

Sample Output 2

-1000000000 3000000000


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

;; BEGIN_INSERTED_CONTENTS
(setf *print-circle* t)

;; Treap with implicit key for updating and querying interval.

(declaim (inline op))
(defun op (a b)
  (+ a b))

(defconstant +op-identity+ 0)

(defconstant +updater-identity+ 0)

(declaim (inline updater-op))
(defun updater-op (a b)
  "Is the operator to compute and update LAZY value."
  (+ a b))

(declaim (inline modifier-op))
(defun modifier-op (a b size)
  "Is the operator to update ACCUMULATOR based on LAZY value."
  (declare (ignore size))
  (+ a b))

(defstruct (inode (:constructor %make-inode (value priority &key left right (count 1) (accumulator +op-identity+) (lazy +updater-identity+) reversed))
                  (:copier nil)
                  (:conc-name %inode-))
  (value +op-identity+ :type fixnum)
  (accumulator +op-identity+ :type fixnum) ; e.g. MIN, MAX, SUM, ...
  (lazy +updater-identity+ :type fixnum)
  (reversed nil :type boolean)
  (priority 0 :type (integer 0 #.most-positive-fixnum))
  (count 1 :type (integer 0 #.most-positive-fixnum))
  (left nil :type (or null inode))
  (right nil :type (or null inode)))

(declaim (inline inode-count))
(defun inode-count (inode)
  (declare ((or null inode) inode))
  (if inode
      (%inode-count inode)
      0))

(declaim (inline inode-accumulator))
(defun inode-accumulator (inode)
  (declare ((or null inode) inode))
  (if inode
      (%inode-accumulator inode)
      +op-identity+))

(declaim (inline update-count))
(defun update-count (inode)
  (declare (inode inode))
  (setf (%inode-count inode)
        (+ 1
           (inode-count (%inode-left inode))
           (inode-count (%inode-right inode)))))

(declaim (inline update-accumulator))
(defun update-accumulator (inode)
  (declare (inode inode))
  (setf (%inode-accumulator inode)
        (if (%inode-left inode)
            (if (%inode-right inode)
                (let ((mid (op (%inode-accumulator (%inode-left inode))
                               (%inode-value inode))))
                  (declare (dynamic-extent mid))
                  (op mid (%inode-accumulator (%inode-right inode))))
                (op (%inode-accumulator (%inode-left inode))
                    (%inode-value inode)))
            (if (%inode-right inode)
                (op (%inode-value inode)
                    (%inode-accumulator (%inode-right inode)))
                (%inode-value inode)))))

(declaim (inline force-self))
(defun force-self (inode)
  (declare (inode inode))
  (update-count inode)
  (update-accumulator inode))

(declaim (inline force-down))
(defun force-down (inode)
  (declare (inode inode))
  (when (%inode-reversed inode)
    (setf (%inode-reversed inode) nil)
    (rotatef (%inode-left inode) (%inode-right inode))
    (let ((left (%inode-left inode)))
      (when left
        (setf (%inode-reversed left) (not (%inode-reversed left)))))
    (let ((right (%inode-right inode)))
      (when right
        (setf (%inode-reversed right) (not (%inode-reversed right))))))
  (unless (eql +updater-identity+ (%inode-lazy inode))
    (when (%inode-left inode)
      (setf (%inode-lazy (%inode-left inode))
            (updater-op (%inode-lazy (%inode-left inode))
                        (%inode-lazy inode)))
      (setf (%inode-accumulator (%inode-left inode))
            (modifier-op (%inode-accumulator (%inode-left inode))
                         (%inode-lazy inode)
                         (%inode-count (%inode-left inode)))))
    (when (%inode-right inode)
      (setf (%inode-lazy (%inode-right inode))
            (updater-op (%inode-lazy (%inode-right inode))
                        (%inode-lazy inode)))
      (setf (%inode-accumulator (%inode-right inode))
            (modifier-op (%inode-accumulator (%inode-right inode))
                         (%inode-lazy inode)
                         (%inode-count (%inode-right inode)))))
    (setf (%inode-value inode)
          (modifier-op (%inode-value inode)
                       (%inode-lazy inode)
                       1))
    (setf (%inode-lazy inode) +updater-identity+)))

(defun inode-split (inode index)
  "Destructively splits the INODE into two nodes [0, INDEX) and [INDEX, N), where N
  is the number of elements of the INODE."
  (declare ((integer 0 #.most-positive-fixnum) index))
  (unless inode
    (return-from inode-split (values nil nil)))
  (force-down inode)
  (let ((implicit-key (1+ (inode-count (%inode-left inode)))))
    (if (< index implicit-key)
        (multiple-value-bind (left right)
            (inode-split (%inode-left inode) index)
          (setf (%inode-left inode) right)
          (force-self inode)
          (values left inode))
        (multiple-value-bind (left right)
            (inode-split (%inode-right inode) (- index implicit-key))
          (setf (%inode-right inode) left)
          (force-self inode)
          (values inode right)))))

(defun inode-merge (left right)
  "Destructively merges two INODEs."
  (declare ((or null inode) left right))
  (cond ((null left) (when right (force-down right) (force-self right)) right)
        ((null right) (when left (force-down left) (force-self left)) left)
        (t (force-down left)
           (force-down right)
           (if (> (%inode-priority left) (%inode-priority right))
               (progn
                 (setf (%inode-right left)
                       (inode-merge (%inode-right left) right))
                 (force-self left)
                 left)
               (progn
                 (setf (%inode-left right)
                       (inode-merge left (%inode-left right)))
                 (force-self right)
                 right)))))

;; (define-condition invalid-itreap-index-error (type-error)
;;   ((itreap :initarg :itreap :reader invalid-itreap-index-error-itreap)
;;    (index :initarg :index :reader invalid-itreap-index-error-index))
;;   (:report
;;    (lambda (condition stream)
;;      (format stream "Invalid index ~W for itreap ~S."
;;              (invalid-itreap-index-error-index condition)
;;              (invalid-itreap-index-error-itreap condition)))))

(declaim (inline inode-insert))
(defun inode-insert (inode index obj)
  "Destructively inserts OBJ into INODE at INDEX."
  (declare ((or null inode) inode)
           ((integer 0 #.most-positive-fixnum) index))
  (assert (<= index (inode-count inode)))
  (let ((obj-inode (%make-inode obj (random most-positive-fixnum))))
    (multiple-value-bind (left right)
        (inode-split inode index)
      (inode-merge (inode-merge left obj-inode) right))))

(defun inode-map (function inode)
  "Successively applies FUNCTION to INODE[0], ..., INODE[SIZE-1]."
  (declare (function function))
  (when inode
    (force-down inode)
    (inode-map function (%inode-left inode))
    (funcall function (%inode-value inode))
    (inode-map function (%inode-right inode))
    (force-self inode)))

(defmethod print-object ((object inode) stream)
  (print-unreadable-object (object stream :type t)
    (let ((size (inode-count object))
          (index 0))
      (declare ((integer 0 #.most-positive-fixnum) index))
      (inode-map (lambda (x)
                   (princ x stream)
                   (incf index)
                   (when (< index size)
                     (write-char #\  stream)))
                 object))))

(defmacro do-inode ((var inode &optional result) &body body)
  "Successively binds INODE[0], ..., INODE[SIZE-1] to VAR and executes BODY."
  `(block nil
     (inode-map (lambda (,var) ,@body) ,inode)
     ,result))

(defun inode (&rest args)
  ;; TODO: Currently takes O(nlog(n)) time though it can be reduced to O(n).
  (labels ((recurse (list position inode)
             (declare ((integer 0 #.most-positive-fixnum) position))
             (if (null list)
                 inode
                 (recurse (cdr list)
                          (1+ position)
                          (inode-insert inode position (car list))))))
    (recurse args 0 nil)))

(declaim (inline make-inode))
(defun make-inode (size)
  "Makes a treap of SIZE in O(SIZE). The values are filled with the identity
element."
  (labels ((heapify (top)
             (when top
               (let ((prioritized-node top))
                 (when (and (%inode-left top)
                            (> (%inode-priority (%inode-left top))
                               (%inode-priority prioritized-node)))
                   (setq prioritized-node (%inode-left top)))
                 (when (and (%inode-right top)
                            (> (%inode-priority (%inode-right top))
                               (%inode-priority prioritized-node)))
                   (setq prioritized-node (%inode-right top)))
                 (unless (eql prioritized-node top)
                   (rotatef (%inode-priority prioritized-node)
                            (%inode-priority top))
                   (heapify prioritized-node)))))
           (build (l r)
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (if (= l r)
                 nil
                 (let* ((mid (ash (+ l r) -1))
                        (node (%make-inode +op-identity+
                                           (random most-positive-fixnum))))
                   (setf (%inode-left node) (build l mid))
                   (setf (%inode-right node) (build (+ mid 1) r))
                   (heapify node)
                   (update-count node)
                   node))))
    (build 0 size)))

(declaim (inline inode-delete))
(defun inode-delete (inode index)
  (declare ((integer 0 #.most-positive-fixnum) index))
  (assert (< index (inode-count inode)))
  (multiple-value-bind (inode1 inode2)
      (inode-split inode (1+ index))
    (multiple-value-bind (inode1 _)
        (inode-split inode1 index)
      (declare (ignore _))
      (inode-merge inode1 inode2))))

(declaim (inline inode-ref))
(defun inode-ref (inode index)
  (declare ((integer 0 #.most-positive-fixnum) index))
  (assert (< index (inode-count inode)))
  (labels ((%ref (inode index)
             (declare ((integer 0 #.most-positive-fixnum) index))
             (force-down inode)
             (prog1
                 (let ((left-count (inode-count (%inode-left inode))))
                   (cond ((< index left-count)
                          (%ref (%inode-left inode) index))
                         ((> index left-count)
                          (%ref (%inode-right inode) (- index left-count 1)))
                         (t (%inode-value inode))))
               (force-self inode))))
    (%ref inode index)))

(declaim (inline (setf inode-ref)))
(defun (setf inode-ref) (new-value inode index)
  (declare ((integer 0 #.most-positive-fixnum) index))
  (assert (< index (inode-count inode)))
  (labels ((%set (inode index)
             (declare ((integer 0 #.most-positive-fixnum) index))
             (force-down inode)
             (prog1
                 (let ((left-count (inode-count (%inode-left inode))))
                   (cond ((< index left-count)
                          (%set (%inode-left inode) index))
                         ((> index left-count)
                          (%set (%inode-right inode) (- index left-count 1)))
                         (t (setf (%inode-value inode) new-value))))
               (force-self inode))))
    (%set inode index)
    new-value))

(defun copy-inode (inode)
  "For development. Recursively copies the whole INODEs."
  (if (null inode)
      nil
      (%make-inode (%inode-value inode)
                   (%inode-priority inode)
                   :left (copy-inode (%inode-left inode))
                   :right (copy-inode (%inode-right inode))
                   :count (%inode-count inode)
                   :accumulator (%inode-accumulator inode)
                   :lazy (%inode-lazy inode)
                   :reversed (%inode-reversed inode))))

(defun inode-bisect-left (threshold treap &key (test #'<))
  "Returns the smallest index and the corresponding key that satisfies
KEY[index] >= THRESHOLD. Returns the size of TREAP and THRESHOLD if KEY[size-1]
< THRESHOLD."
  (declare (function test))
  (labels ((recur (count treap)
             (declare ((integer 0 #.most-positive-fixnum) count))
             (cond ((null treap) nil)
                   ((funcall test (%inode-value treap) threshold)
                    (recur count (%inode-right treap)))
                   (t (let ((left-count (- count (inode-count (%inode-right treap)) 1)))
                        (let ((idx (recur left-count (%inode-left treap))))
                          (if idx
                              idx
                              left-count)))))))
    (or (recur (inode-count treap) treap)
        (inode-count treap))))

;; FIXME: might be problematic when two priorities collide.
(declaim (inline inode-query))
(defun inode-query (inode l r)
  (declare ((integer 0 #.most-positive-fixnum) l r))
  (unless (< l r)
    (return-from inode-query 0))
  (assert (<= r (inode-count inode)))
  (multiple-value-bind (inode-0-l inode-l-n)
      (inode-split inode l)
    (multiple-value-bind (inode-l-r inode-r-n)
        (inode-split inode-l-n (- r l))
      (prog1 (%inode-accumulator inode-l-r)
        (inode-merge inode-0-l (inode-merge inode-l-r inode-r-n))))))

(declaim (inline inode-reverse))
(defun inode-reverse (inode l r)
  (declare ((integer 0 #.most-positive-fixnum) l r))
  (assert (and (<= l r) (<= r (inode-count inode))))
  (multiple-value-bind (inode-0-l inode-l-n)
      (inode-split inode l)
    (multiple-value-bind (inode-l-r inode-r-n)
        (inode-split inode-l-n (- r l))
      (setf (%inode-reversed inode-l-r) (not (%inode-reversed inode-l-r)))
      (inode-merge inode-0-l (inode-merge inode-l-r inode-r-n)))))

(declaim (inline inode-update))
(defun inode-update (inode x l r)
  "Updates INODE[i] := (OP INODE[i] X) for all i in [l, r)"
  (declare ((integer 0 #.most-positive-fixnum) l r))
  (assert (and (<= l r) (<= r (inode-count inode))))
  (multiple-value-bind (inode-0-l inode-l-n)
      (inode-split inode l)
    (multiple-value-bind (inode-l-r inode-r-n)
        (inode-split inode-l-n (- r l))
      (when inode-l-r
        (setf (%inode-lazy inode-l-r)
              (updater-op (%inode-lazy inode-l-r) x)))
      (inode-merge inode-0-l (inode-merge inode-l-r inode-r-n)))))

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (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
                                  ;; (return-from read-fixnum 0)
                                  (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))))))))

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

(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 (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 ()
  (let* ((q (read))
         (const 0)
         inode)
    (declare (uint32 q))
    (dotimes (i q)
      (let ((id (read-fixnum)))
        (if (= id 1)
            (let ((a (read-fixnum))
                  (b (read-fixnum)))
              (setf inode (inode-insert inode (inode-bisect-left a inode) a))
              (incf const b))
            (let ((count (inode-count inode)))
              (if (oddp count)
                  (let* ((mid (floor count 2))
                         (at (inode-ref inode mid)))
                    (format t
                            "~D ~D~%"
                            at
                            (+ const
                               (inode-query inode (+ mid 1) (inode-count inode))
                               (- (inode-query inode 0 mid)))))
                  (let* ((mid (floor count 2))
                         (at (inode-ref inode (- mid 1))))
                    (format t
                            "~D ~D~%"
                            at
                            (+ const
                               (inode-query inode mid (inode-count inode))
                               (- (inode-query inode 0 mid))))))))))))

#-swank(main)


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

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

(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 (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 ()
  (let* ((n (read))
         (k (read))
         (s (read-line)))
    (setf (aref s (- k 1)) (char-downcase (aref s (- k 1))))
    (write-line s)))

#-swank(main)

;; For Test
#+swank
(defun io-equal (in-string out-string &optional (func #'main))
  (labels ((ensure-last-lf (s)
             (if (and (> (length s) 0)
                      (eql (char s (- (length s) 1)) #\Linefeed))
                 s
                 (uiop:strcat s uiop:+lf+))))
    (equal (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 func)))))))

#+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*))
  (let ((*standard-output* out))
    (etypecase thing
      (null ; Runs #'MAIN with the string on clipboard
       (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 ; Runs #'MAIN with the string in a text file
       (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)))

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


(defun answer-word (YYMM MMYY)
  (cond ((and YYMM MMYY) "AMBIGUOUS")
        ((and (not YYMM) MMYY) "MMYY")
        ((and YYMM (not MMYY)) "YYMM")
        (t "NA")))

(defun is-MM (n)
  (and (< 0 n)
       (< n 13)))

;(defun is-YY (n) t)

(defun can-YYMM (str)
  (is-MM (parse-integer (subseq str 2))))
(defun can-MMYY (str)
  (is-MM (parse-integer (subseq str 0 2))))

(let ((str (read-line)))
  (princ (answer-word (can-YYMM str) (can-MMYY str))))

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


(defun yymm (aa bb)
  (let ((am (and (<= 1 aa) (<= aa 12)))
        (bm (and (<= 1 bb) (<= bb 12))))
    (cond ((and am bm) "AMBIGUOUS")
          (am "MMYY")
          (bm "YYMM")
          (t "NA"))))

(defun w_yymm (str)
  (if (not (= (length str) 4)) "NA"
    (let ((num (read-from-string str)))
      (if (not (numberp num)) "NA"
        (multiple-value-bind (aa bb) (floor num 100)
          (yymm aa bb))))))
#|
(print (yymm 17 00))
(print (yymm 01 12))
(print (yymm 19 05))
(print (w_yymm "abc"))
(print (w_yymm "123"))
(print (w_yymm "1700"))
(print (w_yymm "0112"))
(print (w_yymm "1905"))
(print (w_yymm "0000"))
|#

(let ((str (read-line)))
  (format t (w_yymm str)))


(let ((n (read))
      (k (read))
      temp
      (ans 0))
  (loop for i from 1 upto n do
        (setf temp 0)
        (loop for j from 0 upto 20
              while (< (* i (expt 2 j)) k) do (incf temp))
        (incf ans (/ 1 (* n (expt 2 temp)))))
  (format t "~A~%" (float  ans)))

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


(defconstant +color-unknown+ -1)
(defconstant +color-white+ 0)
(defconstant +color-black+ 1)

(defmacro next-int ()
  '(read))

(defun solve ()
  (let*  ((n (next-int))                 ; 頂点の数
          ;; 根を除いて各頂点にはたった1つの親頂点があるので、辺の数は
          ;; 「頂点の数-1」になる。
          (from (make-array (1- n)))     ; 番号が小さいほうの頂点
          (to (make-array (1- n)))       ; 番号が大きいほうの頂点
          (w (make-array (1- n))))       ; 辺の長さ
    (loop for i below (1- n)
         do
         ;; 0ベース配列の添字にしたいので、各頂点番号をデクリメントしておく。
         (setf (aref from i) (1- (next-int)))
         (setf (aref to i) (1- (next-int)))
         (setf (aref w i) (next-int)))

    (let ((g (pack-wu n from to w))
          (color (make-array n :initial-element +color-unknown+))) ; 頂点の色。

      (dfs 0 color g +color-white+)

      (format t "~{~A~^~%~}~%" (coerce color 'list)))))

(defun dfs (now     ; 現在訪問している頂点
            color   ; 色を出力する配列
            g       ; 辺の接続先と長さの情報
            mod)    ; 現在の頂点の色(0 か 1)
  (setf (aref color now) mod)
  (loop for edge across (aref g now)
       do
       (when (= (aref color (first edge)) +color-unknown+)
         (dfs (first edge) color g (mod (+ mod (second edge)) 2)))))

;; 各頂点についてその接続情報を収めた表 g を生成して返す。
;; g[頂点番号][各辺][+edge-other-vertex+] = 辺の長さ
;; g[頂点番号][各辺][+edge-length+] = 接続先の頂点
(defun pack-wu (n from to w)
  (let ((sup (length from)) ; 辺の数
        (g (make-array n))
        (p (make-array n :initial-element 0))) ; 各頂点の次数(接続している辺の数)

    ;; 各頂点の次数を数える。各辺は、2つの頂点の次数をそれぞれ1つずつ
    ;; 増やす。
    (loop for i below sup
       do
         (incf (aref p (aref from i)))
         (incf (aref p (aref to i))))

    (loop for i below n
       do
       ;; g[i] に頂点 i 接続している辺の情報を収める配列を割り当てる。
         (setf (aref g i) (make-array (aref p i))))

    ;; 各頂点の持つ辺の情報を配列の後ろから格納する。
    (loop for i below sup
       do
         (let ((v (aref from i))
               (u (aref to i))
               (len (aref w i)))

           (decf (aref p v))
           (setf (aref (aref g v) (aref p v)) (list u len))

           (decf (aref p u))
           (setf (aref (aref g u) (aref p u)) (list v len))))

    g))

(solve)

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

5
2 5 2
2 3 10
1 3 8
3 4 2

Sample Output 2

1
0
1
0
1


(defconstant +color-unknown+ -1)
(defconstant +color-white+ 0)
(defconstant +color-black+ 1)

(defmacro next-int ()
  '(read))

(defun solve ()
  (let*  ((n (next-int))                 ; 頂点の数
          ;; 根を除いて各頂点にはたった1つの親頂点があるので、辺の数は
          ;; 「頂点の数-1」になる。
          (from (make-array (1- n)))     ; 番号が小さいほうの頂点
          (to (make-array (1- n)))       ; 番号が大きいほうの頂点
          (w (make-array (1- n))))       ; 辺の長さ
    (loop for i below (1- n)
         do
         ;; 0ベース配列の添字にしたいので、各頂点番号をデクリメントしておく。
         (setf (aref from i) (1- (next-int)))
         (setf (aref to i) (1- (next-int)))
         (setf (aref w i) (next-int)))

    (let ((g (pack-wu n from to w))
          (color (make-array n :initial-element +color-unknown+))) ; 頂点の色。

      (dfs 0 color g +color-white+)

      (format t "~{~A~^~%~}~%" (coerce color 'list)))))

(defun dfs (now     ; 現在訪問している頂点
            color   ; 色を出力する配列
            g       ; 辺の接続先と長さの情報
            mod)    ; 現在の頂点の色(0 か 1)
  (setf (aref color now) mod)
  (loop for edge across (aref g now)
       do
       (destructuring-bind
             (next-vertex length) edge
         (when (= (aref color next-vertex) +color-unknown+)
           (dfs next-vertex color g (mod (+ mod length) 2))))))

;; 各頂点についてその接続情報を収めた表 g を生成して返す。
;; g[頂点番号][各辺][+edge-other-vertex+] = 辺の長さ
;; g[頂点番号][各辺][+edge-length+] = 接続先の頂点
(defun pack-wu (n from to w)
  (let ((sup (length from)) ; 辺の数
        (g (make-array n))
        (p (make-array n :initial-element 0))) ; 各頂点の次数(接続している辺の数)

    ;; 各頂点の次数を数える。各辺は、2つの頂点の次数をそれぞれ1つずつ
    ;; 増やす。
    (loop for i below sup
       do
         (incf (aref p (aref from i)))
         (incf (aref p (aref to i))))

    (loop for i below n
       do
       ;; g[i] に頂点 i 接続している辺の情報を収める配列を割り当てる。
         (setf (aref g i) (make-array (aref p i))))

    ;; 各頂点の持つ辺の情報を配列の後ろから格納する。
    (loop for i below sup
       do
         (let ((v (aref from i))
               (u (aref to i))
               (len (aref w i)))

           (decf (aref p v))
           (setf (aref (aref g v) (aref p v)) (list u len))

           (decf (aref p u))
           (setf (aref (aref g u) (aref p u)) (list v len))))

    g))

(solve)


(defun root (l)
  (if (null (cdr l)) l (setf (cdr l)(root (cdr l)))))

(loop with ht = (make-hash-table) and N = (read) repeat (read)
      initially (loop for i from 1 to N
                      do (setf (gethash i ht) (list i)))

      do (setf l1 (root (gethash (read) ht))
               l2 (root (gethash (read) ht)))
      (read)
      if (not (eq l1 l2)) do (rplacd (root l1) (root l2))

      ;do (loop for v being each hash-value of ht
      ;         do (princ v) (terpri))
      ;(terpri)

      finally (princ (loop for v being each hash-value of ht
                           count (null (cdr v)))))

Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

6 5
1 2 1
2 3 2
1 3 3
4 5 4
5 6 5

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


(defun solve (r g b n)
  (let ((ans 0))
    (loop :for ri :from 0 :to (floor (/ n r))
          :do
             (loop :for gi :from 0 :to (floor (/ (- n (* ri r)) g))
                   :do
                      (if (zerop (rem (- n (* ri r) (* gi g)) b))
                          (setf ans (1+ ans)))))
    ans))

(defun main ()
  (let ((r (read))
        (g (read))
        (b (read))
        (n (read)))
    (format t "~A~%" (solve r g b n))))

(main)

Score : 200 points

Problem Statement

Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:

Red boxes, each containing R red balls

Green boxes, each containing G green balls

Blue boxes, each containing B blue balls

Snuke wants to get a total of exactly N balls by buying r red boxes, g green boxes and b blue boxes.
How many triples of non-negative integers (r,g,b) achieve this?

Constraints

All values in input are integers.

1 \leq R,G,B,N \leq 3000

Input

Input is given from Standard Input in the following format:

R G B N

Output

Print the answer.

Sample Input 1

1 2 3 4

Sample Output 1

4

Four triples achieve the objective, as follows:

(4,0,0)

(2,1,0)

(1,0,1)

(0,2,0)

Sample Input 2

13 1 4 3000

Sample Output 2

87058


(defun solve (r g b n)
  (let ((sorted (sort (list r g b) #'<)))
    (setf r (third sorted))
    (setf g (second sorted))
    (setf b (first sorted)))
  (let ((ans 0))
    (loop :for ri :from 0 :to (ceiling (/ n r))
          :do
             (loop :for gi :from 0 :to (ceiling (/ (- n (* ri r)) g))
                   :do
                      (if (zerop (rem (- n (* ri r) (* gi g)) b))
                          (setf ans (1+ ans)))))
    ans))

(defun main ()
  (let ((r (read))
        (g (read))
        (b (read))
        (n (read)))
    (format t "~A~%" (solve r g b n))))

(main)


(defparameter *s* #())

(defun last-char (s)
  (aref s (1- (length s))))

(defun count-ab (str)
  (let ((prev-char #\C))
    (loop :for c :across str
          :count (and (char= prev-char #\A)
                      (char= c         #\B))
          :do (setf prev-char c))))

(defun solve ()
  (let* ((last-a (loop :for s :across *s*
                       :count (char= (last-char s) #\A)))
         (first-b (loop :for s :across *s*
                        :count (char= (aref s 0) #\B)))
         (both (loop :for s :across *s*
                     :count (and (char= (last-char s) #\A) (char= (aref s 0) #\B))))
         (outer-ab (min last-a first-b (- (max last-a first-b) both)))
         (inner-ab (loop :for s :across *s*
                         :sum (count-ab s))))
    (+ outer-ab inner-ab)))

(defun main ()
  (let* ((n (read))
         (s (loop :repeat n :collect (read-line))))
    (setf *s* (make-array (length s) :initial-contents s))
    (format t "~A~%" (solve))))

(main)

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


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

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

;; BEGIN_INSERTED_CONTENTS

(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
                                  ;; (return-from read-fixnum 0)
                                  (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) (the fixnum (* result 10))))
              (return (if minus (- result) result))))))))

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

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

(declaim (inline find-optimal))
(defun find-optimal (sequence predicate &key (start 0) end)
  "Returns a index x that satisfies (FUNCALL PREDICATE SEQUENCE[x] SEQUENCE[y])
for all the index y and returns SEQUENCE[x] as the second value."
  (declare ((or null (integer 0 #.most-positive-fixnum)) end)
           ((integer 0 #.most-positive-fixnum) start)
           (function predicate)
           (sequence sequence))
  (etypecase sequence
    (list (error "Not implemented yet."))
    (vector
     (let ((end (or end (length sequence))))
       (unless (<= start end)
         (error "Can't find optimal value in null interval [~A, ~A)" start end))
       (let ((optimal (aref sequence 0))
             (index 0))
         (dotimes (i (length sequence) (values index optimal))
           (unless (funcall predicate optimal (aref sequence i))
             (setq optimal (aref sequence i)
                   index i))))))))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         (dist0 (make-array n :element-type 'uint32 :initial-element #xffffffff))
         (distv (make-array n :element-type 'uint32 :initial-element #xffffffff)))
    (setf (aref dist0 0) 0)
    (dotimes (i (- n 1))
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1)))
        (push a (aref graph b))
        (push b (aref graph a))))
    (labels ((calc-length (pos prev-pos len dist-table)
               (declare (fixnum pos prev-pos len)
                        ((simple-array uint32 (*)) dist-table))
               (setf (aref dist-table pos) len)
               (dolist (neighbor (aref graph pos))
                 (declare (uint32 neighbor))
                 (unless (= neighbor prev-pos)
                   (calc-length neighbor pos (+ 1 len) dist-table)))))
      (calc-length 0 -1 0 dist0)
      (let ((init-v (find-optimal dist0 #'>)))
        (setf (aref distv init-v) 0)
        (calc-length init-v -1 0 distv)
        (let ((diam (reduce #'max distv)))
          (write-line (if (= 1 (mod diam 3)) "Second" "First")))))))

#-swank(main)

Score : 800 points

Problem Statement

Takahashi and Aoki will play a game on a tree.
The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.

At the beginning of the game, each vertex contains a coin.
Starting from Takahashi, he and Aoki will alternately perform the following operation:

Choose a vertex v that contains one or more coins, and remove all the coins from v.

Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.

The player who becomes unable to play, loses the game.
That is, the player who takes his turn when there is no coin remaining on the tree, loses the game.
Determine the winner of the game when both players play optimally.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq a_i, b_i \leq N

a_i \neq b_i

The graph given as input is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}

Output

Print First if Takahashi will win, and print Second if Aoki will win.

Sample Input 1

3
1 2
2 3

Sample Output 1

First

Here is one possible progress of the game:

Takahashi removes the coin from Vertex 1. Now, Vertex 1 and Vertex 2 contain one coin each.

Aoki removes the coin from Vertex 2. Now, Vertex 2 contains one coin.

Takahashi removes the coin from Vertex 2. Now, there is no coin remaining on the tree.

Aoki takes his turn when there is no coin on the tree and loses.

Sample Input 2

6
1 2
2 3
2 4
4 6
5 6

Sample Output 2

Second

Sample Input 3

7
1 7
7 4
3 4
7 5
6 3
2 1

Sample Output 3

First


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (ql:quickload '(:cl-debug-print :fiveam))
  #-swank (set-dispatch-macro-character #\# #\> (lambda (s c p) (declare (ignore c p)) (read s nil (values) t))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(declaim (inline get-2dcumul))
(defun get-2dcumul (cumul-table i0 j0 i1 j1)
  "Returns the cumulative sum of the region given by the rectangle [i0, i1)*[j0,
j1). CUMUL-TABLE must be appropriately initialized beforehand:
i.e. CUMUL-TABLE[i][j] = sum of the region given by the regtangle [0, i)*[0,
j)."
  (+ (- (aref cumul-table i1 j1)
        (aref cumul-table i0 j1)
        (aref cumul-table i1 j0))
     (aref cumul-table i0 j0)))

;;;
;;; Memoization macro
;;;

;;
;; Basic usage:
;;
;; (with-cache (:hash-table :test #'equal :key #'cons)
;;   (defun add (a b)
;;     (+ a b)))
;; This function caches the returned values for already passed combinations of
;; arguments. In this case ADD stores the key (CONS A B) and the return value to
;; a hash-table when evaluating (ADD A B) for the first time. ADD returns the
;; stored value when it is called with the same arguments (w.r.t. EQUAL) again.
;;
;; The storage for the cache is hash-table or array. Let's see an example for
;; array:
;; (with-cache (:array (10 20 30) :initial-element -1 :element-type 'fixnum)
;;   (defun foo (a b c) ... ))
;; This form stores the value of FOO in the array created by (make-array (list
;; 10 20 30) :initial-element -1 :element-type 'fixnum). Note that
;; INITIAL-ELEMENT must always be given here as it is used as the flag for `not
;; yet stored'. (Therefore INITIAL-ELEMENT should be a value FOO never takes.)
;;
;; If you want to ignore some arguments, you can put `*' in dimensions:
;; (with-cache (:array (10 10 * 10) :initial-element -1)
;;   (defun foo (a b c d) ...)) ; then C is ignored when querying or storing cache
;;
;; Available definition forms in WITH-CACHE are DEFUN, LABELS, FLET, and
;; SB-INT:NAMED-LET.
;;
;; You can trace the memoized function by :TRACE option:
;; (with-cache (:array (10 10) :initial-element -1 :trace t)
;;   (defun foo (x y) ...))
;; Then FOO is traced as with CL:TRACE.
;;

;; FIXME: *RECURSION-DEPTH* should be included within the macro.
(declaim (type (integer 0 #.most-positive-fixnum) *recursion-depth*))
(defparameter *recursion-depth* 0)

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defun %enclose-with-tracing (fname args form)
    (let ((value (gensym)))
      `(progn
         (format t "~&~A~A: (~A ~{~A~^ ~}) =>"
                 (make-string *recursion-depth*
                              :element-type 'base-char
                              :initial-element #\ )
                 *recursion-depth*
                 ',fname
                 (list ,@args))
         (let ((,value (let ((*recursion-depth* (1+ *recursion-depth*)))
                         ,form)))
           (format t "~&~A~A: (~A ~{~A~^ ~}) => ~A"
                   (make-string *recursion-depth*
                                :element-type 'base-char
                                :initial-element #\ )
                   *recursion-depth*
                   ',fname
                   (list ,@args)
                   ,value)
           ,value))))

  (defun %extract-declarations (body)
    (remove-if-not (lambda (form) (eql 'declare (car (if (listp form) form (list form)))))
                   body))

  (defun %parse-cache-form (cache-specifier)
    (let ((cache-type (car cache-specifier))
          (cache-attribs (cdr cache-specifier)))
      (assert (member cache-type '(:hash-table :array)))
      (let* ((dims-with-* (when (eql cache-type :array) (first cache-attribs)))
             (dims (remove '* dims-with-*))
             (rank (length dims))
             (rest-attribs (ecase cache-type
                             (:hash-table cache-attribs)
                             (:array (cdr cache-attribs))))
             (key (prog1 (getf rest-attribs :key) (remf rest-attribs :key)))
             (trace-p (prog1 (getf rest-attribs :trace) (remf rest-attribs :trace)))
             (cache-form (case cache-type
                           (:hash-table `(make-hash-table ,@rest-attribs))
                           (:array `(make-array (list ,@dims) ,@rest-attribs))))
             (initial-element (when (eql cache-type :array)
                                (assert (member :initial-element rest-attribs))
                                (getf rest-attribs :initial-element))))
        (let ((cache (gensym "CACHE"))
              (value (gensym))
	      (present-p (gensym))
              (name-alias (gensym))
	      (args-lst (gensym))
              (indices (loop repeat rank collect (gensym))))
          (labels
              ((make-cache-querier (cache-type name args)
                 (let ((res (case cache-type
                              (:hash-table
                               `(let ((,args-lst (funcall ,(or key #'list) ,@args)))
                                  (multiple-value-bind (,value ,present-p)
                                      (gethash ,args-lst ,cache)
                                    (if ,present-p
                                        ,value
                                        (setf (gethash ,args-lst ,cache)
                                              (,name-alias ,@args))))))
                              (:array
                               (let ((memoized-args (loop for dimension in dims-with-*
                                                          for arg in args
                                                          unless (eql dimension '*)
                                                          collect arg)))
                                 (if key
                                     `(multiple-value-bind ,indices
                                          (funcall ,key ,@memoized-args)
                                        (let ((,value (aref ,cache ,@indices)))
                                          (if (eql ,initial-element ,value)
                                              (setf (aref ,cache ,@indices)
                                                    (,name-alias ,@args))
                                              ,value)))
                                     `(let ((,value (aref ,cache ,@memoized-args)))
                                        (if (eql ,initial-element ,value)
                                            (setf (aref ,cache ,@memoized-args)
                                                  (,name-alias ,@args))
                                            ,value))))))))
                   (if trace-p
                       (%enclose-with-tracing name args res)
                       res)))
               (make-reset-form (cache-type)
                 (case cache-type
                   (:hash-table `(setf ,cache (make-hash-table ,@rest-attribs)))
                   (:array `(prog1 nil
                              (fill (array-storage-vector ,cache) ,initial-element)))))
               (make-reset-name (name)
                 (intern (format nil "RESET-~A" (symbol-name name)))))
            (values cache cache-form cache-type name-alias
                    #'make-reset-name
                    #'make-reset-form
                    #'make-cache-querier)))))))

(defmacro with-caches (cache-specs def-form)
  "DEF-FORM := definition form with LABELS or FLET.

 (with-caches (cache-spec1 cache-spec2)
   (labels ((f (x) ...) (g (y) ...))))
is equivalent to the line up of
 (with-cache cache-spec1 (labels ((f (x) ...))))
and
 (with-cache cache-spec2 (labels ((g (y) ...)))) "
  (assert (member (car def-form) '(labels flet)))
  (let (cache-symbol-list cache-form-list cache-type-list name-alias-list make-reset-name-list make-reset-form-list make-cache-querier-list)
    (dolist (cache-spec (reverse cache-specs))
      (multiple-value-bind (cache-symbol cache-form cache-type name-alias
                            make-reset-name make-reset-form make-cache-querier)
          (%parse-cache-form cache-spec)
        (push cache-symbol cache-symbol-list)
        (push cache-form cache-form-list)
        (push cache-type cache-type-list)
        (push name-alias name-alias-list)
        (push make-reset-name make-reset-name-list)
        (push make-reset-form make-reset-form-list)
        (push make-cache-querier make-cache-querier-list)))
    (labels ((def-name (def) (first def))
             (def-args (def) (second def))
             (def-body (def) (cddr def)))
      (destructuring-bind (_ definitions &body labels-body) def-form
        (declare (ignore _))
        `(let ,(loop for cache-symbol in cache-symbol-list
                     for cache-form in cache-form-list
                     collect `(,cache-symbol ,cache-form))
           (,(car def-form)
            (,@(loop for def in definitions
                     for cache-type in cache-type-list
                     for make-reset-name in make-reset-name-list
                     for make-reset-form in make-reset-form-list
                     collect `(,(funcall make-reset-name (def-name def)) ()
                               ,(funcall make-reset-form cache-type)))
             ,@(loop for def in definitions
                     for cache-type in cache-type-list
                     for name-alias in name-alias-list
                     for make-cache-querier in make-cache-querier-list
                     collect `(,(def-name def) ,(def-args def)
                               ,@(%extract-declarations (def-body def))
                               (labels ((,name-alias ,(def-args def) ,@(def-body def)))
                                 (declare (inline ,name-alias))
                                 ,(funcall make-cache-querier cache-type (def-name def) (def-args def))))))
            (declare (ignorable ,@(loop for def in definitions
                                        for make-reset-name in make-reset-name-list
                                        collect `#',(funcall make-reset-name
                                                             (def-name def)))))
            ,@labels-body))))))

(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (term-char #\Space))
  "Reads ASCII inputs and returns two values: the string and the end
position. Note that the returned string will be reused if this form is executed
more than once.

This macro calls READ-BYTE to read characters though it calls READ-CHAR instead
on SLIME because SLIME's IO is not bivalent."
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let* ((,buffer (load-time-value (make-string ,buffer-size :element-type 'base-char))))
       (declare (simple-base-string ,buffer)
                (inline read-byte))
       (loop for ,character of-type base-char =
                ,(if (member :swank *features*)
                     `(read-char ,in nil #\Newline) ; on SLIME
                     `(code-char (read-byte ,in nil #.(char-code #\Newline))))
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (when (< ,idx ,buffer-size)
                       (setf (schar ,buffer ,idx) ,term-char))
                     (return (values ,buffer ,idx))))))

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

(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 (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 ()
  (let* ((h (read))
         (w (read))
         (cumuls (make-array (list (+ h 1) (+ w 1)) :element-type 'uint32 :initial-element 0)))
    (declare (uint8 h w))
    (dotimes (i h)
      (let ((line (buffered-read-line 185)))
        (dotimes (j w)
          (when (char= #\# (aref line j))
            (setf (aref cumuls (+ i 1) (+ j 1)) 1)))))
    (dotimes (i (+ h 1))
      (dotimes (j w)
        (incf (aref cumuls i (+ j 1)) (aref cumuls i j))))
    (dotimes (j (+ w 1))
      (dotimes (i h)
        (incf (aref cumuls (+ i 1) j) (aref cumuls i j))))
    (with-caches ((:array ((+ h 1) (+ w 1) (+ h 1) 20)
                   :element-type 'uint8
                   :initial-element #xff)
                  (:array ((+ h 1) (+ w 1) (+ w 1) 20)
                   :element-type 'uint8
                   :initial-element #xff))
      (labels
          ((f (y1 x1 y2 c)
             (declare (uint8 y1 x1 y2 c))
             (if (zerop c)
                 (sb-int:named-let bisect ((ok x1) (ng (+ w 1)))
                   (declare (uint8 ok ng))
                   (if (<= (- ng ok) 1)
                       ok
                       (let* ((mid (floor (+ ok ng) 2))
                              (sum (get-2dcumul cumuls y1 x1 y2 mid)))
                         (if (or (= sum (* (- y2 y1) (- mid x1)))
                                 (= sum 0))
                             (bisect mid ng)
                             (bisect ok mid)))))
                 (let ((res1 (f y1 (f y1 x1 y2 (- c 1)) y2 (- c 1)))
                       (res2 (sb-int:named-let bisect ((ok x1) (ng (+ w 1)))
                               (declare (uint8 ok ng))
                               (if (<= (- ng ok) 1)
                                   ok
                                   (let* ((mid (floor (+ ok ng) 2))
                                          (val (g (g y1 x1 mid (- c 1)) x1 mid (- c 1))))
                                     (if (>= val y2)
                                         (bisect mid ng)
                                         (bisect ok mid)))))))
                   (max res1 res2))))
           (g (y1 x1 x2 c)
             (declare (uint8 y1 x1 x2 c))
             (if (zerop c)
                 (sb-int:named-let bisect ((ok y1) (ng (+ h 1)))
                   (declare (uint8 ok ng))
                   (if (<= (- ng ok) 1)
                       ok
                       (let* ((mid (floor (+ ok ng) 2))
                              (sum (get-2dcumul cumuls y1 x1 mid x2)))
                         (if (or (= sum (* (- mid y1) (- x2 x1)))
                                 (= sum 0))
                             (bisect mid ng)
                             (bisect ok mid)))))
                 (let ((res1 (g (g y1 x1 x2 (- c 1)) x1 x2 (- c 1)))
                       (res2 (sb-int:named-let bisect ((ok y1) (ng (+ h 1)))
                               (declare (uint8 ok ng))
                               (if (<= (- ng ok) 1)
                                   ok
                                   (let* ((mid (floor (+ ok ng) 2))
                                          (val (f y1 (f y1 x1 mid (- c 1)) mid (- c 1))))
                                     (if (>= val x2)
                                         (bisect mid ng)
                                         (bisect ok mid)))))))
                   (max res1 res2)))))
        (dotimes (c 20)
          (let  ((x (f 0 0 h c)))
            (when (= x w)
              (println c)
              (return-from main))))))))

#-swank (main)

Score : 1000 points

Problem Statement

Note the unusual memory limit.

For a rectangular grid where each square is painted white or black, we define its complexity as follows:

If all the squares are black or all the squares are white, the complexity is 0.

Otherwise, divide the grid into two subgrids by a line parallel to one of the sides of the grid, and let c_1 and c_2 be the complexities of the subgrids. There can be multiple ways to perform the division, and let m be the minimum value of \max(c_1, c_2) in those divisions. The complexity of the grid is m+1.

You are given a grid with H horizontal rows and W vertical columns where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

Find the complexity of the given grid.

Constraints

1 \leq H,W \leq 185

A_{ij} is # or ..

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the complexity of the given grid.

Sample Input 1

3 3
...
.##
.##

Sample Output 1

2

Let us divide the grid by the boundary line between the first and second columns.
The subgrid consisting of the first column has the complexity of 0, and the subgrid consisting of the second and third columns has the complexity of 1, so the whole grid has the complexity of at most 2.

Sample Input 2

6 7
.####.#
#....#.
#....#.
#....#.
.####.#
#....##

Sample Output 2

4


(defmacro aif(test then else)
  `(let ((it ,test))
     (if it ,then ,else)))

(defun split (pattern str)
  (aif (search pattern str)
       (cons (subseq str 0 it) (split pattern (subseq str (+ it (length pattern)))))
       (list str)))

(defun main ()
  (let* ((input (split " " (read-line)))
         (a (parse-integer (first input)))
         (b (parse-integer (second input)))
         (tt (parse-integer (third input))))
    (print (* (floor tt a) b))))
(main)

Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


(let ((a (read))
      (b (read))
      (c (read)))
  (princ (* (floor c a) b)))