(defun main (ps)
  (- (reduce #'+ ps) (floor (reduce #'max ps) 2)))

(defun repl ()
  (let* ((n (read))
         (ps (loop :repeat n :collect (read))))
    (format t "~a~%" (main ps))))

(repl)

Score : 200 points

Problem Statement

In some other world, today is the day before Christmas Eve.

Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).

He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 items cost their regular prices. What is the total amount he will pay?

Constraints

2 \leq N \leq 10

100 \leq p_i \leq 10000

p_i is an even number.

Input

Input is given from Standard Input in the following format:

N
p_1
p_2
:
p_N

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

The 7980-yen item gets the discount and the total is 4980 + 7980 / 2 + 6980 = 15950 yen.

Note that outputs such as 15950.0 will be judged as Wrong Answer.

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

Only one of the four items gets the discount and the total is 4320 / 2 + 4320 + 4320 + 4320 = 15120 yen.


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

(defun solve(n k h)
    (let ((_h (sort h #'<=))
	  (ans (expt 10 9)))
      (dotimes (i (1+ (- n k)) ans)
	(setf ans (min ans (- (nth (+ i (1- k)) _h)
			      (nth i _h)))))))

(defun main ()
  (let* ((n (read))
	 (k (read))
	 (h (make-list n)))
    (dotimes (i n)
      (setf (nth i h) (read-fixnum)))
    (princ (solve n k h))))

(main)

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

Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.

He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.

More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

Print the minimum possible value of h_{max} - h_{min}.

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

If we decorate the second, fourth and fifth trees, h_{max} = 7, h_{min} = 7 so h_{max} - h_{min} = 0. This is optimal.

There are not too many trees in these sample inputs, but note that there can be at most one hundred thousand trees (we just can't put a sample with a hundred thousand lines here).

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.


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

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

(defconstant +mod+ 1000000007)

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

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

;; BEGIN_INSERTED_CONTENTS
;; BEGIN_USE_PACKAGE
(in-package :cl-user)

;;;
;;; Body
;;;

(defun main ()
  (let* ((x (read)))
    (write-line (if (member x '(3 5 7))
                    "YES"
                    "NO"))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (5am:is
   (equal "YES
"
          (run "5
" nil)))
  (5am:is
   (equal "NO
"
          (run "6
" nil))))

Score : 100 points

Problem Statement

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

1 ≤ X ≤ 9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If Takahashi's growth will be celebrated, print YES; if it will not, print NO.

Sample Input 1

5

Sample Output 1

YES

The growth of a five-year-old child will be celebrated.

Sample Input 2

6

Sample Output 2

NO

See you next year.


(if (find (read-char) "753") (princ "YES") (princ "NO"))


(format t "~a~%" ((lambda (x) (if (= x 5) (= x "YES" "NO")) (read)))


#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))
(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 main (str)
  (loop for i from 0 to (- (length str) 3)
        minimize (abs (- 753 (read-from-string (subseq str i (+ i 3)))))))

(princ (main (read-line)))

Score : 200 points

Problem Statement

There is a string S consisting of digits 1, 2, ..., 9.
Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)

The master's favorite number is 753. The closer to this number, the better.
What is the minimum possible (absolute) difference between X and 753?

Constraints

S is a string of length between 4 and 10 (inclusive).

Each character in S is 1, 2, ..., or 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum possible difference between X and 753.

Sample Input 1

1234567876

Sample Output 1

34

Taking out the seventh to ninth characters results in X = 787, and the difference between this and 753 is 787 - 753 = 34. The difference cannot be made smaller, no matter where X is taken from.

Note that the digits cannot be rearranged. For example, taking out 567 and rearranging it to 765 is not allowed.

We cannot take out three digits that are not consecutive from S, either. For example, taking out the seventh digit 7, the ninth digit 7 and the tenth digit 6 to obtain 776 is not allowed.

Sample Input 2

35753

Sample Output 2

0

If 753 itself can be taken out, the answer is 0.

Sample Input 3

1111111111

Sample Output 3

642

No matter where X is taken from, X = 111, with the difference 753 - 111 = 642.


(defun substAbs (s)
  (abs (- (parse-integer (subseq s 0 3)) 753)))

(defun minSubst (s &optional (mins 10000))
   (if (< 2 (length s))
       (minSubst (subseq s 1 (length s))
                 (min mins (substAbs s)))
       mins))

(format t "~a~%" (minsubst (read-line)))


(defun substAbs (s)
  (abs (- (parse-integer (subseq s 0 3)) 753)))

(defun minSubst (s &optional (mins 10000000))
   (if (< 2 (length s))
      (if (> mins (substAbs s))
          (minSubst (subseq s 1 (length s))
                    (substAbs s))
           mins)
       mins))


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

;; Hauptteil

(defun decompose (n prime-table)
  (map 'vector
       (lambda (p)
         (loop for i from 0
               do (multiple-value-bind (quot rem) (floor n p)
                    (if (zerop rem)
                        (setf n quot)
                        (return i)))))
       prime-table))

(defun count-4-4-2 (table)
  (let ((num2~3 (loop for i across table count (<= 2 i 3)))
        (num4~ (loop for i across table count (<= 4 i))))
    (+ (floor (* num2~3 num4~ (- num4~ 1)) 2)
       (floor (* num4~ (- num4~ 1) (- num4~ 2)) 2))))

(defun count-14-4 (table)
  (let ((num4~13 (loop for i across table count (<= 4 i 13)))
        (num14~ (loop for i across table count (<= 14 i))))
    (+ (* num14~ (- num14~ 1))
       (* num14~ num4~13))))

(defun count-24-2 (table)
  (let ((num2~23 (loop for i across table count (<= 2 i 23)))
        (num24~ (loop for i across table count (<= 24 i))))
    (+ (* num24~ (- num24~ 1))
       (* num24~ num2~23))))

(defun count-74 (table)
  (loop for i across table count (<= 74 i)))

(defun main ()
  (let* ((n (read))
         (prime-table (coerce (loop for x from 2 to n
                                    when (sb-impl::positive-primep x)
                                    collect x)
                              'vector))
         (factor-table (make-array (length prime-table) :element-type 'uint16)))
    (loop for k from 1 to n
          do (map-into factor-table #'+ factor-table (decompose k prime-table)))
    (println (+ (count-4-4-2 factor-table)
                (count-14-4 factor-table)
                (count-24-2 factor-table)
                (count-74 factor-table)))))

#-swank(main)

Score : 400 points

Problem Statement

You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there?

Here, a Shichi-Go number is a positive integer that has exactly 75 divisors.

Note

When a positive integer A divides a positive integer B, A is said to a divisor of B.
For example, 6 has four divisors: 1, 2, 3 and 6.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go numbers that are divisors of N!.

Sample Input 1

9

Sample Output 1

0

There are no Shichi-Go numbers among the divisors of 9! = 1 \times 2 \times ... \times 9 = 362880.

Sample Input 2

10

Sample Output 2

1

There is one Shichi-Go number among the divisors of 10! = 3628800: 32400.

Sample Input 3

100

Sample Output 3

543


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

;; Hauptteil

(defun decompose (n prime-table)
  (map 'vector
       (lambda (p)
         (loop for i from 0
               do (multiple-value-bind (quot rem) (floor n p)
                    (if (zerop rem)
                        (setf n quot)
                        (return i)))))
       prime-table))

(defun count-4-4-2 (table)
  (let ((num2~3 (loop for i across table count (<= 2 i 3)))
        (num4~ (loop for i across table count (<= 4 i))))
    (+ (floor (* num2~3 num4~ (- num4~ 1)) 2)
       (floor (* num4~ (- num4~ 1) (- num4~ 2)) 2))))

(defun count-14-4 (table)
  (let ((num4~13 (loop for i across table count (<= 4 i 13)))
        (num14~ (loop for i across table count (<= 14 i))))
    (+ (* num14~ (- num14~ 1))
       (* num14~ num4~13))))

(defun count-24-2 (table)
  (let ((num2~23 (loop for i across table count (<= 2 i 23)))
        (num24~ (loop for i across table count (<= 24 i))))
    (+ (* num24~ (- num24~ 1))
       (* num24~ num2~23))))

(defun count-74 (table)
  (loop for i across table count (<= 74 i)))

(defun main ()
  (let* ((n (read))
         (prime-table (coerce (loop for x from 2 to n
                                    when (sb-impl::positive-primep x)
                                    collect x)
                              'vector))
         (factor-table (make-array (length prime-table) :element-type 'uint16)))
    (loop for k from 1 to n
          do (map-into factor-table #'+ factor-table (decompose k prime-table)))
    (println (+ (count-4-4-2 factor-table)
                (count-14-4 factor-table)
                (count-24-2 factor-table)
                (count-74 factor-table)))))


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

;; BEGIN_INSERTED_CONTENTS
(declaim (inline read-line-into))
(defun read-line-into (buffer-string &key (in *standard-input*) (term-char #\Space))
  "Receives ASCII inputs and returns multiple values: the string and the end
position.

This function calls READ-BYTE to read characters though it calls READ-CHAR
instead on SLIME because SLIME's IO is not bivalent."
  (declare (inline read-byte)
           #-swank (sb-kernel:ansi-stream in))
  (loop for c of-type base-char =
           #-swank (code-char (read-byte in nil #.(char-code #\Newline)))
           #+swank (read-char in nil #\Newline)
        for idx from 0
        until (char= c #\Newline)
        do (setf (char buffer-string idx) c)
        finally (when (< idx (length buffer-string))
                  (setf (char buffer-string idx) term-char))
                (return (values buffer-string idx))))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (s (let ((s (make-string n :element-type 'base-char)))
              (read-line-into s)))
         (q (read))
         (ks (make-array q :element-type 'uint32))
         (cumul-d (make-array (+ n 1) :element-type 'uint31))
         (cumul-m (make-array (+ n 1) :element-type 'uint31))
         (cumul-c (make-array (+ n 1) :element-type 'uint31))
         (cumul-dm (make-array (+ n 1) :element-type 'uint62))
         (total-dmc 0))
    (declare (uint31 n q)
             (uint62 total-dmc)
             (simple-base-string s))
    (dotimes (i q)
      (setf (aref ks i) (read)))
    (dotimes (i n)
      (setf (aref cumul-d (+ i 1))
            (+ (aref cumul-d i)
               (if (char= #\D (aref s i)) 1 0)))
      (setf (aref cumul-m (+ i 1))
            (+ (aref cumul-m i)
               (if (char= #\M (aref s i)) 1 0)))
      (setf (aref cumul-c (+ i 1))
            (+ (aref cumul-c i)
               (if (char= #\C (aref s i)) 1 0)))
      (setf (aref cumul-dm (+ i 1))
            (if (char= #\M (aref s i))
                (+ (aref cumul-dm i) (aref cumul-d i))
                (aref cumul-dm i))))
    (dotimes (i n)
      (when (char= #\M (aref s i))
        (incf total-dmc (* (aref cumul-d i)
                           (- (aref cumul-c n) (aref cumul-c i))))))
    (labels ((calc (k)
               (let ((res 0))
                 (declare (uint62 res))
                 (dotimes (z n)
                   (when (char= #\C (aref s z))
                     (incf res (aref cumul-dm (max 0 (+ 1 (- z k)))))
                     (incf res (* (aref cumul-d (max 0 (+ 1 (- z k))))
                                  (- (aref cumul-m z)
                                     (aref cumul-m (max 0 (+ 1 (- z k)))))))))
                 res)))
      (sb-int:dovector (k ks)
        (println (- total-dmc (calc k)))))))

#-swank (main)

Score : 600 points

Problem Statement

In Dwango Co., Ltd., there is a content distribution system named 'Dwango Media Cluster', and it is called 'DMC' for short.

The name 'DMC' sounds cool for Niwango-kun, so he starts to define DMC-ness of a string.

Given a string S of length N and an integer k (k \geq 3),
he defines the k-DMC number of S as the number of triples (a, b, c) of integers that satisfy the following conditions:

0 \leq a < b < c \leq N - 1

S[a] = D

S[b] = M

S[c] = C

c-a < k

Here S[a] is the a-th character of the string S. Indexing is zero-based, that is, 0 \leq a \leq N - 1 holds.

For a string S and Q integers k_0, k_1, ..., k_{Q-1}, calculate the k_i-DMC number of S for each i (0 \leq i \leq Q-1).

Constraints

3 \leq N \leq 10^6

S consists of uppercase English letters

1 \leq Q \leq 75

3 \leq k_i \leq N

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N
S
Q
k_{0} k_{1} ... k_{Q-1}

Output

Print Q lines.
The i-th line should contain the k_i-DMC number of the string S.

Sample Input 1

18
DWANGOMEDIACLUSTER
1
18

Sample Output 1

1

(a,b,c) = (0, 6, 11) satisfies the conditions.

Strangely, Dwango Media Cluster does not have so much DMC-ness by his definition.

Sample Input 2

18
DDDDDDMMMMMCCCCCCC
1
18

Sample Output 2

210

The number of triples can be calculated as 6\times 5\times 7.

Sample Input 3

54
DIALUPWIDEAREANETWORKGAMINGOPERATIONCORPORATIONLIMITED
3
20 30 40

Sample Output 3

0
1
2

(a, b, c) = (0, 23, 36), (8, 23, 36) satisfy the conditions except the last one, namely, c-a < k_i.

By the way, DWANGO is an acronym for "Dial-up Wide Area Network Gaming Operation".

Sample Output 4

30
DMCDMCDMCDMCDMCDMCDMCDMCDMCDMC
4
5 10 15 20

Sample Output 4

10
52
110
140


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

;; BEGIN_INSERTED_CONTENTS
(declaim (inline read-line-into))
(defun read-line-into (buffer-string &key (in *standard-input*) (term-char #\Space))
  "Receives ASCII inputs and returns multiple values: the string and the end
position.

This function calls READ-BYTE to read characters though it calls READ-CHAR
instead on SLIME because SLIME's IO is not bivalent."
  (declare (inline read-byte)
           #-swank (sb-kernel:ansi-stream in))
  (loop for c of-type base-char =
           #-swank (code-char (read-byte in nil #.(char-code #\Newline)))
           #+swank (read-char in nil #\Newline)
        for idx from 0
        until (char= c #\Newline)
        do (setf (char buffer-string idx) c)
        finally (when (< idx (length buffer-string))
                  (setf (char buffer-string idx) term-char))
                (return (values buffer-string idx))))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (s (let ((s (make-string n :element-type 'base-char)))
              (read-line-into s)))
         (q (read))
         (ks (make-array q :element-type 'uint32))
         (cumul-d (make-array (+ n 1) :element-type 'uint31))
         (cumul-m (make-array (+ n 1) :element-type 'uint31))
         (cumul-c (make-array (+ n 1) :element-type 'uint31))
         (cumul-dm (make-array (+ n 1) :element-type 'uint31)))
    (declare (uint31 n q)
             (simple-base-string s))
    (dotimes (i q)
      (setf (aref ks i) (read)))
    (dotimes (i n)
      (setf (aref cumul-d (+ i 1))
            (+ (aref cumul-d i)
               (if (char= #\D (aref s i)) 1 0)))
      (setf (aref cumul-m (+ i 1))
            (+ (aref cumul-m i)
               (if (char= #\M (aref s i)) 1 0)))
      (setf (aref cumul-c (+ i 1))
            (+ (aref cumul-c i)
               (if (char= #\C (aref s i)) 1 0))))
    (dotimes (i n)
      (setf (aref cumul-dm (+ i 1))
            (if (char= #\M (aref s i))
                (+ (aref cumul-dm i) (aref cumul-d i))
                (aref cumul-dm i))))
    (let ((total-dmc 0))
      (declare (uint62 total-dmc))
      (dotimes (i n)
        (when (char= #\M (aref s i))
          (incf total-dmc (* (aref cumul-d i)
                             (- (aref cumul-c n) (aref cumul-c i))))))
      (labels ((calc (k)
                 (let ((res 0))
                   (declare (uint62 res))
                   (dotimes (z n)
                     (when (char= #\C (aref s z))
                       (incf res (aref cumul-dm (max 0 (+ 1 (- z k)))))
                       (incf res (* (aref cumul-d (max 0 (+ 1 (- z k))))
                                    (- (aref cumul-m z)
                                       (aref cumul-m (max 0 (+ 1 (- z k)))))))))
                   res)))
        (sb-int:dovector (k ks)
          (println (- total-dmc (calc k))))))))

#-swank (main)


Score: 100 points

Problem Statement

There is a train going from Station A to Station B that costs X yen (the currency of Japan).

Also, there is a bus going from Station B to Station C that costs Y yen.

Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.

How much does it cost to travel from Station A to Station C if she uses this ticket?

Constraints

1 \leq X,Y \leq 100

Y is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If it costs x yen to travel from Station A to Station C, print x.

Sample Input 1

81 58

Sample Output 1

110

The train fare is 81 yen.

The train fare is 58 ⁄ 2=29 yen with the 50% discount.

Thus, it costs 110 yen to travel from Station A to Station C.

Sample Input 2

4 54

Sample Output 2

31


(defvar *N* (read))
(defvar *M* (read))

(defun shape-ans (n lst)
  (let ((tmp-lst (list nil)))
    (dolist (x lst)
      (when (= n (car x))
        (push (cdr x) tmp-lst)))
    (setq tmp-lst (sort (cdr (reverse tmp-lst)) #'<))
    (let ((count 0)
          (tmp-alist (list nil))
          (r-lst (list nil))
          (flag nil))
      (dolist (x tmp-lst)
        (push (cons x (incf count)) tmp-alist))
      (setq tmp-alist (cdr (reverse tmp-alist)))
      (dolist (x lst)
        (dolist (y tmp-alist)
          (when (eql (cdr x) (car y))
            (push (cons 0 (concatenate 'string (format nil "~6,'0D" n) (format nil "~6,'0D" (cdr y)))) r-lst)
            (setq flag t)))
        (unless flag
          (push x r-lst))
        (setq flag nil))
      (cdr (reverse r-lst)))))

(defun main ()
  (let ((lst (list nil)))
    (dotimes (x *M*)
      (push (cons (read) (read)) lst))
    (setq lst (cdr (reverse lst)))
    (dotimes (x *N*)
      (setq lst (shape-ans (1+ x) lst)))
    (dolist (v lst)
      (when (= 0 (car v))
        (format t "~A~%" (cdr v))))))

(main)

Score: 300 points

Problem Statement

In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.

City i is established in year Y_i and belongs to Prefecture P_i.

You can assume that there are no multiple cities that are established in the same year.

It is decided to allocate a 12-digit ID number to each city.

If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.

Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.

Find the ID numbers for all the cities.

Note that there can be a prefecture with no cities.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq P_i \leq N

1 \leq Y_i \leq 10^9

Y_i are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
P_1 Y_1
:
P_M Y_M

Output

Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).

Sample Input 1

2 3
1 32
2 63
1 12

Sample Output 1

000001000002
000002000001
000001000001

As City 1 is the second established city among the cities that belong to Prefecture 1, its ID number is 000001000002.

As City 2 is the first established city among the cities that belong to Prefecture 2, its ID number is 000002000001.

As City 3 is the first established city among the cities that belong to Prefecture 1, its ID number is 000001000001.

Sample Input 2

2 3
2 55
2 77
2 99

Sample Output 2

000002000001
000002000002
000002000003


(defvar *N* (read))
(defvar *M* (read))

(defun shape-ans (n lst)
  (let ((tmp-lst (list nil)))
    (dolist (x lst)
      (when (= n (car x))
        (push (cdr x) tmp-lst)))
    (setq tmp-lst (sort (cdr (reverse tmp-lst)) #'<))
    (let* ((count 0)
           (tmp-alist (loop for x in tmp-lst
                            for y from 1 to (length tmp-lst)
                            collect (cons x y)))
           (r-lst (list nil))
           (flag nil))
      (dolist (x lst)
        (dolist (y tmp-alist)
          (when (eql (cdr x) (car y))
                (push (cons 0 (concatenate 'string (format nil "~6,'0D" n) (format nil "~6,'0D" (cdr y)))) r-lst)
                (setq flag t)))
        (unless flag
          (push x r-lst))
        (setq flag nil))
      (cdr (reverse r-lst)))))

(defun main ()
  (let ((lst (loop for x from 0 to *N*
                   collect (cons (read) (read)))))
    (dotimes (x *N*)
      (setq lst (shape-ans (1+ x) lst)))
    (dolist (result lst)
      (when (= 0 (car result))
        (princ (cdr result))))))

(main)


(defparameter *n* (read))
(when (= *n* 2)
  (defparameter *a* (read))
  (defparameter *b* (read)))
(when (= *n* 1)
  (defparameter *a* nil)
  (defparameter *b* nil))

(defun f (n a b)
  (if (= n 1)
      "Hello World"
      (+ a b)))

(princ (f *n* *a* *b*))

Score: 100 points

Problem Statement

In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.

One day, there was an exam where a one-year-old child must write a program that prints Hello World, and a two-year-old child must write a program that receives integers A, B and prints A+B.

Takahashi, who is taking this exam, suddenly forgets his age.

He decides to write a program that first receives his age N (1 or 2) as input, then prints Hello World if N=1, and additionally receives integers A, B and prints A+B if N=2.

Write this program for him.

Constraints

N is 1 or 2.

A is an integer between 1 and 9 (inclusive).

B is an integer between 1 and 9 (inclusive).

Input

Input is given from Standard Input in one of the following formats:

1

2
A
B

Output

If N=1, print Hello World; if N=2, print A+B.

Sample Input 1

1

Sample Output 1

Hello World

As N=1, Takahashi is one year old. Thus, we should print Hello World.

Sample Input 2

2
3
5

Sample Output 2

8

As N=2, Takahashi is two years old. Thus, we should print A+B, which is 8 since A=3 and B=5.


(defun solve (n ans tmax)
  (cond
    ((< n 1)
     (if (> ans 1000) 'tle ans))
    (t
     (print n)
     (print ans)
     (print tmax)
     (let ((cost (read)) (time (read)))
	 (if (and
	      (<= time tmax)
	      (< cost ans))
	     (solve (- n 1) cost tmax)
	     (solve (- n 1) ans tmax))))))
(print (solve (read) 1000000000 (read)))

Score : 200 points

Problem Statement

When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.

You, the smartwatch, has found N routes to his home.

If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.

Find the smallest cost of a route that takes not longer than time T.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq T \leq 1000

1 \leq c_i \leq 1000

1 \leq t_i \leq 1000

The pairs (c_i, t_i) are distinct.

Input

Input is given from Standard Input in the following format:

N T
c_1 t_1
c_2 t_2
:
c_N t_N

Output

Print the smallest cost of a route that takes not longer than time T.

If there is no route that takes not longer than time T, print TLE instead.

Sample Input 1

3 70
7 60
1 80
4 50

Sample Output 1

4

The first route gets him home at cost 7.

The second route takes longer than time T = 70.

The third route gets him home at cost 4.

Thus, the cost 4 of the third route is the minimum.

Sample Input 2

4 3
1 1000
2 4
3 1000
4 500

Sample Output 2

TLE

There is no route that takes not longer than time T = 3.

Sample Input 3

5 9
25 8
5 9
4 10
1000 1000
6 1

Sample Output 3

5


(defun solve (n ans tmax)
  (cond
    ((< n 1)
     (if (> ans 1000) 'tle ans))
    (t
     (print n)
     (print ans)
     (print tmax)
     (let ((cost (read)) (time (read)))
	 (if (and
	      (<= time tmax)
	      (< cost ans))
	     (solve (- n 1) cost tmax)
	     (solve (- n 1) ans tmax))))))
(print (solve (read) (1000000000) (read)))


(let ((n (read))
      (tmax (read))
      (ans 1000000000))
  (loop repeat n do
       (let ((cost (read))
	     (time (read)))
	 (when (and
		(<= time tmax)
		(< cost ans))
	   (setq ans cost))))
  (print (if (<= ans 1000) ans 'TLE)))


Score : 100 points

Problem Statement

Cat Snuke is learning to write characters.
Today, he practiced writing digits 1 and 9, but he did it the other way around.

You are given a three-digit integer n written by Snuke.
Print the integer obtained by replacing each digit 1 with 9 and each digit 9 with 1 in n.

Constraints

111 \leq n \leq 999

n is an integer consisting of digits 1 and 9.

Input

Input is given from Standard Input in the following format:

n

Output

Print the integer obtained by replacing each occurrence of 1 with 9 and each occurrence of 9 with 1 in n.

Sample Input 1

119

Sample Output 1

991

Replace the 9 in the ones place with 1, the 1 in the tens place with 9 and the 1 in the hundreds place with 9. The answer is 991.

Sample Input 2

999

Sample Output 2

111


(princ (concatenate 'string (mapcar (lambda (n) (if (equal n #\1)
                                                    #\9 #\1)) (concatenate 'list (read-line)))))


;; -*- 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
(declaim (inline hash-keys-to-list))
(defun hash-keys-to-list (hash-table)
  (let ((result nil))
    (maphash (lambda (key _)
               (declare (ignore _))
               (push key result))
             hash-table)
    result))

;; from alexandria
(declaim (inline hash-table-to-alist))
(defun hash-table-to-alist (hash-table)
  (let ((alist nil))
    (maphash (lambda (k v)
               (push (cons k v) alist))
             hash-table)
    alist))

(declaim (inline alist-to-hash-table))
(defun alist-to-hash-table (alist &key (test #'eql))
  (let ((table (make-hash-table :test test)))
    (dolist (pair alist table)
      (setf (gethash (car pair) table) (cdr pair)))))

(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))
         (odd-freq-table (make-hash-table))
         (even-freq-table (make-hash-table)))
    (labels ((ensure-hash (obj table)
               (multiple-value-bind (num presentp) (gethash obj table)
                 (if presentp
                     (setf (gethash obj table) (+ num 1))
                     (setf (gethash obj table) 1)))))
      (dotimes (i n)
        (let ((v (read-fixnum)))
          (if (evenp i)
              (ensure-hash v even-freq-table)
              (ensure-hash v odd-freq-table))))
      (let ((odd-freqs (hash-table-to-alist odd-freq-table))
            (even-freqs (hash-table-to-alist even-freq-table)))
        (setq odd-freqs (sort odd-freqs #'> :key #'cdr)
              even-freqs (sort even-freqs #'> :key #'cdr))
        (println
         (if (= (car (first odd-freqs)) (car (first even-freqs)))
             (cond ((and (second odd-freqs) (second even-freqs))
                    (min (- n (cdr (second even-freqs)) (cdr (first odd-freqs)))
                         (- n (cdr (first even-freqs)) (cdr (second odd-freqs)))))
                   ((second even-freqs)
                    (- n (cdr (second even-freqs)) (cdr (first odd-freqs))))
                   ((second odd-freqs)
                    (- n (cdr (first even-freqs)) (cdr (second odd-freqs))))
                   (t
                    (min (- n (cdr (first even-freqs)))
                         (- n (cdr (first odd-freqs))))))
             (- n (cdr (first even-freqs)) (cdr (first odd-freqs)))))))))

#-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 "4
3 1 3 2
"
    "1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6
105 119 105 119 105 119
"
    "0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4
1 1 1 1
"
    "2
")))

Score : 300 points

Problem Statement

A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:

For each i = 1,2,..., n-2, a_i = a_{i+2}.

Exactly two different numbers appear in the sequence.

You are given a sequence v_1,v_2,...,v_n whose length is even.
We would like to make this sequence /\/\/\/ by replacing some of its elements.
Find the minimum number of elements that needs to be replaced.

Constraints

2 \leq n \leq 10^5

n is even.

1 \leq v_i \leq 10^5

v_i is an integer.

Input

Input is given from Standard Input in the following format:

n
v_1 v_2 ... v_n

Output

Print the minimum number of elements that needs to be replaced.

Sample Input 1

4
3 1 3 2

Sample Output 1

1

The sequence 3,1,3,2 is not /\/\/\/, but we can make it /\/\/\/ by replacing one of its elements: for example, replace the fourth element to make it 3,1,3,1.

Sample Input 2

6
105 119 105 119 105 119

Sample Output 2

0

The sequence 105,119,105,119,105,119 is /\/\/\/.

Sample Input 3

4
1 1 1 1

Sample Output 3

2

The elements of the sequence 1,1,1,1 are all the same, so it is not /\/\/\/.


;; -*- 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
(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))
         (odd-freq-table (make-hash-table))
         (even-freq-table (make-hash-table)))
    (labels ((ensure-hash (obj table)
               (multiple-value-bind (num presentp) (gethash obj table)
                 (if presentp
                     (setf (gethash obj table) (+ num 1))
                     (setf (gethash obj table) 1)))))
      (dotimes (i n)
        (let ((v (read-fixnum)))
          (if (evenp i)
              (ensure-hash v even-freq-table)
              (ensure-hash v odd-freq-table))))
      (let ((odd-freqs (sb-int:%hash-table-alist odd-freq-table))
            (even-freqs (sb-int:%hash-table-alist even-freq-table)))
        (setq odd-freqs (sort odd-freqs #'> :key #'cdr)
              even-freqs (sort even-freqs #'> :key #'cdr))
        (println
         (if (= (car (first odd-freqs)) (car (first even-freqs)))
             (cond ((and (second odd-freqs) (second even-freqs))
                    (min (- n (cdr (second even-freqs)) (cdr (first odd-freqs)))
                         (- n (cdr (first even-freqs)) (cdr (second odd-freqs)))))
                   ((second even-freqs)
                    (- n (cdr (second even-freqs)) (cdr (first odd-freqs))))
                   ((second odd-freqs)
                    (- n (cdr (first even-freqs)) (cdr (second odd-freqs))))
                   (t
                    (min (- n (cdr (first even-freqs)))
                         (- n (cdr (first odd-freqs))))))
             (- n (cdr (first even-freqs)) (cdr (first odd-freqs)))))))))

#-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 "4
3 1 3 2
"
    "1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6
105 119 105 119 105 119
"
    "0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4
1 1 1 1
"
    "2
")))


(defparameter *char-list*
  (loop for i below 26 collect (code-char (+ (char-code #\a)
                                             i))))
(defun lst-equal-p (xs ys)
  (if (null xs)
      t
      (if (equal (first xs) (first ys))
          (lst-equal-p (rest xs)
                       (rest ys))
          nil)))

(defun make-pos-list (lst chr &optional (acc nil) (cnt 0))
  (if (null lst)
      (reverse acc)
      (progn
        (when (char-equal (first lst) chr)
          (push cnt acc))
        (make-pos-list (rest lst) chr acc (1+ cnt)))))

(defun solve (s1 s2)
  (let ((p1 (sort (remove-if #'null
                             (mapcar (lambda (c) (make-pos-list s1 c))
                                     *char-list*))
                  (lambda (xs ys) (< (first xs) (first ys)))))
        (p2 (sort (remove-if #'null
                             (mapcar (lambda (c) (make-pos-list s2 c))
                                     *char-list*))
                  (lambda (xs ys) (< (first xs) (first ys))))))
    (if (/= (length p1) (length p2))
        "No")
    (if (lst-equal-p p1 p2)
        "Yes"
        "No")))

(defun main ()
  (let ((str1 (concatenate 'list (read-line)))
        (str2 (concatenate 'list (read-line))))
    (format t "~a~%" (solve str1 str2))))

(main)

Score : 300 points

Problem Statement

You are given strings S and T consisting of lowercase English letters.

You can perform the following operation on S any number of times:

Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.

Determine if S and T can be made equal by performing the operation zero or more times.

Constraints

1 \leq |S| \leq 2 \times 10^5

|S| = |T|

S and T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S and T can be made equal, print Yes; otherwise, print No.

Sample Input 1

azzel
apple

Sample Output 1

Yes

azzel can be changed to apple, as follows:

Choose e as c_1 and l as c_2. azzel becomes azzle.

Choose z as c_1 and p as c_2. azzle becomes apple.

Sample Input 2

chokudai
redcoder

Sample Output 2

No

No sequences of operation can change chokudai to redcoder.

Sample Input 3

abcdefghijklmnopqrstuvwxyz
ibyhqfrekavclxjstdwgpzmonu

Sample Output 3

Yes


(defun collector (function lst)
  (if lst
      (let* ((ans '())
             (mem (cons (car lst) 1)))
        (mapcar (lambda (k)
                  (if (funcall function k (car mem))
                      (incf (cdr mem))
                      (progn (push mem ans)
                             (setf mem (cons k 1))))) (cdr lst))
        (push mem ans)
        ans)
      '()))
(if (equal (mapcar #'cdr (collector #'char= (sort (concatenate 'list (read-line)) #'char<)))
           (mapcar #'cdr (collector #'char= (sort (concatenate 'list (read-line)) #'char<))))
    (princ "Yes")
    (princ "No"))


(defun solve (s1 s2)
  (let ((h1 (make-hash-table))
        (h2 (make-hash-table))
        (len (length s1)))
    (dotimes (i len)
      (let ((c1 (char s1 i))
            (c2 (char s2 i)))
        (when (or (and (gethash c1 h1) (not (eq c2 (gethash c1 h1))))
                  (and (gethash c2 h2) (not (eq c1 (gethash c2 h2)))))
          (return-from solve "No"))
        (setf (gethash c1 h1) c2)
        (setf (gethash c2 h2) c1)))
    "Yes"))
(format t "~A~%" (solve (read-line) (read-line)))


;; -*- 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 nlet (name args &body body)
  (labels ((ensure-list (x) (if (listp x) x (list x))))
    (let ((args (mapcar #'ensure-list args)))
      `(labels ((,name ,(mapcar #'first args) ,@body))
         (,name ,@(mapcar #'second args))))))

(declaim (ftype (function * (values simple-bit-vector &optional)) make-prime-table))
(defun make-prime-table (size)
  "Erzeugt die Primzahlentabelle 0 zu SIZE-1."
  (declare #.OPT)
  (let ((dict (make-array size :element-type 'bit :initial-element 1)))
    (setf (sbit dict 0) 0 (sbit dict 1) 0)
    (loop for even-num from 4 below size by 2
          do (setf (sbit dict even-num) 0))
    (loop for p from 3 to (ceiling (sqrt size)) by 2
          when (= 1 (sbit dict p))
          do (loop for composite from (+ p p) below size by p
                   until (>= composite size)
                   do (setf (sbit dict composite) 0)))
    dict))

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

;; Hauptteil
(defconstant +magic+ #.(+ 7 (expt 10 9)))
(defun decompose (m)
  (declare #.OPT
           (uint32 m))
  (let* ((factor-sup (ceiling (sqrt m)))
         (prime-table (make-prime-table (1+ factor-sup))))
    (loop for i from 2 below (length prime-table)
          when (= 1 (sbit prime-table i))
          collect (nlet recurse ((count 0))
                    (declare (uint32 count))
                    (multiple-value-bind (quot rem) (floor m i)
                      (if (zerop rem)
                          (progn (setf m quot)
                                 (recurse (1+ count)))
                          count)))
          into factors
          finally (return
                    (let ((factors (delete 0 (the list factors))))
                      (if (= 1 m)
                          factors
                          (append factors (list 1))))))))

;; Based on alexandria
;; (declaim (inline %multiply-range))
(defun %multiply-range (i j)
  (labels ((bisect (j k)
             (declare (type (integer 1 #.most-positive-fixnum) j k)
                      (values integer))
             (if (< (- k j) 8)
                 (multiply-range j k)
                 (let ((middle (+ j (truncate (- k j) 2))))
                   (* (bisect j middle)
                      (bisect (+ middle 1) k)))))
           (multiply-range (j k)
             (declare (type (integer 1 #.most-positive-fixnum) j k))
             (do ((f k (* f m))
                  (m (1- k) (1- m)))
                 ((< m j) f)
               (declare (type (integer 0 (#.most-positive-fixnum)) m)
                        (type unsigned-byte f)))))
    (bisect i j)))

(defun binomial-coefficient (n k)
  (declare ((integer 0 (#.most-positive-fixnum)) n k))
  (assert (>= n k))
  (mod (if (or (zerop k) (= n k))
           1
           (let ((n-k (- n k)))
             (when (< k n-k)
               (rotatef k n-k))
             (if (= 1 n-k)
                 n
                 (floor (%multiply-range (+ k 1) n)
	                (%multiply-range 1 n-k)))))
       +magic+))

(defun multiset-coefficient (n k)
  (binomial-coefficient (+ n k -1) k))

(defun main ()
  (let* ((n (read))
         (m (read))
         (factors (decompose m)))
    (if (= m 1)
        (println 1)
        (println
         (reduce (lambda (x y) (mod (* x y) +magic+))
                 factors
                 :key (lambda (k) (multiset-coefficient n k)))))))

#-swank(main)

Score : 400 points

Problem Statement

You are given positive integers N and M.

How many sequences a of length N consisting of positive integers satisfy a_1 \times a_2 \times ... \times a_N = M? Find the count modulo 10^9+7.

Here, two sequences a' and a'' are considered different when there exists some i such that a_i' \neq a_i''.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of the sequences consisting of positive integers that satisfy the condition, modulo 10^9 + 7.

Sample Input 1

2 6

Sample Output 1

4

Four sequences satisfy the condition: \{a_1, a_2\} = \{1, 6\}, \{2, 3\}, \{3, 2\} and \{6, 1\}.

Sample Input 2

3 12

Sample Output 2

18

Sample Input 3

100000 1000000000

Sample Output 3

957870001


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

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

;; BEGIN_INSERTED_CONTENTS
(defmacro nlet (name args &body body)
  (labels ((ensure-list (x) (if (listp x) x (list x))))
    (let ((args (mapcar #'ensure-list args)))
      `(labels ((,name ,(mapcar #'car args) ,@body))
         (,name ,@(mapcar #'cadr args))))))

(declaim (ftype (function * (values simple-bit-vector &optional)) make-prime-table))
(defun make-prime-table (size)
  "Erzeugt die Primzahlentabelle 0 zu SIZE-1."
  (declare (optimize (speed 3) (safety 1)))
  (let ((dict (make-array size :element-type 'bit :initial-element 1)))
    (setf (sbit dict 0) 0 (sbit dict 1) 0)
    (loop for even-num from 4 below size by 2
          do (setf (sbit dict even-num) 0))
    (loop for p from 3 to (ceiling (sqrt size)) by 2
          when (= 1 (sbit dict p))
          do (loop for composite from (+ p p) below size by p
                   until (>= composite size)
                   do (setf (sbit dict composite) 0)))
    dict))

;; (with-memoizing (:hash-table :test #'equal :key #'cons)
;;   (defun ...))
;; (with-memoizing (:array '(10 10 10) :initial-element -1 :element-type 'fixnum)
;;   (defun ...))
(defmacro with-memoizing (cache-attribs def-form)
  (let* ((cache-attribs (if (atom cache-attribs) (list cache-attribs) cache-attribs))
         (cache-type (first cache-attribs))
         (dimensions (when (eql cache-type :array) (second cache-attribs)))
         (rank (length dimensions))
         (rest-attribs (ecase cache-type
                         (:hash-table (cdr cache-attribs))
                         (:array (cddr cache-attribs))))
         (key (prog1 (getf rest-attribs :key) (remf rest-attribs :key)))
         (cache-form (case cache-type
                       (:hash-table `(make-hash-table ,@rest-attribs))
                       (:array `(make-array ,dimensions ,@rest-attribs))))
         (initial-element (when (eql cache-type :array)
                            (assert (member :initial-element rest-attribs))
                            (getf rest-attribs :initial-element))))
    (let ((cache (gensym))
          (value (gensym))
	  (present-p (gensym))
          (name-alias (gensym))
	  (args-lst (gensym))
          (indices (loop repeat rank collect (gensym))))
      (labels ((make-cache-check-form (cache-type args)
                 (case cache-type
                   (:hash-table
                    `(let ((,args-lst (funcall ,(or key #'list) ,@args)))
                       (multiple-value-bind (,value ,present-p)
                           (gethash ,args-lst ,cache)
                         (if ,present-p
                             ,value
                             (setf (gethash ,args-lst ,cache)
                                   (,name-alias ,@args))))))
                   (:array
                    (if key
                        `(multiple-value-bind ,indices
                             (funcall ,key ,@args)
                           (let ((,value (aref ,cache ,@indices)))
                             (if (eql ,initial-element ,value)
                                 (setf (aref ,cache ,@indices)
                                       (,name-alias ,@args))
                                 ,value)))
                        `(let ((,value (aref ,cache ,@args)))
                           (if (eql ,initial-element ,value)
                               (setf (aref ,cache ,@args)
                                     (,name-alias ,@args))
                               ,value))))))
               (make-reset-form (cache-type)
                 (case cache-type
                   (:hash-table `(setf ,cache (make-hash-table ,@rest-attribs)))
                   (:array `(prog1 nil
                              (fill (array-storage-vector ,cache) ,initial-element)))))
               (make-reset-name (name)
                 (intern (format nil "RESET-~A" (symbol-name name)))))
        (ecase (car def-form)
          ((defun)
           (destructuring-bind (_ name args &body body) def-form
             (declare (ignore _))
             `(let ((,cache ,cache-form))
                (defun ,(make-reset-name name) () ,(make-reset-form cache-type))
                (defun ,name ,args
                  (labels ((,name-alias ,args ,@body))
                    (declare (inline ,name-alias))
                    ,(make-cache-check-form cache-type args))))))
          ((nlet)
           (destructuring-bind (_ name bindings &body body) def-form
             (declare (ignore _))
             `(let ((,cache ,cache-form))
                (nlet ,name ,bindings
                  ,(let ((args (mapcar (lambda (x) (if (atom x) x (car x))) bindings)))
                     `(labels ((,name-alias ,args ,@body))
                        (declare (inline ,name-alias))
                        ,(make-cache-check-form cache-type args)))))))
          ((labels flet)
           (destructuring-bind (_ definitions &body labels-body) def-form
             (declare (ignore _))
             (destructuring-bind (name args &body body) (car definitions)
               `(let ((,cache ,cache-form))
                  (,(car def-form)
                   ((,(make-reset-name name) () ,(make-reset-form cache-type))
                    (,name ,args
                           (labels ((,name-alias ,args ,@body))
                             (declare (inline ,name-alias))
                             ,(make-cache-check-form cache-type args)))
                    ,@(cdr definitions))
                   (declare (ignorable #',(make-reset-name name)))
                   ,@labels-body))))))))))

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

;; Hauptteil
(defconstant +magic+ #.(+ 7 (expt 10 9)))
(defun decompose (m prime-table)
  (declare #.OPT
           (simple-bit-vector prime-table)
           (uint32 m))
  (loop for i from 2 below (length prime-table)
        when (= 1 (sbit prime-table i))
        collect (nlet recurse ((count 0))
                  (declare (uint32 count))
                  (multiple-value-bind (quot rem) (floor m i)
                    (if (zerop rem)
                        (progn (setf m quot)
                               (recurse (1+ count)))
                        count)))
        into factors
        finally (let ((factors (delete 0 (the list factors))))
                  (return (or factors (list 1))))))

(with-memoizing (:array '(100001 32) :element-type 'fixnum :initial-element -1)
  (defun multiset-coefficient (n k)
    (declare #.OPT
             ((integer 1 #.most-positive-fixnum) n)
             ((integer 0 #.most-positive-fixnum) k))
    (cond ((zerop k) 1)
          ((= n 1) 1)
          (t (mod (the uint63 (+ (multiset-coefficient (- n 1) k)
                                 (multiset-coefficient n (- k 1))))
                  +magic+)))))

(defun main ()
  (let* ((n (read))
         (m (read))
         (max-prime (ceiling (sqrt m)))
         (prime-table (make-prime-table (1+ max-prime)))
         (factors (decompose m prime-table)))
    (if (= m 1)
        (println 1)
        (println
         (reduce (lambda (x y) (mod (* x y) +magic+))
                 factors
                 :key (lambda (k) (multiset-coefficient n k)))))))

#-swank(main)


(defmacro defmemo (name args &body exprs)
  "Define memoized function with referential transparency."
  (let ((fn (gensym))
        (memo (gensym)))
    `(labels ((,fn ,args ,@exprs))
       (let ((,memo (make-hash-table :test #'equal)))
         (defun ,name ,args
           (or (gethash (list ,@args) ,memo)
               (setf (gethash (list ,@args) ,memo) (apply (function ,fn) (list ,@args)))))))))

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

(defun f (m)
  (labels ((f1 (m div lst)
             (let ((x (/ m div)))
               (cond ((= x 1) (cons div lst))
                     ((integerp x) (f1 x div (cons div lst)))
                     ((< m (* div div)) (cons m lst))
                     ((oddp div) (f1 m (+ div 2) lst))
                     (t (f1 m (1+ div) lst))))))
    (f1 m 2 nil)))

(defun combination (n r)
  (if (zerop r)
      1
      (* (/ n r)
         (combination (1- n) (1- r)))))

(defun g (lst)
  (mapcar (lambda (n) (count n lst)) (remove-duplicates lst)))

(defun h (n lst)
  (apply #'* (mapcar (lambda (x)
                       (combination (+ x (1- n)) x))
                     lst)))

(defun i (n m)
  (rem (h n (g (f m))) (+ 1000000000 7)))

(princ (i *n* *m*))


;; -*- 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
(defstruct (stair-sum (:constructor %make-stair-sum))
  (cumul nil :type (simple-array (unsigned-byte 62) (*)))
  (stair nil :type (simple-array (unsigned-byte 62) (*))))

(declaim (inline make-stair-sum))
(defun make-stair-sum (vector)
  "Makes a table from VECTOR that stores 0, VECTOR[0], VECTOR[0] + 2*VECTOR[1],
VECTOR[0] + 2*VECTOR[1] + 3*VECTOR[2], ..."
  (let* ((n (length vector))
         (cumul (make-array (+ n 1) :element-type '(unsigned-byte 62) :initial-element 0))
         (stair (make-array (+ n 1) :element-type '(unsigned-byte 62) :initial-element 0)))
    (dotimes (i n)
      (setf (aref stair (+ i 1))
            (+ (aref stair i) (* (+ i 1) (aref vector i)))
            (aref cumul (+ i 1))
            (+ (aref cumul i) (aref vector i))))
    (%make-stair-sum :cumul cumul :stair stair)))

(declaim (inline stair-sum-query))
(defun stair-sum-query (stair-sum l r)
  "Returns VECTOR[L] + 2*VECTOR[L+1] + 3*VECTOR[L+2] + ... + (R-L)*VECTOR[R-1]."
  (symbol-macrolet ((stair (stair-sum-stair stair-sum))
                    (cumul (stair-sum-cumul stair-sum)))
    (the uint62 (- (- (aref stair r)
                      (aref stair l))
                   (the uint62 (* l (- (aref cumul r)
                                       (aref cumul l))))))))

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  "NOTE: cannot read -2^62"
  (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
;;;

(declaim (inline calc-distribution))
(defun calc-distribution (total num)
  (declare (uint31 total num))
  (multiple-value-bind (smaller rem) (floor total num)
    (if (zerop rem)
        `((,smaller . ,num))
        (let ((larger-num (- total (* smaller num))))
          `((,(+ 1 smaller) . ,larger-num) .
            (,smaller . ,(- num larger-num)))))))

(declaim (inline get-next))
(defun get-next (distribution)
  (assert (cdr distribution))
  (let* ((node1 (car distribution))
         (node2 (cdr distribution))
         (num1 (cdr node1))
         (num2 (cdr node2)))
    (declare (uint31 num1 num2))
    (if (= num1 1)
        (rplacd node2 (+ num2 1))
        (cons (rplacd node1 (- num1 1)) (rplacd node2 (+ num2 1))))))

(declaim (inline calc-coefficient))
(defun calc-coefficient (distribution)
  (if (cdr distribution)
      (destructuring-bind ((size1 . num1) . (size2 . num2)) distribution
        (declare (uint31 size1 num1 size2 num2))
        (+ (the uint62 (* num1 (expt (+ size1 1) 2)))
           (the uint62 (* num2 (expt (+ size2 1) 2)))
           num1
           num2))
      (destructuring-bind ((size . num)) distribution
        (declare (uint31 size num))
        (+ (* num (expt (+ size 1) 2))
           num))))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (x (read))
         (xs (make-array n :element-type 'uint31))
         (dxs (make-array n :element-type 'uint31))
         (cumul (make-array (+ n 1) :element-type 'uint31 :initial-element 0))
         (res #xffffffffffffffffff))
    (declare (uint31 n x))
    (dotimes (i n)
      (setf (aref xs i) (read-fixnum)
            (aref dxs i) (- (aref xs i) (if (zerop i) 0 (aref xs (- i 1))))
            (aref cumul (+ i 1)) (+ (aref cumul i) (aref dxs i))))
    (let ((stair-sum (make-stair-sum dxs)))
      (loop for k from 1 to n
            for cost-sum of-type unsigned-byte = 0
            for n/k of-type uint31 = (floor n k)
            do (when (> n (* k n/k))
                 (let* ((end (- n (* k n/k)))
                        (base-coef (calc-coefficient (calc-distribution n k)))
                        (delta-coef (+ 1 (* 2 (+ n/k 1))))
                        (cost (- (* base-coef
                                    (- (aref cumul end) (aref cumul 0)))
                                 (* delta-coef
                                    (stair-sum-query stair-sum 1 end)))))
                   (declare (uint31 end delta-coef)
                            (uint62 base-coef))
                   (incf cost-sum cost)))
            do (loop for m from n/k above 0
                     for base-index of-type uint31 = (- n (* k m))
                     for size of-type uint31 = (floor (* m k) k)
                     for base-coef of-type uint62 = (+ (* k (expt (+ size 1) 2)) k)
                     for delta-coef of-type uint31 = (if (= 1 m) 5 (+ 1 (* 2 m)))
                     for cost = (- (* base-coef
                                      (- (aref cumul (+ base-index k))
                                         (aref cumul base-index)))
                                   (* delta-coef
                                      (stair-sum-query stair-sum
                                                       (+ base-index 1)
                                                       (+ base-index k))))
                     do (incf cost-sum cost))
               (setq res (min res (+ (* k x) cost-sum)))))
    ;; 拾うコストNXは最後に足す
    (println (+ res (* x n)))))

#-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 "200000 1000000000~%")
    (let ((xs (loop repeat 200000 collect (+ 1 (random #.(expt 10 9))))))
      (setq xs (sort xs #'<))
      (dolist (x xs)
        (println x 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 100
1 10
"
    "355
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5 1
1 999999997 999999998 999999999 1000000000
"
    "19999999983
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10 8851025
38 87 668 3175 22601 65499 90236 790604 4290609 4894746
"
    "150710136
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "16 10
1 7 12 27 52 75 731 13856 395504 534840 1276551 2356789 9384806 19108104 82684732 535447408
"
    "3256017715
")))

Score : 700 points

Problem Statement

Snuke has decided to use a robot to clean his room.

There are N pieces of trash on a number line.
The i-th piece from the left is at position x_i.
We would like to put all of them in a trash bin at position 0.

For the positions of the pieces of trash, 0 < x_1 < x_2 < ... < x_{N} \leq 10^{9} holds.

The robot is initially at position 0.
It can freely move left and right along the number line, pick up a piece of trash when it comes to the position of that piece, carry any number of pieces of trash and put them in the trash bin when it comes to position 0. It is not allowed to put pieces of trash anywhere except in the trash bin.

The robot consumes X points of energy when the robot picks up a piece of trash, or put pieces of trash in the trash bin. (Putting any number of pieces of trash in the trash bin consumes X points of energy.)
Also, the robot consumes (k+1)^{2} points of energy to travel by a distance of 1 when the robot is carrying k pieces of trash.

Find the minimum amount of energy required to put all the N pieces of trash in the trash bin.

Constraints

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

0 < x_1 < ... < x_N \leq 10^9

1 \leq X \leq 10^9

All values in input are integers.

Partial Scores

400 points will be awarded for passing the test set satisfying N \leq 2000.

Input

Input is given from Standard Input in the following format:

N X
x_1 x_2 ... x_{N}

Output

Print the answer.

Sample Input 1

2 100
1 10

Sample Output 1

355

Travel to position 10 by consuming 10 points of energy.

Pick up the piece of trash by consuming 100 points of energy.

Travel to position 1 by consuming 36 points of energy.

Pick up the piece of trash by consuming 100 points of energy.

Travel to position 0 by consuming 9 points of energy.

Put the two pieces of trash in the trash bin by consuming 100 points of energy.

This strategy consumes a total of 10+100+36+100+9+100=355 points of energy.

Sample Input 2

5 1
1 999999997 999999998 999999999 1000000000

Sample Output 2

19999999983

Sample Input 3

10 8851025
38 87 668 3175 22601 65499 90236 790604 4290609 4894746

Sample Output 3

150710136

Sample Input 4

16 10
1 7 12 27 52 75 731 13856 395504 534840 1276551 2356789 9384806 19108104 82684732 535447408

Sample Output 4

3256017715


Score : 200 points

Problem Statement

There is a square in the xy-plane. The coordinates of its four vertices are (x_1,y_1),(x_2,y_2),(x_3,y_3) and (x_4,y_4) in counter-clockwise order.
(Assume that the positive x-axis points right, and the positive y-axis points up.)

Takahashi remembers (x_1,y_1) and (x_2,y_2), but he has forgot (x_3,y_3) and (x_4,y_4).

Given x_1,x_2,y_1,y_2, restore x_3,y_3,x_4,y_4. It can be shown that x_3,y_3,x_4 and y_4 uniquely exist and have integer values.

Constraints

|x_1|,|y_1|,|x_2|,|y_2| \leq 100

(x_1,y_1) ≠ (x_2,y_2)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

x_1 y_1 x_2 y_2

Output

Print x_3,y_3,x_4 and y_4 as integers, in this order.

Sample Input 1

0 0 0 1

Sample Output 1

-1 1 -1 0

(0,0),(0,1),(-1,1),(-1,0) is the four vertices of a square in counter-clockwise order.
Note that (x_3,y_3)=(1,1),(x_4,y_4)=(1,0) is not accepted, as the vertices are in clockwise order.

Sample Input 2

2 3 6 6

Sample Output 2

3 10 -1 7

Sample Input 3

31 -41 -59 26

Sample Output 3

-126 -64 -36 -131


;; -*- 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 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* ((l (read))
         (k (- (integer-length l) 1))
         (out (make-string-output-stream :element-type 'base-char))
         (n (+ k 1))
         (m 0))
    (declare (uint32 m l))
    (dotimes (i k)
      (format out "~D ~D ~D~%" (+ i 1) (+ i 2) 0)
      (format out "~D ~D ~D~%" (+ i 1) (+ i 2) (ash 1 i))
      (incf m 2))
    (loop for v from (- k 1) downto 0
          when (>= (- l (ash 1 v)) (ash 1 k))
          do (format out "~D ~D ~D~%" (+ v 1) n (- l (ash 1 v)))
             (decf l (ash 1 v))
             (incf m))
    (format t "~D ~D~%" n m)
    (write-string (get-output-stream-string out))))

#-swank (main)

Score : 700 points

Problem Statement

You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.

The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.

The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).

Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.

There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.

Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.

Constraints

2 \leq L \leq 10^6

L is an integer.

Input

Input is given from Standard Input in the following format:

L

Output

In the first line, print N and M, the number of the vertices and edges in your graph.
In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge.
If there are multiple solutions, any of them will be accepted.

Sample Input 1

4

Sample Output 1

8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1

In the graph represented by the sample output, there are four paths from Vertex 1 to N=8:

1 → 2 → 3 → 4 → 8 with length 0

1 → 2 → 3 → 7 → 8 with length 1

1 → 2 → 6 → 7 → 8 with length 2

1 → 5 → 6 → 7 → 8 with length 3

There are other possible solutions.

Sample Input 2

5

Sample Output 2

5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1


(defun leader ()
  (setf *gridmap* (loop :for n :from 1 :upto *var* collect(concatenate 'list (read-line)))))

(defun compresser ()
  (setf *gridmap* (remove (loop :for f :from 1 :upto *hol* collect(coerce "." 'character)) *gridmap* :test #'equal))
  (defparameter *nth-comp* 0)
  (loop :for a :from 0 :upto (1- *hol*) do(comp-loop a)))

(defun comp-loop (n)
  (format t "縦~A.横~A~%" *nth-comp* n)
  (if (equal (nth n (nth *nth-comp* *gridmap*)) (coerce "." 'character))
      (if (= *nth-comp* (length *gridmap*))
          (setf  *gridmap* (mapcar (lambda (g)
            (remove-if #'(lambda (q) t) g :start n :end (1+ n))) *gridmap*))
          (progn (setq *nth-comp* (1+ *nth-comp*))
                 (comp-loop n)))
      (setq *nth-comp* 0)))

(defun main ()
  (defparameter *gridmap* nil)
  (defparameter *var* (read))
  (defparameter *hol* (read))
  (leader)
  (compresser)
                                        ;(mapcar (lambda (n) (format t "~A~%" (concatenate 'string n))) *gridmap*)
  *gridmap*
  )

(mapcar (lambda (n) (format t "~A~%" (concatenate 'string n))) (main))

Score : 200 points

Problem Statement

There is a grid of squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column from the left is represented as (i, j).
Each square is black or white.
The color of the square is given as an H-by-W matrix (a_{i, j}).
If a_{i, j} is ., the square (i, j) is white; if a_{i, j} is #, the square (i, j) is black.

Snuke is compressing this grid.
He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares:

Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns.

It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation.
Find the final state of the grid.

Constraints

1 \leq H, W \leq 100

a_{i, j} is . or #.

There is at least one black square in the whole grid.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}...a_{1, W}
:
a_{H, 1}...a_{H, W}

Output

Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity.

Sample Input 1

4 4
##.#
....
##.#
.#.#

Sample Output 1

###
###
.##

The second row and the third column in the original grid will be removed.

Sample Input 2

3 3
#..
.#.
..#

Sample Output 2

#..
.#.
..#

As there is no row or column that consists only of white squares, no operation will be performed.

Sample Input 3

4 5
.....
.....
..#..
.....

Sample Output 3

#

Sample Input 4

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

Sample Output 4

..#
#..
.#.
.#.
#.#


;;; body

(defun solve (n k x)
  (flet ((calc-dist (i-left i-right)
           (let ((left (aref x i-left))
                 (right (aref x (1- i-right))))
             (min (+ (abs left) (abs (- right left)))
                  (+ (abs right) (abs (- right left)))))))
    (if (= n 1)
        (abs (aref x 0))
        (reduce #'min
                (let ((acc nil))
                  (loop with i = 0  while (<= (+ i k) n) do
                       (push (calc-dist i
                                        (+ i k))
                             acc)
                       (incf i))
                  acc)))))

(defun main ()
  (let ((n (read))
        (k (read)))
    (let ((x (make-array n
                         :initial-contents (loop repeat n collect (read)))))
      (princ (solve n k x))
      (fresh-line))))

#-swank (main)

Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

8 5
-9 -7 -4 -3 1 2 3 4

Sample Output 4

10


(let* ((n (read))
       (m (read))
       (lst (loop :repeat n :collect (read)))
       (z (loop :for k :on lst
                :for j :from 0
                :if (cdr k)
                  :if (<= (first k) 0 (second k))
                    :return (if (= 0 (first k))
                                (cons j j)
                                (cons j (1+ j))) :end
                :else :return j)))
  (princ (loop :for k :from (- (car z) (1- m)) :upto (1+ (car z))
               :for j := (+ k m)
               :if (and (<= 0 k) (<= j n))
                 :minimize (let* ((a (subseq lst k (1+ (car z))))
                                  (b (subseq lst (cdr z) j)))
                             (min (+ (* 2 (abs (car a))) (car (last b)))
                                  (+ (abs (car a)) (* 2 (car (last b)))))))))