(defun duplicate-char-counter (str separator)
  (labels ((duplicate-char-counter (char-list cnt)
             (if char-list
                 (duplicate-char-counter (cdr char-list)
                                         (if (find (car char-list) str :start separator :test #'char=)
                                             (1+ cnt)
                                             cnt))
                 cnt)))
    (let ((char-list (coerce (remove-duplicates (subseq str 0 separator)) 'list)))
      (duplicate-char-counter char-list 0))))

(princ (loop for separator from 1 upto (1- (read))
             with input-str = (read-line)
             maximize (duplicate-char-counter input-str separator)))

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters.
We will cut this string at one position into two strings X and Y.
Here, we would like to maximize the number of different letters contained in both X and Y.
Find the largest possible number of different letters contained in both X and Y when we cut the string at the optimal position.

Constraints

2 \leq N \leq 100

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the largest possible number of different letters contained in both X and Y.

Sample Input 1

6
aabbca

Sample Output 1

2

If we cut the string between the third and fourth letters into X = aab and Y = bca, the letters contained in both X and Y are a and b.
There will never be three or more different letters contained in both X and Y, so the answer is 2.

Sample Input 2

10
aaaaaaaaaa

Sample Output 2

1

However we divide S, only a will be contained in both X and Y.

Sample Input 3

45
tgxgdqkyjzhyputjjtllptdfxocrylqfqjynmfbfucbir

Sample Output 3

9


(defun solve (N arr)
  (let (tmp)
       (loop for i from (1- N) downto 0
             with sum = 0
             do (push sum tmp)
             if (eq (aref arr i) #\E) do (incf sum))
       (loop for x across arr with sum = 0
             for y in tmp
             minimize (+ y sum)
             if (eq x #\W) do (incf sum))))

(princ (solve (read) (concatenate 'vector (read-line))))

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

Score : 300 points

Problem Statement

There are N people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string S of length N.
The i-th person from the west is facing east if S_i = E, and west if S_i = W.

You will appoint one of the N people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

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

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is 1 in this case.
It is not possible to have 0 people who have to change their directions, so the answer is 1.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3

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 solve (p)
  (let ((last (aref p 0))
        (amax 0)
        idx
        (a 0))
    (loop for i from 1 below (length p)
          do (let ((p2 (aref p i)))
               (if (< p2 last)
                   (if (< amax p2)
                       (setf amax p2
                             idx i))
                   (setf last p2))))
    (when idx
      (loop for i to idx
            do (when (<= (aref p i) amax)
                 (incf a))))
    a))

(let ((p (make-array (read))))
  (loop for i below (length p)
        do (setf (aref p i) (read)))
  (princ (solve p))
  (terpri))

Score : 500 points

Problem Statement

You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N.
You would like to sort this sequence in ascending order by repeating the following operation:

Choose an element in the sequence and move it to the beginning or the end of the sequence.

Find the minimum number of operations required.
It can be proved that it is actually possible to sort the sequence using this operation.

Constraints

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

(P_1,P_2,...,P_N) is a permutation of (1,2,...,N).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1
:
P_N

Output

Print the minimum number of operations required.

Sample Input 1

4
1
3
2
4

Sample Output 1

2

For example, the sequence can be sorted in ascending order as follows:

Move 2 to the beginning. The sequence is now (2,1,3,4).

Move 1 to the beginning. The sequence is now (1,2,3,4).

Sample Input 2

6
3
2
5
1
4
6

Sample Output 2

4

Sample Input 3

8
6
3
1
2
7
4
8
5

Sample Output 3

5


Score : 100 points

Problem Statement

Three people, A, B and C, are trying to communicate using transceivers.
They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively.
Two people can directly communicate when the distance between them is at most d meters.
Determine if A and C can communicate, either directly or indirectly.
Here, A and C can indirectly communicate when A and B can directly communicate and also B and C can directly communicate.

Constraints

1 ≤ a,b,c ≤ 100

1 ≤ d ≤ 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

If A and C can communicate, print Yes; if they cannot, print No.

Sample Input 1

4 7 9 3

Sample Output 1

Yes

A and B can directly communicate, and also B and C can directly communicate, so we should print Yes.

Sample Input 2

100 10 1 2

Sample Output 2

No

They cannot communicate in this case.

Sample Input 3

10 10 10 1

Sample Output 3

Yes

There can be multiple people at the same position.

Sample Input 4

1 100 2 10

Sample Output 4

Yes


(let* ((s (read-line))
       (k (read))
       (l (length s))
       (lset))
  (loop for i from 1 to k
        do (loop for j to (- l i)
                 do (pushnew (subseq s j (+ i j)) lset
                             :test #'equal)))
  (format t "~A~%"
          (nth (1- k) (sort lset #'string<))))

Score : 300 points

Problem Statement

You are given a string s.
Among the different substrings of s, print the K-th lexicographically smallest one.

A substring of s is a string obtained by taking out a non-empty contiguous part in s.
For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z and an empty string are not.
Also, we say that substrings are different when they are different as strings.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

1 ≤ |s| ≤ 5000

s consists of lowercase English letters.

1 ≤ K ≤ 5

s has at least K different substrings.

Partial Score

200 points will be awarded as a partial score for passing the test set satisfying |s| ≤ 50.

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.

Sample Input 1

aba
4

Sample Output 1

b

s has five substrings: a, b, ab, ba and aba.
Among them, we should print the fourth smallest one, b.
Note that we do not count a twice.

Sample Input 2

atcoderandatcodeer
5

Sample Output 2

andat

Sample Input 3

z
1

Sample Output 3

z


;; -*- coding:utf-8 -*-

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 1))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))))

(defmacro print-line (obj &optional (stream '*standard-output*))
  `(prog1 (princ ,obj ,stream) (terpri ,stream)))

;; Hauptteil

(declaim (inline dict<))
(defun dict< (str1 str2)
  (declare #.OPT
           (base-string str1 str2))
  (let* ((len1 (length str1))
         (len2 (length str2))
         (len (min len1 len2)))
    (loop for i below len
          for c1 = (aref str1 i)
          for c2 = (aref str2 i)
          do (cond ((char< c1 c2) (return t))
                   ((char> c1 c2) (return nil)))
          finally (return (if (< len1 len2) t nil)))))

(declaim (inline enum-words))
(defun enum-words (source)
  (declare #.OPT
           (base-string source))
  (let ((len (length source))
        res)
    (dotimes (idx1 len res)
      (loop for width from 1 to 5
            while (<= (+ idx1 width) len)
            do (push (make-array width
                                 :element-type 'base-char
                                 :displaced-to source
                                 :displaced-index-offset idx1)
                     res)))))

(defun get-min (tmp-min lst)
  (declare #.OPT)
  (cond ((null lst) tmp-min)
        ((dict< (car lst) tmp-min) (get-min (car lst) (cdr lst)))
        (t (get-min tmp-min (cdr lst)))))

(defun get-nth-min (n lst)
  (declare #.OPT
           (uint n))
  (let ((min (get-min (car lst) lst)))
    (if (= n 1)
        min
        (get-nth-min (- n 1)
                     (delete min lst :test #'string=)))))

(deftype uint nil `(integer 0 ,(expt 10 9)))
(defun main ()
  (declare #.OPT)
  (let ((str (coerce (read-line) 'base-string))
        (n (read)))
    (write-line (get-nth-min n (enum-words str)))))

#-swank(main)


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           ;; enclose the form with VALUES to avoid being captured by LOOP macro
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Succinct bit vector
;;;

;; REVIEW: Is it really better to use the typical three-layer succint bit vector
;; in competitive programming? It may be efficient to use a two-layer (not
;; succinct but compact) bit vector preserving the original vector and the
;; cumulative sum per 64-bit word.

(defconstant +chunk-width+ (* 64 16))
;; This constant cannot be changed as the current implementation depends on the
;; assumption: +BLOCK-WIDTH+ is equal to the word size.
(defconstant +block-width+ 64)
(defconstant +block-number+ (floor +chunk-width+ +block-width+))

(eval-when (:compile-toplevel :load-toplevel :execute)
  (assert (zerop (mod +chunk-width+ +block-width+)))
  (assert (= sb-vm:n-word-bits 64)))

(defstruct (succinct-bit-vector (:constructor %make-sucbv (storage chunks blocks))
                                (:conc-name sucbv-)
                                (:copier nil))
  (storage nil :type simple-bit-vector)
  (chunks nil :type (simple-array (integer 0 #.most-positive-fixnum) (*)))
  (blocks nil :type (simple-array (unsigned-byte 16) (* *))))

(defun make-sucbv! (vector)
  "The consequence is undefined when VECTOR is modified after a succinct bit
vector is created."
  (declare (optimize (speed 3)))
  (check-type vector simple-bit-vector)
  (let* ((vector (if (zerop (mod (length vector) +chunk-width+))
                     vector
                     (adjust-array vector
                                   (* +chunk-width+ (ceiling (length vector) +chunk-width+))
                                   :initial-element 0)))
         (len (length vector))
         (chunk-count (floor len +chunk-width+))
         (chunks (make-array (+ 1 chunk-count)
                             :element-type '(integer 0 #.most-positive-fixnum)
                             :initial-element 0))
         (blocks (make-array (list (+ 1 chunk-count) +block-number+)
                             :element-type '(unsigned-byte 16)
                             :initial-element 0))
         (sum 0))
    (declare (simple-bit-vector vector)
             ((integer 0 #.most-positive-fixnum) sum))
    (dotimes (i chunk-count)
      (setf (aref chunks i) sum)
      (let ((block-sum 0))
        (declare ((integer 0 #.most-positive-fixnum) block-sum))
        (dotimes (j +block-number+)
          (setf (aref blocks i j) block-sum)
          (incf block-sum
                (logcount (sb-kernel:%vector-raw-bits vector (+ (* i +block-number+) j)))))
        (incf sum block-sum)))
    (setf (aref chunks chunk-count) sum)
    (%make-sucbv vector chunks blocks)))

(declaim (inline sucbv-ref))
(defun sucbv-ref (sucbv index)
  (sbit (sucbv-storage sucbv) index))

;; NOTE: No error handling.
(declaim (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional)) sucbv-rank))
(defun sucbv-rank (sucbv end)
  "Counts the number of 1's in the range [0, END)."
  (declare (optimize (speed 3))
           ((integer 0 #.most-positive-fixnum) end))
  (let ((storage (sucbv-storage sucbv))
        (chunks (sucbv-chunks sucbv))
        (blocks (sucbv-blocks sucbv)))
    (multiple-value-bind (cpos crem) (floor end +chunk-width+)
      (multiple-value-bind (bpos brem) (floor crem +block-width+)
        (let ((csum (aref chunks cpos))
              (bsum (aref blocks cpos bpos))
              (wordpos (floor end 64)))
          (+ csum
             bsum
             (if (zerop brem) ; avoid out-of-bounds access
                 0
                 (logcount (ldb (byte brem 0)
                                (sb-kernel:%vector-raw-bits storage wordpos))))))))))

(declaim (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional)) sucbv-count))
(defun sucbv-count (sucbv value end)
  "Counts the number of VALUEs in the range [0, END)"
  (declare (optimize (speed 3))
           (bit value)
           ((integer 0 #.most-positive-fixnum) end))
  (let ((count1 (sucbv-rank sucbv end)))
    (if (= value 1)
        count1
        (- end count1))))

(defun sucbv-select (sucbv num)
  "Detects the position of (1-based) NUM-th 1 in SUCBV. (SUCBV-SELECT 0) always
returns 0."
  (declare (optimize (speed 3))
           ((integer 0 #.most-positive-fixnum) num))
  (let* ((storage (sucbv-storage sucbv))
         (chunks (sucbv-chunks sucbv))
         (blocks (sucbv-blocks sucbv))
         (chunk-size (length chunks)))
    (unless (<= num (aref chunks (- chunk-size 1)))
      ;; FIXME: introduce condition class
      (error "~&There aren't ~W 1's in ~W" num sucbv))
    (labels ((chunk-bisect (ok ng)
               (declare ((unsigned-byte 32) ok ng))
               (if (<= (- ng ok) 1)
                   ok
                   (let ((mid (ash (+ ok ng) -1)))
                     (if (<= num (aref chunks mid))
                         (chunk-bisect ok mid)
                         (chunk-bisect mid ng))))))
      (let* ((chunk-idx (chunk-bisect 0 chunk-size))
             (num (- num (aref chunks chunk-idx))))
        (labels ((block-bisect (ok ng)
                   (declare ((unsigned-byte 32) ok ng))
                   (if (<= (- ng ok) 1)
                       ok
                       (let ((mid (ash (+ ok ng) -1)))
                         (if (<= num (aref blocks chunk-idx mid))
                             (block-bisect ok mid)
                             (block-bisect mid ng))))))
          (let* ((block-idx (block-bisect 0 +block-number+))
                 (num (- num (aref blocks chunk-idx block-idx)))
                 (word-pos (+ block-idx (* chunk-idx +block-number+)))
                 (word (sb-kernel:%vector-raw-bits storage word-pos)))
            (labels ((pos-bisect (ok ng)
                       (declare ((integer 0 64) ok ng))
                       (if (<= (- ng ok) 1)
                           ok
                           (let ((mid (ash (+ ok ng) -1)))
                             (if (<= num (logcount (ldb (byte mid 0) word)))
                                 (pos-bisect ok mid)
                                 (pos-bisect mid ng))))))
              (let ((pos (pos-bisect 0 64)))
                (+ (* 64 word-pos) pos)))))))))

;;;
;;; Wavelet matrix
;;;

(deftype wavelet-integer () '(integer 0 #.most-positive-fixnum))

(defstruct (wavelet-matrix (:constructor %make-wavelet-matrix
                               (length data zeros
                                &aux (depth (array-dimension data 0))))
                           (:copier nil)
                           (:conc-name wavelet-))
  (depth 0 :type (integer 1 #.most-positive-fixnum))
  (length 0 :type (integer 0 #.most-positive-fixnum))
  (data nil :type (simple-array succinct-bit-vector (*)))
  (zeros nil :type (simple-array (integer 0 #.most-positive-fixnum) (*))))

#+sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-c:defknown make-wavelet ((integer 1 #.most-positive-fixnum) vector)
      wavelet-matrix (sb-c:flushable)
    :overwrite-fndb-silently t))

;; TODO: add deftransform for better type derivation
(defun make-wavelet (bit-depth vector)
  (declare ((integer 1 #.most-positive-fixnum) bit-depth))
  (let* ((len (length vector))
         (fitted-len (* +chunk-width+ (ceiling len +chunk-width+)))
         (data (locally (declare #+sbcl (muffle-conditions style-warning))
                 (make-array bit-depth :element-type 'succinct-bit-vector)))
         (zeros (make-array bit-depth :element-type '(integer 0 #.most-positive-fixnum)))
         (tmp (copy-seq vector))
         (lefts (make-array len :element-type (array-element-type vector)))
         (rights (make-array len :element-type (array-element-type vector)))
         (bits (make-array fitted-len :element-type 'bit)))
    (declare ((integer 0 #.most-positive-fixnum) len fitted-len)
             (vector tmp))
    (loop for d from (- bit-depth 1) downto 0
          do (let ((lpos 0)
                   (rpos 0))
               (declare ((integer 0 #.most-positive-fixnum) lpos rpos))
               (dotimes (i len)
                 (let ((bit (logand 1 (ash (aref tmp i) (- d)))))
                   (if (zerop bit)
                       (setf (aref lefts lpos) (aref tmp i)
                             lpos (+ lpos 1))
                       (setf (aref rights rpos) (aref tmp i)
                             rpos (+ rpos 1)))
                   (setf (aref bits i) bit)))
               (setf (aref data d) (make-sucbv! (copy-seq bits))
                     (aref zeros d) lpos)
               (rotatef lefts tmp)
               (replace tmp rights :start1 lpos :end2 rpos)))
    (%make-wavelet-matrix len data zeros)))

(define-condition invalid-wavelet-index-error (type-error)
  ((wavelet :initarg :wavelet :reader invalid-wavelet-index-error-wavelet)
   (index :initarg :index :reader invalid-wavelet-index-error-index))
  (:report
   (lambda (condition stream)
     (let ((index (invalid-wavelet-index-error-index condition)))
       (if (consp index)
           (format stream "Invalid range [~W, ~W) for wavelet-matrix ~W."
                   (car index)
                   (cdr index)
                   (invalid-wavelet-index-error-wavelet condition))
           (format stream "Invalid index ~W for wavelet-matrix ~W."
                   index
                   (invalid-wavelet-index-error-wavelet condition)))))))

(defun wavelet-range-count (wmatrix lo hi &key (start 0) end)
  (declare (optimize (speed 3))
           ((integer 0 #.most-positive-fixnum) lo hi start)
           ((or null (integer 0 #.most-positive-fixnum)) end))
  (let ((data (wavelet-data wmatrix))
        (zeros (wavelet-zeros wmatrix))
        (end (or end (wavelet-length wmatrix))))
    (assert (<= lo hi))
    (unless (<= start end (wavelet-length wmatrix))
      (error 'invalid-wavelet-index-error :index (cons start end) :wavelet wmatrix))
    (labels
        ((dfs (depth start end value)
           (declare ((integer 0 #.most-positive-fixnum) start end value)
                    ((integer -1 #.most-positive-fixnum) depth)
                    #+sbcl (values (integer 0 #.most-positive-fixnum)))
           (cond ((or (= start end)
                      (<= hi value))
                  0)
                 ((= depth -1)
                  (if (< value lo)
                      0
                      (- end start)))
                 (t
                  (let* ((next-value (logior value
                                             (the wavelet-integer (ash 1 depth))))
                         (upper-bound (logior next-value
                                              (- (the wavelet-integer (ash 1 depth)) 1))))
                    (cond ((< upper-bound lo)
                           0)
                          ((and (<= lo value) (< upper-bound hi))
                           (- end start))
                          (t
                           (let ((lcount (sucbv-rank (aref data depth) start))
                                 (rcount (sucbv-rank (aref data depth) end)))
                             (+ (dfs (- depth 1)
                                     (- start lcount)
                                     (- end rcount)
                                     value)
                                (dfs (- depth 1)
                                     (+ (aref zeros depth) lcount)
                                     (+ (aref zeros depth) rcount)
                                     next-value))))))))))
      (dfs (- (wavelet-depth wmatrix) 1) start end 0))))

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

(defconstant +inf+ (- (expt 2 11) 1))

(defun main ()
  (let* ((n (read))
         (ws-plan (make-array (* 2 n) :element-type 'uint16 :initial-element +inf+))
         (bs-plan (make-array (* 2 n) :element-type 'uint16 :initial-element +inf+))
         (ws-pos (make-array (+ n 1) :element-type 'uint16))
         (bs-pos (make-array (+ n 1) :element-type 'uint16))
         (dp (make-array (list (+ n 1) (+ n 1))
                         :element-type 'uint32
                         :initial-element 0)))
    (declare (uint16 n))
    (dotimes (i (* 2 n))
      (let ((col (read))
            (a (read)))
        (if (eql col 'w)
            (setf (aref ws-plan i) a
                  (aref ws-pos a) i)
            (setf (aref bs-plan i) a
                  (aref bs-pos a) i))))
    (let ((ws-plan (make-wavelet 12 ws-plan))
          (bs-plan (make-wavelet 12 bs-plan)))
      (loop
        for x from 0 to n
        do (loop
             for y from 0 to n
             do (unless (= x y 0)
                  (setf (aref dp x y)
                        (min
                         (if (zerop y)
                             #xffffffff
                             (let ((pos (aref bs-pos y)))
                               (+ (aref dp x (- y 1))
                                  (wavelet-range-count ws-plan 0 (+ x 1) :start (+ pos 1))
                                  (wavelet-range-count bs-plan 0 y :start (+ pos 1))
                                  (wavelet-range-count ws-plan (+ x 1) 2001 :end pos)
                                  (wavelet-range-count bs-plan (+ y 1) 2001 :end pos))))
                         (if (zerop x)
                             #xffffffff
                             (let ((pos (aref ws-pos x)))
                               (+ (aref dp (- x 1) y)
                                  (wavelet-range-count ws-plan 0 x :start (+ pos 1))
                                  (wavelet-range-count bs-plan 0 (+ y 1) :start (+ pos 1))
                                  (wavelet-range-count ws-plan (+ x 1) 2001 :end pos)
                                  (wavelet-range-count bs-plan (+ y 1) 2001 :end pos))))))))))
    #>dp
    (println (floor (aref dp n n) 2))))

#-swank (main)

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

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

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    ;; (run-program "C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe" '("get-clipboard") :output out)
    (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)))

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
B 1
W 2
B 3
W 1
W 3
B 2
"
    "4
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4
B 4
W 4
B 3
W 3
B 2
W 2
B 1
W 1
"
    "18
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "9
W 3
B 1
B 4
W 1
B 5
W 9
W 2
B 6
W 5
B 3
W 8
B 9
W 7
B 2
B 8
W 4
W 6
B 7
"
    "41
")))

Score : 600 points

Problem Statement

There are 2N balls, N white and N black, arranged in a row. The integers from 1 through N are written on the white balls, one on each ball, and they are also written on the black balls, one on each ball.
The integer written on the i-th ball from the left (1 ≤ i ≤ 2N) is a_i, and the color of this ball is represented by a letter c_i.
c_i = W represents the ball is white; c_i = B represents the ball is black.

Takahashi the human wants to achieve the following objective:

For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the white ball with i written on it is to the left of the white ball with j written on it.

For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the black ball with i written on it is to the left of the black ball with j written on it.

In order to achieve this, he can perform the following operation:

Swap two adjacent balls.

Find the minimum number of operations required to achieve the objective.

Constraints

1 ≤ N ≤ 2000

1 ≤ a_i ≤ N

c_i = W or c_i = B.

If i ≠ j, (a_i,c_i) ≠ (a_j,c_j).

Input

Input is given from Standard Input in the following format:

N
c_1 a_1
c_2 a_2
:
c_{2N} a_{2N}

Output

Print the minimum number of operations required to achieve the objective.

Sample Input 1

3
B 1
W 2
B 3
W 1
W 3
B 2

Sample Output 1

4

The objective can be achieved in four operations, for example, as follows:

Swap the black 3 and white 1.

Swap the white 1 and white 2.

Swap the black 3 and white 3.

Swap the black 3 and black 2.

Sample Input 2

4
B 4
W 4
B 3
W 3
B 2
W 2
B 1
W 1

Sample Output 2

18

Sample Input 3

9
W 3
B 1
B 4
W 1
B 5
W 9
W 2
B 6
W 5
B 3
W 8
B 9
W 7
B 2
B 8
W 4
W 6
B 7

Sample Output 3

41


(let ((a (read))
      (b (read)))
     (if (> a b)
         (format t "~A" (1- a))
         (format t "~A" a)))

Score: 100 points

Problem Statement

In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.

For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.

In this country, a date is called Takahashi when the month and the day are equal as numbers. For example, 5-5 is Takahashi.

How many days from 2018-1-1 through 2018-a-b are Takahashi?

Constraints

a is an integer between 1 and 12 (inclusive).

b is an integer between 1 and 31 (inclusive).

2018-a-b is a valid date in Gregorian calendar.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the number of days from 2018-1-1 through 2018-a-b that are Takahashi.

Sample Input 1

5 5

Sample Output 1

5

There are five days that are Takahashi: 1-1, 2-2, 3-3, 4-4 and 5-5.

Sample Input 2

2 1

Sample Output 2

1

There is only one day that is Takahashi: 1-1.

Sample Input 3

11 30

Sample Output 3

11

There are eleven days that are Takahashi: 1-1, 2-2, 3-3, 4-4, 5-5, 6-6, 7-7, 8-8, 9-9, 10-10 and 11-11.


(let ((ans (- (read) 1))
      (n (read)))
 (format t "~A~%" (if (< n ans) ans (1+ ans))))


(defun sieve (n)
  (let ((is-prime (make-array (1+ n)
                              :initial-element t))
        (primes '()))
    (setf (svref is-prime 0) nil)
    (setf (svref is-prime 1) nil)
    (loop for i from 2 to n
          do (when (svref is-prime i)
               (push i primes)
               (loop for j from (* 2 i) to n by i
                     do (setf (svref is-prime j) nil))))
    (nreverse primes)))

(defparameter goods
  (remove-if (lambda (n) (/= (mod n 5) 1))
             (sieve 55555)))

(defparameter n (read))
(format t "~{~a~^ ~}~%"
        (subseq goods 0 n))


(defun split-string (str)
  (let ((string-position (position #\Space str)))
    (cond
      ((null string-position) (list str))
      (t (cons (subseq str 0 string-position) (split-string (subseq str (1+ string-position)))))
      )))

(defun readline-to-list ()
  (let ((str (read-line *standard-input* nil)))
    (cond
      ((null str) nil)
      ((string= str "") nil)
      (t (cons str (readline-to-list))))))

(defun takahashi (a b)
  (let ((result (+ (parse-integer a) (if (>= (parse-integer b) (parse-integer a)) 0 -1))))
    (format t "~A~%" result)))

(apply #'takahashi (split-string (read-line)))


(defun solver ()
  (let* ((a (read)) (b (read)))
    (if (>= b a)
        (format t "~a~%" a)
        (format t "~a~%" (1- a)))))

(solver)


(setq a(read))
(setq b(read))
(setq c(read))
(princ(+ a b c(*(max a b c)(1-(expt 2(read))))))

Score: 200 points

Problem Statement

There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:

Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.

What is the largest possible sum of the integers written on the blackboard after K operations?

Constraints

A, B and C are integers between 1 and 50 (inclusive).

K is an integer between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C
K

Output

Print the largest possible sum of the integers written on the blackboard after K operations by E869220.

Sample Input 1

5 3 11
1

Sample Output 1

30

In this sample, 5, 3, 11 are initially written on the blackboard, and E869120 can perform the operation once.

There are three choices:

Double 5: The integers written on the board after the operation are 10, 3, 11.

Double 3: The integers written on the board after the operation are 5, 6, 11.

Double 11: The integers written on the board after the operation are 5, 3, 22.

If he chooses 3., the sum of the integers written on the board afterwards is 5 + 3 + 22 = 30, which is the largest among 1. through 3.

Sample Input 2

3 3 4
2

Sample Output 2

22

E869120 can perform the operation twice. The sum of the integers eventually written on the blackboard is maximized as follows:

First, double 4. The integers written on the board are now 3, 3, 8.

Next, double 8. The integers written on the board are now 3, 3, 16.

Then, the sum of the integers eventually written on the blackboard is 3 + 3 + 16 = 22.


(defun split-string (str)
  (let ((string-position (position #\Space str)))
    (cond
      ((null string-position) (list str))
      (t (cons (subseq str 0 string-position) (split-string (subseq str (1+ string-position)))))
      )))

(defun readline-to-list ()
  (let ((str (read-line *standard-input* nil)))
    (cond
      ((null str) nil)
      ((string= str "") nil)
      (t (cons str (readline-to-list))))))

(defun MaximumSum (k a b c)
  (let* ((sortedList (sort (list (parse-integer c) (parse-integer b) (parse-integer a)) #'>)) (m (car sortedList)))
    (dotimes (i (parse-integer k)) (setf m (* 2 m)))
     (format t "~A~%" (+ m (cadr sortedList) (caddr sortedList)))))

(let* ((r-list (readline-to-list))
       (tmp (split-string (car r-list)))
       (real-list (cons (cadr r-list) tmp)))
  (apply #'MaximumSum real-list))


(defun solver ()
  (let* ((a (read)) (b (read)) (c (read))
         (k (read)) (result 0) (max (max a b c))
         (max2 (* (expt 2 k) max)))
    (cond ((= a max) (setf result (+ max2 b c)))
          ((= b max) (setf result (+ a max2 c)))
          ((= c max) (setf result (+ a b max2))))
    (format t "~a~%" result)))

(solver)


#-swank
(unless (member :child-sbcl *features*)
  "I refered from https://competitive12.blogspot.com/2020/03/common-lisp.html thank you!"
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))
(defmacro dp (name args memo-size &body body)
  (let ((memo (gensym)))
    `(let ((,memo (make-array ,memo-size :initial-element nil)))
       (defun ,name ,args
         (or (aref ,memo ,@args)
             (setf (aref ,memo ,@args)
                   ,@body))))))

(defun split (x str)
  (let ((pos (search x str))
        (size (length x)))
    (if pos
        (cons (subseq str 0 pos)
              (split x (subseq str (+ pos size))))
        (list str))))

(defmacro collect-times (time body)
  `(loop repeat ,time collect ,body))

(defun read-times (time)
  (collect-times time (read)))

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

(defmacro awhen (expr &rest then)
  `(aif ,expr (progn ,@then) nil))

(defun comulative (function list &key base)
  (if base
      (comulative function (cons base list))
      (do ((lst (cdr list) (cdr lst))
           (acc (list (car list))))
          ((null lst) (reverse acc))
        (push (funcall function (car acc) (car lst)) acc))))

(defun binary-search (function left right
                      &optional
                        (eps 1)
                        (average-function (lambda (x y) (ash (+ x y) -1))))
  (if (<= (abs (- left right)) eps)
      right
      (let ((mid (funcall average-function left right)))
        (if (funcall function mid)
            (binary-search function left mid eps average-function)
            (binary-search function mid right eps average-function)))))

(defun arithmetic-mean (&rest body)
  (/ (apply #'+ body) (length body)))

(defvar +MOD+ (+ (expt 10 9) 7))

(defun range-0-n (n &optional (step 1))
  (loop for i from 0 below n by step collect i))

(defun range-1-n (n &optional (step 1))
  (loop for i from 1 below n by step collect i))

(defun range-a-b (a b &optional (step 1))
  (loop for i from a below b by step collect i))

(defun map-0-n (function n &optional (step 1))
  (mapcar function (range-0-n n step)))

(defun map-1-n (function n &optional (step 1))
  (mapcar function (range-1-n n step)))

(defun map-a-b (function a b &optional (step 1))
  (mapcar function (range-a-b a b step)))

(defun read-string (&optional (stream *standard-input*))
  (labels ((is-empty (x)
             (or (char= x #\space) (char= x #\newline))))
    (loop for char = (read-char stream)
          with result
          when (is-empty char)
            do (return (concatenate 'string (nreverse result)))
          do (push char result))))

(defun merge-sort (lst &optional (compare #'<))
  (let ((turn 0))
    (labels ((merge-list (a b a-length b-length)
               (cond ((zerop a-length) b)
                     ((zerop b-length) a)
                     ((funcall compare (car b) (car a))
                      (incf turn a-length)
                      (cons (car b)
                            (merge-list a (cdr b) a-length (1- b-length))))
                     (t
                      (cons (car a)
                            (merge-list (cdr a) b (1- a-length) b-length)))))
             (f (lst length)
               (if (= length 1)
                   lst
                   (let ((mid (ash length -1)))
                     (merge-list (f (subseq lst 0 mid) mid)
                                 (f (subseq lst mid) (- length mid))
                                 mid
                                 (- length mid))))))
      (values (f lst (length lst)) turn))))

(defun group (lst &optional (test #'eql) (key nil))
  (let ((table (make-hash-table :test test)))
    (mapc (lambda (x)
            (push x (gethash (if key (funcall key x) x) table)))
          lst)
    (loop for value being each hash-value in table
          collect value)))

(defun nearby (&rest args)
  (let ((current (subseq args 0 (ash (length args) -1)))
        (validator (subseq args (ash (length args) -1)))
        (res nil))
    (labels ((check (pos)
               (every (lambda (x y) (and (<= 0 x) (< x y)))
                      pos validator))
             (f (lst)
               (unless lst (return-from f))
               (incf (car lst))
               (when (check lst) (push (copy-list current) res))
               (decf (car lst) 2)
               (when (check lst) (push (copy-list current) res))
               (incf (car lst))
               (f (cdr lst))))
      (f current)
      res)))

(defun main (h w map)
  (every
   (lambda (y)
     (every
      (lambda (x)
        (or (char= (aref map y x) #\.)
            (and (char= (aref map y x))
                 (some (lambda (pos)
                         (char= (aref map (nth 0 pos) (nth 1 pos)) #\#))
                       (nearby y x h w)))))
      (range-0-n w)))
   (range-0-n h)))

(let ((h (read))
      (w (read)))
  (format t "~a~%" (if (main
                        h w
                        (make-array
                         (list h w)
                         :initial-contents (collect-times h (read-string))))
                       "Yes"
                       "No")))

Score: 300 points

Problem Statement

We have a canvas divided into a grid with H rows and W columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j).

Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square (i, j) black when s_{i, j}= #, and to make Square (i, j) white when s_{i, j}= ..

However, since he is not a good painter, he can only choose two squares that are horizontally or vertically adjacent and paint those squares black, for some number of times (possibly zero). He may choose squares that are already painted black, in which case the color of those squares remain black.

Determine if square1001 can achieve his objective.

Constraints

H is an integer between 1 and 50 (inclusive).

W is an integer between 1 and 50 (inclusive).

For every (i, j) (1 \leq i \leq H, 1 \leq j \leq W), s_{i, j} is # or ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1} s_{1, 2} s_{1, 3} ... s_{1, W}
s_{2, 1} s_{2, 2} s_{2, 3} ... s_{2, W}
: :
s_{H, 1} s_{H, 2} s_{H, 3} ... s_{H, W}

Output

If square1001 can achieve his objective, print Yes; if he cannot, print No.

Sample Input 1

3 3
.#.
###
.#.

Sample Output 1

Yes

One possible way to achieve the objective is shown in the figure below. Here, the squares being painted are marked by stars.

Sample Input 2

5 5
#.#.#
.#.#.
#.#.#
.#.#.
#.#.#

Sample Output 2

No

square1001 cannot achieve his objective here.

Sample Input 3

11 11
...#####...
.##.....##.
#..##.##..#
#..##.##..#
#.........#
#...###...#
.#########.
.#.#.#.#.#.
##.#.#.#.##
..##.#.##..
.##..#..##.

Sample Output 3

Yes


Score: 400 points

Problem Statement

Print a sequence a_1, a_2, ..., a_N whose length is N that satisfies the following conditions:

a_i (1 \leq i \leq N) is a prime number at most 55 555.

The values of a_1, a_2, ..., a_N are all different.

In every choice of five different integers from a_1, a_2, ..., a_N, the sum of those integers is a composite number.

If there are multiple such sequences, printing any of them is accepted.

Notes

An integer N not less than 2 is called a prime number if it cannot be divided evenly by any integers except 1 and N, and called a composite number otherwise.

Constraints

N is an integer between 5 and 55 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print N numbers a_1, a_2, a_3, ..., a_N in a line, with spaces in between.

Sample Input 1

5

Sample Output 1

3 5 7 11 31

Let us see if this output actually satisfies the conditions.

First, 3, 5, 7, 11 and 31 are all different, and all of them are prime numbers.

The only way to choose five among them is to choose all of them, whose sum is a_1+a_2+a_3+a_4+a_5=57, which is a composite number.

There are also other possible outputs, such as 2 3 5 7 13, 11 13 17 19 31 and 7 11 5 31 3.

Sample Input 2

6

Sample Output 2

2 3 5 7 11 13

2, 3, 5, 7, 11, 13 are all different prime numbers.

2+3+5+7+11=28 is a composite number.

2+3+5+7+13=30 is a composite number.

2+3+5+11+13=34 is a composite number.

2+3+7+11+13=36 is a composite number.

2+5+7+11+13=38 is a composite number.

3+5+7+11+13=39 is a composite number.

Thus, the sequence 2 3 5 7 11 13 satisfies the conditions.

Sample Input 3

8

Sample Output 3

2 5 7 13 19 37 67 79


(let* ((n (read))
      (m (read))
      (lst (sort (loop :for k :from 1 :upto n collect(read)) #'<)))
  (format t "~A" (+ n (floor (- m (reduce #'+ lst)) (first lst)))))

Score : 200 points

Problem Statement

Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts.

Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition:

For each of the N kinds of doughnuts, make at least one doughnut of that kind.

At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Also, under the constraints of this problem, it is always possible to obey the condition.

Constraints

2 ≤ N ≤ 100

1 ≤ m_i ≤ 1000

m_1 + m_2 + ... + m_N ≤ X ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
m_1
m_2
:
m_N

Output

Print the maximum number of doughnuts that can be made under the condition.

Sample Input 1

3 1000
120
100
140

Sample Output 1

9

She has 1000 grams of Moto and can make three kinds of doughnuts. If she makes one doughnut for each of the three kinds, she consumes 120 + 100 + 140 = 360 grams of Moto. From the 640 grams of Moto that remains here, she can make additional six Doughnuts 2. This is how she can made a total of nine doughnuts, which is the maximum.

Sample Input 2

4 360
90
90
90
90

Sample Output 2

4

Making one doughnut for each of the four kinds consumes all of her Moto.

Sample Input 3

5 3000
150
130
150
130
110

Sample Output 3

26


(defun solver ()
  (let* ((n (read)) (x (read))
         (mi (make-array n :fill-pointer 0))
         m-temp (m-min 1001)
         (answer n))
    (loop repeat n do
          (vector-push (read) mi))
    (loop for i from 0 below n do
          (setf m-temp (aref mi i))
          (decf x m-temp)
          (when (< m-temp m-min) (setf m-min m-temp)))
    (incf answer (floor x m-min))
    (format t "~a~%" answer)))

(solver)


Score : 300 points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy 200000 AB-pizzas and rearrange them into 100000 A-pizzas and 100000 B-pizzas. We will have 10000 more A-pizzas than necessary, but that is fine.


;; -*- 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))))))))

(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 solve (xs vs c)
  (declare #.OPT
           ((simple-array uint62 (*)) xs)
           ((simple-array uint32 (*)) vs))
  (let* ((n (length xs))
         (cumuls-clock (make-array n :element-type 'fixnum))
         (cumuls-anticlock (make-array n :element-type 'fixnum))
         (dp-clock (make-array n :element-type 'fixnum))
         (dp-anticlock (make-array n :element-type 'fixnum)))
    (setf (aref cumuls-clock 0) (- (aref vs 0) (aref xs 0)))
    (loop for i from 1 below n
          do (setf (aref cumuls-clock i)
                   (+ (aref cumuls-clock (- i 1))
                      (aref vs i)
                      (- (aref xs (- i 1)) (aref xs i)))))
    (setf (aref cumuls-anticlock (- n 1)) (- (aref vs (- n 1))
                                             (* 2 (- c (aref xs (- n 1))))))
    (loop for i from (- n 2) downto 0
          do (setf (aref cumuls-anticlock i)
                   (+ (aref cumuls-anticlock (+ i 1))
                      (aref vs i)
                      (- (* 2 (- (aref xs (+ i 1)) (aref xs i)))))))
    (setf (aref dp-clock 0) (aref cumuls-clock 0))
    (loop for i from 1 below n
          do (setf (aref dp-clock i)
                   (max (aref dp-clock (- i 1)) (aref cumuls-clock i))))
    (setf (aref dp-anticlock (- n 1)) (aref cumuls-anticlock (- n 1)))
    (loop for i from (- n 2) downto 0
          do (setf (aref dp-anticlock i)
                   (max (aref dp-anticlock (+ i 1)) (aref cumuls-anticlock i))))
    (max (reduce #'max cumuls-clock)
         (loop for i from 0 below (- n 1)
               maximize (+ (aref dp-clock i) (aref dp-anticlock (+ i 1)))))))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (c (read))
         (xs (make-array n :element-type 'uint62))
         (rev-xs (make-array n :element-type 'uint62))
         (vs (make-array n :element-type 'uint32))
         (rev-vs (make-array n :element-type 'uint32)))
    (declare (uint62 c) (uint32 n))
    (dotimes (i n)
      (let ((x (read-fixnum))
            (v (read-fixnum)))
        (setf (aref xs i) x)
        (setf (aref rev-xs (- n i 1)) (- c x))
        (setf (aref vs i) v)
        (setf (aref rev-vs (- n i 1)) v)))
    (println (max 0 (solve xs vs c) (solve rev-xs rev-vs c)))))

#-swank(main)

Score : 500 points

Problem Statement

"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.

Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.

Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.

Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

1 ≤ x_1 < x_2 < ... < x_N < C

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

300 points will be awarded for passing the test set satisfying N ≤ 100.

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 8 kilocalories, thus he can take in 192 kilocalories on balance, which is the largest possible value.

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

Even though the only sushi is so far that it does not fit into a 32-bit integer, its nutritive value is low, thus he should immediately leave without doing anything.

Sample Input 4

15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000

Sample Output 4

6500000000

All these sample inputs above are included in the test set for the partial score.


;; -*- 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 define-binary-heap (name &key (order '#'>) (element-type 'fixnum))
  (check-type name symbol)
  (let* ((string-name (string name))
         (fname-push (intern (format nil "~A-PUSH" string-name)))
         (fname-pop (intern (format nil "~A-POP" string-name)))
         (fname-reinitialize (intern (format nil "~A-REINITIALIZE" string-name)))
         (fname-empty-p (intern (format nil "~A-EMPTY-P" string-name)))
         (fname-peak (intern (format nil "~A-PEAK" string-name)))
         (fname-make (intern (format nil "MAKE-~A" string-name)))
         (acc-position (intern (format nil "~A-POSITION" string-name)))
         (acc-data (intern (format nil "~A-DATA" string-name))))
    `(progn
       (defstruct (,name
                   (:constructor ,fname-make
                       (size
                        &aux (data ,(if (eql element-type '*)
                                        `(make-array (1+ size))
                                        `(make-array (1+ size) :element-type ',element-type))))))
         (data #() :type (simple-array ,element-type (*)) :read-only t)
         (position 1 :type (integer 1 #.most-positive-fixnum)))

       (declaim (inline ,fname-push))
       (defun ,fname-push (obj heap)
         (symbol-macrolet ((position (,acc-position heap)))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((update (pos)
                        (unless (= pos 1)
                          (let ((parent-pos (ash pos -1)))
                            (when (funcall ,order (aref data pos) (aref data parent-pos))
                              (rotatef (aref data pos) (aref data parent-pos))
                              (update parent-pos))))))
               (setf (aref data position) obj)
               (update position)
               (incf position)
               heap))))

       (declaim (inline ,fname-pop))
       (defun ,fname-pop (heap &optional (error t) null-value)
         (symbol-macrolet ((position (,acc-position heap)))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((update (pos)
                        (declare ((integer 1 #.most-positive-fixnum) pos))
                        (let* ((child-pos1 (+ pos pos))
                               (child-pos2 (1+ child-pos1)))
                          (when (<= child-pos1 position)
                            (if (<= child-pos2 position)
                                (if (funcall ,order (aref data child-pos1) (aref data child-pos2))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                      (rotatef (aref data pos) (aref data child-pos1))
                                      (update child-pos1))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos2))
                                      (rotatef (aref data pos) (aref data child-pos2))
                                      (update child-pos2)))
                                (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                  (rotatef (aref data pos) (aref data child-pos1))))))))
               (if (= position 1)
                   (if error
                       (error "No element in heap.")
                       null-value)
                   (prog1 (aref data 1)
                     (decf position)
                     (setf (aref data 1) (aref data position))
                     (update 1)))))))

       (declaim (inline ,fname-reinitialize))
       (defun ,fname-reinitialize (heap)
         (setf (,acc-position heap) 1)
         heap)

       (declaim (inline ,fname-empty-p))
       (defun ,fname-empty-p (heap)
         (= 1 (,acc-position heap)))

       (declaim (inline ,fname-peak))
       (defun ,fname-peak (heap &optional (error t) null-value)
         (if (= 1 (,acc-position heap))
             (if error
                 (error "No element in heap")
                 null-value)
             (aref (,acc-data heap) 1))))))

(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

(define-binary-heap heap
  :order (lambda (x y) (> (car x) (car y)))
  ;; (cal . index)
  :element-type (cons fixnum fixnum))

(defun solve (xs vs c)
  (declare #.OPT
           ((simple-array uint62 (*)) xs)
           ((simple-array uint32 (*)) vs))
  (let* ((n (length xs))
         (cumuls-clock (make-array n :element-type 'fixnum))
         (cumuls-anticlock (make-array n :element-type 'fixnum)))
    (setf (aref cumuls-clock 0) (- (aref vs 0) (aref xs 0)))
    (loop for i from 1 below n
          do (setf (aref cumuls-clock i)
                   (+ (aref cumuls-clock (- i 1))
                      (aref vs i)
                      (- (aref xs (- i 1)) (aref xs i)))))
    (setf (aref cumuls-anticlock (- n 1)) (- (aref vs (- n 1))
                                             (* 2 (- c (aref xs (- n 1))))))
    (loop for i from (- n 2) downto 0
          do (setf (aref cumuls-anticlock i)
                   (+ (aref cumuls-anticlock (+ i 1))
                      (aref vs i)
                      (- (* 2 (- (aref xs (+ i 1)) (aref xs i)))))))
    (let ((res (reduce #'max cumuls-clock))
          (pqueue (make-heap n))
          (pos 0))
      (declare (fixnum res))
      (dotimes (i n)
        (heap-push (cons (aref cumuls-anticlock i) i) pqueue))
      (loop (when (heap-empty-p pqueue)
              (return res))
            (destructuring-bind (rev-cal . rev-pos) (heap-peak pqueue)
              (declare (fixnum rev-cal rev-pos))
              (if (<= rev-pos pos)
                  (heap-pop pqueue)
                  (progn
                    (setf res (max res (+ (aref cumuls-clock pos) rev-cal)))
                    (incf pos))))))))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (c (read))
         (xs (make-array n :element-type 'uint62))
         (rev-xs (make-array n :element-type 'uint62))
         (vs (make-array n :element-type 'uint32))
         (rev-vs (make-array n :element-type 'uint32)))
    (declare (uint62 c) (uint32 n))
    (dotimes (i n)
      (let ((x (read-fixnum))
            (v (read-fixnum)))
        (setf (aref xs i) x)
        (setf (aref rev-xs (- n i 1)) (- c x))
        (setf (aref vs i) v)
        (setf (aref rev-vs (- n i 1)) v)))
    (println (max 0 (solve xs vs c) (solve rev-xs rev-vs c)))))

#-swank(main)


(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 (inline split-ints-into-vector))
(defun split-ints-into-vector (string dest-vector &key (offset 0) (key #'identity))
  (declare (string string)
           (function key)
           ((array * (*)) dest-vector)
           ((integer 0 #.most-positive-fixnum) offset))
  (loop with position = 0
        for idx from offset below (length dest-vector)
        do (setf (values (aref dest-vector idx) position)
                 (parse-integer string :start position :junk-allowed t))
           (setf (aref dest-vector idx) (funcall key (aref dest-vector idx)))
        finally (return dest-vector)))

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

(defmacro println (obj &optional (stream '*standard-output*))
  `(let ((*read-default-float-format* 'double-float))
     (prog1 (princ ,obj ,stream) (terpri ,stream))))

(defconstant +mod+ 1000000007)

;; Hauptteil
(declaim ((simple-array double-float (*)) *bernoulli*))
(defparameter *bernoulli*
  #.(coerce
     (mapcar (lambda (x) (float x 1d0))
             '(1 -1/2 1/6 0 -1/30 0 1/42 0 -1/30 0 5/66 0 -691/2730 0 7/6 0 -3617/510 0 43867/798 0 -174611/330 0 854513/138 0 -236364091/2730 0 8553103/6 0 -23749461029/870 0 8615841276005/14332))
     '(simple-array double-float (*))))

(declaim (ftype (function * (values double-float &optional)) log-factorial))
(defun log-factorial (n &optional (terms 2))
  (declare ((integer 0) n)
           ((unsigned-byte 8) terms))
  (let ((n (float n 1d0)))
    (+ #.(log (sqrt (* 2 pi)))
       (* (+ n 0.5d0) (log n))
       (- n)
       (loop for i2 from 2 to (* terms 2) by 2
             sum (/ (aref *bernoulli* i2)
                    (* i2 (- i2 1) (expt n (- i2 1))))
             of-type double-float))))

(defun log-binomial (n k &optional (terms 2))
  (declare ((integer 0) n k))
  (assert (>= n k))
  (if (zerop k)
      1d0
      (- (log-factorial n terms)
         (log-factorial (- n k) terms)
         (log-factorial k terms))))

(defun bisect-nearest (value vector &key (start 0) end)
  (if (<= value (aref vector start))
      (aref vector start)
      (labels ((%bisect (lo hi)
                 (if (<= (- hi lo) 1)
                     (if (or (= (length vector) hi)
                             (>= (- (aref vector hi) value)
                                (- value (aref vector lo))))
                         (aref vector lo)
                         (aref vector hi))
                     (let ((mid (ash (+ hi lo) -1)))
                       (if (<= (aref vector mid) value)
                           (%bisect mid hi)
                           (%bisect lo mid))))))
        (%bisect start (or end (length vector))))))

(defun main ()
  (let* ((n (read))
         (as (make-array n :element-type 'uint31)))
    (split-ints-into-vector (read-line) as)
    (setf as (sort as #'<))
    (loop for i from 1 below n
          with max = -1
          with a1 = -1
          with a2 = -1
          do (let* ((a/2 (bisect-nearest (* 0.5d0 (aref as i)) as :end i))
                    (b (log-binomial (aref as i) a/2)))
               (when (< max b)
                 (setf max b
                       a1 (aref as i)
                       a2 a/2)))
          finally (format t "~A ~A~%" a1 a2))))

#-swank(main)

Score : 400 points

Problem Statement

Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order.
From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized.
If there are multiple pairs that maximize the value, any of them is accepted.

Constraints

2 \leq n \leq 10^5

0 \leq a_i \leq 10^9

a_1,a_2,...,a_n are pairwise distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print a_i and a_j that you selected, with a space in between.

Sample Input 1

5
6 9 4 2 11

Sample Output 1

11 6

\rm{comb}(a_i,a_j) for each possible selection is as follows:

\rm{comb}(4,2)=6

\rm{comb}(6,2)=15

\rm{comb}(6,4)=15

\rm{comb}(9,2)=36

\rm{comb}(9,4)=126

\rm{comb}(9,6)=84

\rm{comb}(11,2)=55

\rm{comb}(11,4)=330

\rm{comb}(11,6)=462

\rm{comb}(11,9)=55

Thus, we should print 11 and 6.

Sample Input 2

2
100 0

Sample Output 2

100 0


(let ((lst (concatenate 'list (read-line))))
  (if (and (find #\a lst :test #'char=) (find #\b lst :test #'char=) (find #\c lst :test #'char=))
      (format t "Yes~%")
      (format t "No~%")))

Score : 100 points

Problem Statement

You are given a string S of length 3 consisting of a, b and c. Determine if S can be obtained by permuting abc.

Constraints

|S|=3

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

If S can be obtained by permuting abc, print Yes; otherwise, print No.

Sample Input 1

bac

Sample Output 1

Yes

Swapping the first and second characters in bac results in abc.

Sample Input 2

bab

Sample Output 2

No

Sample Input 3

abc

Sample Output 3

Yes

Sample Input 4

aaa

Sample Output 4

No


;; -*- 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 (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (declare #.OPT)
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (sb-impl::ansi-stream-read-byte in nil #.(char-code #\Nul) nil))))
    (let* ((minus nil)
           (result (loop (let ((byte (%read-byte)))
                           (cond ((<= 48 byte 57)
                                  (return (- byte 48)))
                                 ((zerop byte) ; #\Nul
                                  (error "Read EOF or #\Nul."))
                                 ((= byte #.(char-code #\-))
                                  (setf minus t)))))))
      (declare ((integer 0 #.most-positive-fixnum) result))
      (loop
        (let* ((byte (%read-byte)))
          (if (<= 48 byte 57)
              (setq result (+ (- byte 48) (* 10 (the (integer 0 #.(floor most-positive-fixnum 10)) result))))
              (return (if minus (- result) result))))))))

(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)))
    (declare (uint32 q))
    (dotimes (_ q)
      (let ((a (read-fixnum))
            (b (read-fixnum)))
        (declare (uint31 a b))
        (when (> a b) (rotatef a b))
        (let ((res (* 2 (- a 1))))
          (unless (= a b)
            (sb-int:named-let bisect ((ok 0) (ng (- b a)))
              (declare (uint31 ok ng))
              (if (<= (- ng ok) 1)
                  (incf res ok)
                  (let* ((mid (ash (+ ok ng) -1))
                         (x/2 (max 1 (floor mid 2))))
                    (declare (uint31 mid x/2))
                    (if (< (* (+ a x/2) (+ a mid (- x/2))) (* a b))
                        (bisect mid ng)
                        (bisect ok mid))))))
          (println res))))))

#-swank (main)

Score : 700 points

Problem Statement

10^{10^{10}} participants, including Takahashi, competed in two programming contests.
In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th.

The score of a participant is the product of his/her ranks in the two contests.

Process the following Q queries:

In the i-th query, you are given two positive integers A_i and B_i. Assuming that Takahashi was ranked A_i-th in the first contest and B_i-th in the second contest, find the maximum possible number of participants whose scores are smaller than Takahashi's.

Constraints

1 \leq Q \leq 100

1\leq A_i,B_i\leq 10^9(1\leq i\leq Q)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

Q
A_1 B_1
:
A_Q B_Q

Output

For each query, print the maximum possible number of participants whose scores are smaller than Takahashi's.

Sample Input 1

8
1 4
10 5
3 3
4 11
8 9
22 40
8 36
314159265 358979323

Sample Output 1

1
12
4
11
14
57
31
671644785

Let us denote a participant who was ranked x-th in the first contest and y-th in the second contest as (x,y).

In the first query, (2,1) is a possible candidate of a participant whose score is smaller than Takahashi's. There are never two or more participants whose scores are smaller than Takahashi's, so we should print 1.


(defun solve (a b c)
  (let* ((maxi (max a b c))
         (da (floor (/ (- maxi a) 2)))
         (db (floor (/ (- maxi b) 2)))
         (dc (floor (/ (- maxi c) 2))))
    (setq a (+ a (* da 2)))
    (setq b (+ b (* db 2)))
    (setq c (+ c (* dc 2)))
    (+ (case (- (* 3 maxi) a b c)
         (0 0)
         (1 2)
         (2 1))
       da db dc)))

(princ (solve (read) (read) (read)))

Score : 300 points

Problem Statement

You are given three integers A, B and C. Find the minimum number of operations required to make A, B and C all equal by repeatedly performing the following two kinds of operations in any order:

Choose two among A, B and C, then increase both by 1.

Choose one among A, B and C, then increase it by 2.

It can be proved that we can always make A, B and C all equal by repeatedly performing these operations.

Constraints

0 \leq A,B,C \leq 50

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the minimum number of operations required to make A, B and C all equal.

Sample Input 1

2 5 4

Sample Output 1

2

We can make A, B and C all equal by the following operations:

Increase A and C by 1. Now, A, B, C are 3, 5, 5, respectively.

Increase A by 2. Now, A, B, C are 5, 5, 5, respectively.

Sample Input 2

2 6 3

Sample Output 2

5

Sample Input 3

31 41 5

Sample Output 3

23


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           ;; enclose the form with VALUES to avoid being captured by LOOP macro
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

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

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  "NOTE: cannot read -2^62"
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (sb-impl::ansi-stream-read-byte in nil #.(char-code #\Nul) nil))))
    (let* ((minus nil)
           (result (loop (let ((byte (%read-byte)))
                           (cond ((<= 48 byte 57)
                                  (return (- byte 48)))
                                 ((zerop byte) ; #\Nul
                                  (error "Read EOF or #\Nul."))
                                 ((= byte #.(char-code #\-))
                                  (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* ((n (read))
         (as (make-array n :element-type 'uint32))
         (bs (make-array n :element-type 'uint32)))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)
            (aref bs i) (read-fixnum)))
    (when (every #'= as bs)
      (println 0)
      (return-from main))
    (let ((min #xffffffff))
      (loop for a across as
            for b across bs
            when (> a b)
            do (minf min b))
      (println (- (reduce #'+ as) min)))))

#-swank (main)

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

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

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    ;; (run-program "C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe" '("get-clipboard") :output out)
    (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)))

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
1 2
3 2
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
8 3
0 1
4 8
"
    "9
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "1
1 1
"
    "0
")))

Score : 700 points

Problem Statement

You are given sequences A and B consisting of non-negative integers.
The lengths of both A and B are N, and the sums of the elements in A and B are equal.
The i-th element in A is A_i, and the i-th element in B is B_i.

Tozan and Gezan repeats the following sequence of operations:

If A and B are equal sequences, terminate the process.

Otherwise, first Tozan chooses a positive element in A and decrease it by 1.

Then, Gezan chooses a positive element in B and decrease it by 1.

Then, give one candy to Takahashi, their pet.

Tozan wants the number of candies given to Takahashi until the process is terminated to be as large as possible, while Gezan wants it to be as small as possible.
Find the number of candies given to Takahashi when both of them perform the operations optimally.

Constraints

1 \leq N \leq 2 × 10^5

0 \leq A_i,B_i \leq 10^9(1\leq i\leq N)

The sums of the elements in A and B are equal.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the number of candies given to Takahashi when both Tozan and Gezan perform the operations optimally.

Sample Input 1

2
1 2
3 2

Sample Output 1

2

When both Tozan and Gezan perform the operations optimally, the process will proceed as follows:

Tozan decreases A_1 by 1.

Gezan decreases B_1 by 1.

One candy is given to Takahashi.

Tozan decreases A_2 by 1.

Gezan decreases B_1 by 1.

One candy is given to Takahashi.

As A and B are equal, the process is terminated.

Sample Input 2

3
8 3
0 1
4 8

Sample Output 2

9

Sample Input 3

1
1 1

Sample Output 3

0


;; -*- 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
(defmacro with-buffered-stdout (&body body)
  "Buffers all outputs to *STANDARD-OUTPUT* in BODY and flushes them to
*STANDARD-OUTPUT* after BODY has been done (without error). Note that only
BASE-CHAR is allowed."
  (let ((out (gensym)))
    `(let ((,out (make-string-output-stream :element-type 'base-char)))
       (let ((*standard-output* ,out))
         ,@body)
       (write-string (get-output-stream-string ,out)))))

(declaim (ftype (function * (values simple-bit-vector &optional)) make-prime-table))
(defun make-prime-table (sup)
  "Returns a simple-bit-vector of length SUP, whose (0-based) i-th bit is 1 if i
is prime and 0 otherwise.

Example: (make-prime-table 10) => #*0011010100"
  (declare (optimize (speed 3) (safety 0)))
  (check-type sup (integer 2 (#.array-total-size-limit)))
  (let ((table (make-array sup :element-type 'bit :initial-element 0))
        (sup/64 (ceiling sup 64)))
    ;; special treatment for p = 2
    (dotimes (i sup/64)
      (setf (sb-kernel:%vector-raw-bits table i) #xAAAAAAAAAAAAAAAA))
    (setf (sbit table 1) 0
          (sbit table 2) 1)
    ;; p >= 3
    (loop for p from 3 to (+ 1 (isqrt (- sup 1))) by 2
          when (= 1 (sbit table p))
          do (loop for composite from (* p p) below sup by p
                   do (setf (sbit table composite) 0)))
    table))

;; FIXME: Currently the element type of the resultant vector is (UNSIGNED-BYTE 62).
(defun make-prime-sequence (sup)
  "Returns the ascending sequence of primes smaller than SUP."
  (declare (optimize (speed 3) (safety 0)))
  (check-type sup (integer 2 (#.array-total-size-limit)))
  (let ((table (make-prime-table sup)))
    (let* ((length (count 1 table))
           (result (make-array length :element-type '(integer 0 #.most-positive-fixnum)))
           (index 0))
      (declare ((integer 0 #.most-positive-fixnum) length))
      (loop for x below sup
            when (= 1 (sbit table x))
            do (setf (aref result index) x)
               (incf index))
      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

(defparameter *prime-seq* (make-prime-sequence 30001))

(defparameter *goldbach-table*
  (make-array 20001 :element-type '(cons uint32 uint32)))
(loop for x across *prime-seq*
      do (loop for y across *prime-seq*
               do (when (and (/= x y)
                             (<= (+ x y) 20000))
                    (setf (aref *goldbach-table* (+ x y))
                          (cons x y)))))
(defun main ()
  (let* ((n (read)))
    (cond ((= n 3) (write-line "2 5 63"))
          ((= n 4) (write-line "2 5 20 63"))
          ((= n 6) (write-line "2 5 20 63 12600"))
          (t (let ((pair (if (oddp n)
                             (cons 2 (- n 2))
                             (aref *goldbach-table* n))))
               (with-buffered-stdout
                 (dotimes (i (car pair))
                   (format t "~D " (cdr pair)))
                 (dotimes (i (cdr pair))
                   (format t "~D " (car pair)))
                 (terpri)))))))

#-swank (main)

Score : 600 points

Problem Statement

Nagase is a top student in high school. One day, she's analyzing some properties of special sets of positive integers.

She thinks that a set S = \{a_{1}, a_{2}, ..., a_{N}\} of distinct positive integers is called special if for all 1 \leq i \leq N, the gcd (greatest common divisor) of a_{i} and the sum of the remaining elements of S is not 1.

Nagase wants to find a special set of size N. However, this task is too easy, so she decided to ramp up the difficulty. Nagase challenges you to find a special set of size N such that the gcd of all elements are 1 and the elements of the set does not exceed 30000.

Constraints

3 \leq N \leq 20000

Input

Input is given from Standard Input in the following format:

N

Output

Output N space-separated integers, denoting the elements of the set S. S must satisfy the following conditions :

The elements must be distinct positive integers not exceeding 30000.

The gcd of all elements of S is 1, i.e. there does not exist an integer d > 1 that divides all elements of S.

S is a special set.

If there are multiple solutions, you may output any of them. The elements of S may be printed in any order. It is guaranteed that at least one solution exist under the given contraints.

Sample Input 1

3

Sample Output 1

2 5 63

\{2, 5, 63\} is special because gcd(2, 5 + 63) = 2, gcd(5, 2 + 63) = 5, gcd(63, 2 + 5) = 7. Also, gcd(2, 5, 63) = 1. Thus, this set satisfies all the criteria.

Note that \{2, 4, 6\} is not a valid solution because gcd(2, 4, 6) = 2 > 1.

Sample Input 2

4

Sample Output 2

2 5 20 63

\{2, 5, 20, 63\} is special because gcd(2, 5 + 20 + 63) = 2, gcd(5, 2 + 20 + 63) = 5, gcd(20, 2 + 5 + 63) = 10, gcd(63, 2 + 5 + 20) = 9. Also, gcd(2, 5, 20, 63) = 1. Thus, this set satisfies all the criteria.


(format t "~A~%" (+ (min (read) (read)) (min (read) (read))))

Score : 100 points

Problem Statement

You planned a trip using trains and buses.
The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket.
Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.

Find the minimum total fare when the optimal choices are made for trains and buses.

Constraints

1 \leq A \leq 1 000

1 \leq B \leq 1 000

1 \leq C \leq 1 000

1 \leq D \leq 1 000

All input values are integers.

Input

Input is given from Standard Input in the following format:

A
B
C
D

Output

Print the minimum total fare.

Sample Input 1

600
300
220
420

Sample Output 1

520

The train fare will be 600 yen if you buy ordinary tickets, and 300 yen if you buy an unlimited ticket.
Thus, the optimal choice for trains is to buy an unlimited ticket for 300 yen.
On the other hand, the optimal choice for buses is to buy ordinary tickets for 220 yen.

Therefore, the minimum total fare is 300 + 220 = 520 yen.

Sample Input 2

555
555
400
200

Sample Output 2

755

Sample Input 3

549
817
715
603

Sample Output 3

1152


(let ((n (read))
      (d (read))
      (ans (read)))
  (loop repeat n do
        (incf ans (1+ (floor (/ (1- d) (read))))))
  (princ ans))

Score : 200 points

Problem Statement

Some number of chocolate pieces were prepared for a training camp.
The camp had N participants and lasted for D days.
The i-th participant (1 \leq i \leq N) ate one chocolate piece on each of the following days in the camp: the 1-st day, the (A_i + 1)-th day, the (2A_i + 1)-th day, and so on.
As a result, there were X chocolate pieces remaining at the end of the camp. During the camp, nobody except the participants ate chocolate pieces.

Find the number of chocolate pieces prepared at the beginning of the camp.

Constraints

1 \leq N \leq 100

1 \leq D \leq 100

1 \leq X \leq 100

1 \leq A_i \leq 100 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
D X
A_1
A_2
:
A_N

Output

Find the number of chocolate pieces prepared at the beginning of the camp.

Sample Input 1

3
7 1
2
5
10

Sample Output 1

8

The camp has 3 participants and lasts for 7 days.
Each participant eats chocolate pieces as follows:

The first participant eats one chocolate piece on Day 1, 3, 5 and 7, for a total of four.

The second participant eats one chocolate piece on Day 1 and 6, for a total of two.

The third participant eats one chocolate piece only on Day 1, for a total of one.

Since the number of pieces remaining at the end of the camp is one, the number of pieces prepared at the beginning of the camp is 1 + 4 + 2 + 1 = 8.

Sample Input 2

2
8 20
1
10

Sample Output 2

29

Sample Input 3

5
30 44
26
18
81
18
6

Sample Output 3

56


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

;; 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 print-board (b w)
  (labels ((write-point (x)
             (if (zerop x) (write-char #\.) (write-char #\#))))
    (dotimes (i 100)
      (dotimes (j 50)
        (write-point (aref b i j)))
      (dotimes (j 50)
        (write-point (aref w i j)))
      (terpri))))

(defun main ()
  (let* ((a (- (read) 1))
         (b (- (read) 1))
         (black-board (make-array '(100 50) :element-type 'bit :initial-element 1))
         (white-board (make-array '(100 50) :element-type 'bit :initial-element 0)))
    (block white-dot
      (loop for i from 0 below 100 by 2
            do (loop for j from 0 below 49 by 2
                     do (when (zerop a)
                          (return-from white-dot))
                        (setf (aref black-board i j) 0)
                        (decf a))))
    (block black-dot
      (loop for i from 0 below 100 by 2
            do (loop for j from 1 below 50 by 2
                     do (when (zerop b)
                          (return-from black-dot))
                        (setf (aref white-board i j) 1)
                        (decf b))))
    (format t "100 100~%")
    (print-board black-board white-board)))

#-swank(main)

Score : 500 points

Problem Statement

You are given two integers A and B.

Print a grid where each square is painted white or black that satisfies the following conditions, in the format specified in Output section:

Let the size of the grid be h \times w (h vertical, w horizontal). Both h and w are at most 100.

The set of the squares painted white is divided into exactly A connected components.

The set of the squares painted black is divided into exactly B connected components.

It can be proved that there always exist one or more solutions under the conditions specified in Constraints section.
If there are multiple solutions, any of them may be printed.

Notes

Two squares painted white, c_1 and c_2, are called connected when the square c_2 can be reached from the square c_1 passing only white squares by repeatedly moving up, down, left or right to an adjacent square.

A set of squares painted white, S, forms a connected component when the following conditions are met:

Any two squares in S are connected.

No pair of a square painted white that is not included in S and a square included in S is connected.

A connected component of squares painted black is defined similarly.

Constraints

1 \leq A \leq 500

1 \leq B \leq 500

Input

Input is given from Standard Input in the following format:

A B

Output

Output should be in the following format:

In the first line, print integers h and w representing the size of the grid you constructed, with a space in between.

Then, print h more lines. The i-th (1 \leq i \leq h) of these lines should contain a string s_i as follows:

If the square at the i-th row and j-th column (1 \leq j \leq w) in the grid is painted white, the j-th character in s_i should be ..

If the square at the i-th row and j-th column (1 \leq j \leq w) in the grid is painted black, the j-th character in s_i should be #.

Sample Input 1

2 3

Sample Output 1

3 3
##.
..#
#.#

This output corresponds to the grid below:

Sample Input 2

7 8

Sample Output 2

3 5
#.#.#
.#.#.
#.#.#

Sample Input 3

1 1

Sample Output 3

4 2
..
#.
##
##

Sample Input 4

3 14

Sample Output 4

8 18
..................
..................
....##.......####.
....#.#.....#.....
...#...#....#.....
..#.###.#...#.....
.#.......#..#.....
#.........#..####.