;グローバル変数
(setq *n* (read))
(setq *l* nil)

;ガイドブック順ソートの定義
(defun my< (a b)
  (cond
    ((equal (car a) (car b))
     (if (> (cadr a) (cadr b)) t nil))
    ((string< (car a) (car b))
     t)
    (t nil)))

;入力
(dotimes (i *n*)
 (setq *l* (append *l* (list (list (string (read)) (read) (1+ i))))))

;ソート実行
(sort *l* #'(lambda (a b) (my< a b)))

;出力
(format t "~{~a~^~%~}~%" (mapcar #'caddr *l*))

Score : 200 points

Problem Statement

You have decided to write a book introducing good restaurants.
There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i.
No two restaurants have the same score.

You want to introduce the restaurants in the following order:

The restaurants are arranged in lexicographical order of the names of their cities.

If there are multiple restaurants in the same city, they are arranged in descending order of score.

Print the identification numbers of the restaurants in the order they are introduced in the book.

Constraints

1 ≤ N ≤ 100

S is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters.

0 ≤ P_i ≤ 100

P_i is an integer.

P_i ≠ P_j (1 ≤ i < j ≤ N)

Input

Input is given from Standard Input in the following format:

N
S_1 P_1
:
S_N P_N

Output

Print N lines. The i-th line (1 ≤ i ≤ N) should contain the identification number of the restaurant that is introduced i-th in the book.

Sample Input 1

6
khabarovsk 20
moscow 10
kazan 50
kazan 35
moscow 60
khabarovsk 40

Sample Output 1

3
4
6
1
5
2

The lexicographical order of the names of the three cities is kazan < khabarovsk < moscow. For each of these cities, the restaurants in it are introduced in descending order of score. Thus, the restaurants are introduced in the order 3,4,6,1,5,2.

Sample Input 2

10
yakutsk 10
yakutsk 20
yakutsk 30
yakutsk 40
yakutsk 50
yakutsk 60
yakutsk 70
yakutsk 80
yakutsk 90
yakutsk 100

Sample Output 2

10
9
8
7
6
5
4
3
2
1


(let* ((a (read))
       (lst (loop :repeat a :collect (read-line)))
       (srt nil))
  (defun f (k)
      (cons (subseq k 0 (position #\Space k :test #'char=)) (parse-integer (subseq k (1+ (position #\Space k :test #'char=))))))
  (map-into lst #'f lst)
  (defun ff< (p q)
    (if (string= (car p) (car q))
        (> (cdr p) (cdr q))
        (string< (car p) (car q))))
  (setf srt (sort (copy-seq lst) #'ff<))
  (mapcar (lambda (k) (print (1+ (position k lst)))) srt))

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

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.


(defstruct p i city point)
(defun f (s)
  (let* ((n (read s))
         (ps (loop for i from 1 to n
                   for city = (read s)
                   for point = (read s)
                   collecting (make-p :i i :city city :point point)))
         (sorted1 (sort ps #'> :key #'p-point))
         (sorted2 (sort sorted1 #'string< :key #'p-city))
    (loop for p in sorted2
          do (progn (princ (p-i p)) (terpri))))
(f t)


(defun f (s)
  (let* ((n (read s))
         (ps (loop for i from 1 to n
                   for city = (read s)
                   for point = (read s)
                   collecting (list i city point)))
         (sorted1 (sort ps #'(lambda (p pp) (> (third p) (third pp)))))
         (sorted2 (sort sorted1 #'(lambda (p pp) (string< (second p) (second pp))))))
    (loop for p in sorted2
          do (format t "~A~%" (first p)))))
(f t)


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

(defsolver solution-b2 (n)
  (let ((l (list)))
    (dotimes (i n l)
      (push (list (read) (read) (+ i 1)) l))
    (setf l (sort l #'(lambda (x y)
			(or
			 (and
			  (string= (nth 0 x) (nth 0 y))
			  (> (nth 1 x) (nth 1 y)))
			 (string< (nth 0 x) (nth 0 y))))))
    (loop for x in l do (format t "~a~%" (nth 2 x)))))

(solution-b2)


(let* ((n (read))
       (m (read))
       (k (make-array (list (1+ m))))
       (s (make-array (list (1+ m) (1+ n))))
       (p (make-array (list (1+ m))))
       (ans 0))
  (loop :for i :from 1 :to m
        :do (setf (aref k i) (read))
        :do (loop :for j :from 1 :to (aref k i)
                  :do (setf (aref s i j) (read))))
  (loop :for i :from 1 :to m
        :do (setf (aref p i) (read)))
  (defun check (cnt sw)
    (if (= cnt (+ n 1))
        (if (= (loop :for i :from 1 :to m
                     :if (= (mod (loop :for j :from 1 :to (aref k i)
                                       :sum (aref sw (aref s i j)))
                                 2)
                            (aref p i))
                     :sum 1)
               m)
              (incf ans))
        (loop :for a :from 0 :to 1
              :do (setf (aref sw cnt) a)
              :do (check (1+ cnt) sw))))
  (check 1 (make-array (list (1+ n))))
  (format t "~A~%" ans))

Score : 300 points

Problem Statement

We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.

Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

s_{ia} \neq s_{ib} (a \neq b)

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

Sample Input 2

2 3
2 1 2
1 1
1 2
0 0 1

Sample Output 2

0

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an even number of switches that are "on" among the following: Switch 1.

Bulb 3 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

Switch 1 has to be "off" to light Bulb 2 and Switch 2 has to be "on" to light Bulb 3, but then Bulb 1 will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print 0.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


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

(defun gene-switch-type (n)
  (let ((line (loop repeat n collect 0))
        (res))
    (labels ((f (lst thunk)
               (if lst
                   (progn
                     (setf (car lst) 0)
                     (f (cdr lst) thunk)
                     (setf (car lst) 1)
                     (f (cdr lst) thunk))
                   (funcall thunk))))
      (f line (lambda () (push (coerce line 'vector) res)))
      res)))

(defun check (lights switch-type sums)
  (let ((n (length lights)))
    (dotimes (i n)
      (unless (= (aref sums i)
                 (mod (loop for j in (aref lights i)
                       sum (aref switch-type j)) 2))
        (return-from check nil))))
  t)

(defun main (n m lights sum)
  (loop for switch-type in (gene-switch-type n)
        sum
        (if (check lights switch-type sum) 1 0)))

(let* ((n (read))
       (m (read))
       (lights (coerce (loop repeat m collect
                                      (loop repeat (read) collect (1- (read))))
                       'vector))
       (sum (coerce (loop repeat m collect (read)) 'vector)))
  (princ (main n m lights sum)))


(defun split (input stack-string output-list)
  (let ((chara (car input)))
    (case chara
          ((nil) (append output-list (list stack-string)))
          (#\space (split (cdr input)
                                  '()
                                  (append output-list (list stack-string))))
          (otherwise (split (cdr input)
                                    (concatenate 'string stack-string (list chara))
                                    output-list)))))

(defun input-to-list (input)
  (mapcar #'parse-integer (split (concatenate 'list input)
                                 '()
                                 '())))

(defparameter nk (input-to-list (read-line)))
(defparameter v (input-to-list (read-line)))

(defun num-pat (num len)
  (labels ((inner (num cnt lst)
                  (if (eq cnt len)
                      lst
                      (inner (truncate num 4) (1+ cnt) (cons (mod num 4) lst)))))
          (inner num 0 '())))

(defun dot (lst1 lst2)
  (reduce #'+ (mapcar #'* lst1 lst2)))

(defun lastvalue (pattern column hand)
  (if pattern
      (case (car pattern)
            (0 (if column
                   (lastvalue (cdr pattern) (cdr column) (cons (first column) hand))
                   (lastvalue (cdr pattern) column hand)))
            (1 (if column
                   (lastvalue (cdr pattern) (subseq column 0 (1- (length column))) (cons (car (last column)) hand))
                   (lastvalue (cdr pattern) column hand)))
            (2 (if hand
                   (let ((mi (apply #'min hand))) (lastvalue (cdr pattern) (cons mi column) (remove mi hand)))
                   (lastvalue (cdr pattern) column hand)))
            (3 (if hand
                   (let ((mi (apply #'min hand))) (lastvalue (cdr pattern) (append `(,mi) column) (remove mi hand)))
                   (lastvalue (cdr pattern) column hand)))
            (otherwise (princ "error")))
      (if hand
          (reduce #'+ hand)
          0)))

(princ (apply #'max (loop for i from 0 to (cadr nk)
                  collect (apply #'max (loop for j from 0 to (1- (expt 4 i))
                                collect (lastvalue (num-pat j (cadr nk)) v '()))))))

Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.


(defun split (input stack-string output-list)
  (let ((chara (car input)))
    (case chara
          ((nil) (append output-list (list stack-string)))
          (#\space (split (cdr input)
                                  '()
                                  (append output-list (list stack-string))))
          (otherwise (split (cdr input)
                                    (concatenate 'string stack-string (list chara))
                                    output-list)))))

(defun input-to-list (input)
  (mapcar #'parse-integer (split (concatenate 'list input)
                                 '()
                                 '())))

(defparameter nk (input-to-list (read-line)))
(defparameter v (input-to-list (read-line)))

(defun num-pat (num len)
  (labels ((inner (num cnt lst)
                  (if (eq cnt len)
                      lst
                      (inner (truncate num 4) (1+ cnt) (cons (mod num 4) lst)))))
          (inner num 0 '())))

(defun dot (lst1 lst2)
  (reduce #'+ (mapcar #'* lst1 lst2)))

(defun lastvalue (pattern column hand)
  (if pattern
      (case (car pattern)
            (0 (if column
                   (lastvalue (cdr pattern) (cdr column) (cons (first column) hand))
                   (lastvalue (cdr pattern) column hand)))
            (1 (if column
                   (lastvalue (cdr pattern) (subseq column 0 (1- (length column))) (cons (car (last column)) hand))
                   (lastvalue (cdr pattern) column hand)))
            (2 (if hand
                   (let ((mi (apply #'min hand))) (lastvalue (cdr pattern) (cons mi column) (remove mi hand)))
                   (lastvalue (cdr pattern) column hand)))
            (3 (if hand
                   (let ((mi (apply #'min hand))) (lastvalue (cdr pattern) (append `(,mi) column) (remove mi hand)))
                   (lastvalue (cdr pattern) column hand)))
            (t (princ "error")))
      (if hand
          (reduce #'+ hand)
          0)))

(princ (apply #'max (loop for i from 0 to (cadr nk)
                  collect (apply #'max (loop for j from 0 to (1- (expt 4 i))
                                collect (lastvalue (num-pat j (cadr nk)) v '()))))))


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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (let* ((n (read))
         (k (read))
         (vs (make-array n :element-type 'int32))
         (res 0))
    (dotimes (i n) (setf (aref vs i) (read)))
    (labels ((strip (list r)
               (declare (uint32 r))
               (if (or (zerop r)
                       (null list)
                       (>= (the fixnum (car list)) 0))
                   list
                   (strip (cdr list) (- r 1))))
             (frob (x y r)
               (declare (uint32 x y r))
               (let (list)
                 (loop for i below x do (push (aref vs i) list))
                 (loop for i from (- n 1) downto (- n y) do (push (aref vs i) list))
                 (strip (sort list #'<) r))))
      (loop for x to (min n k)
            do (loop for y from 0 to (min (- k x) (- n x))
                     do (let ((r (max 0 (- k x y))))
                           (let ((list (frob x y r)))
                             (setf res (max res (reduce #'+ list :initial-value 0)))))))
      (println res))))

#-swank(main)

;; For Test
#+swank
(defun io-equal (in-string out-string &optional (func #'main))
  (labels ((ensure-last-lf (s)
             (if (and (> (length s) 0)
                      (eql (char s (- (length s) 1)) #\Linefeed))
                 s
                 (uiop:strcat s uiop:+lf+))))
    (equal (ensure-last-lf out-string)
           (with-output-to-string (out)
             (let ((*standard-output* out))
               (with-input-from-string (*standard-input* (ensure-last-lf in-string))
                 (funcall func)))))))

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

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

#+swank
(defun run (&optional thing (out *standard-output*))
  (let ((*standard-output* out))
    (etypecase thing
      (null ; Runs #'MAIN with the string on clipboard
       (with-input-from-string (*standard-input* (delete #\Return (get-clipbrd)))
         (main)))
      (string
       (with-input-from-string (*standard-input* (delete #\Return thing))
         (main)))
      (symbol (5am:run! thing))
      (pathname ; Runs #'MAIN with the string in a text file
       (with-open-file (*standard-input* thing)
         (main))))))

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

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

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


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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (let* ((n (read))
         (k (read))
         (vs (make-array n :element-type 'int32))
         (res 0))
    (dotimes (i n) (setf (aref vs i) (read)))
    (labels ((strip (list r)
               (declare (uint32 r))
               (if (or (zerop r)
                       (null list)
                       (>= (the fixnum (car list)) 0))
                   list
                   (strip (cdr list) (- r 1))))
             (frob (x y r)
               (declare (uint32 x y r))
               (let (list)
                 (loop for i below x do (push (aref vs i) list))
                 (loop for i from (- n 1) downto (- n y) do (push (aref vs i) list))
                 (strip (sort list #'<) r))))
      (loop for x to (min n k)
            do (loop for y from 0 to (min (- k x) (- n x))
                     do  (let ((r (min (- k x y) (- n x y))))
                           (let ((list (frob x y r)))
                             (setf res (max res (reduce #'+ list :initial-value 0)))))))
      (println res))))

#-swank(main)

;; For Test
#+swank
(defun io-equal (in-string out-string &optional (func #'main))
  (labels ((ensure-last-lf (s)
             (if (and (> (length s) 0)
                      (eql (char s (- (length s) 1)) #\Linefeed))
                 s
                 (uiop:strcat s uiop:+lf+))))
    (equal (ensure-last-lf out-string)
           (with-output-to-string (out)
             (let ((*standard-output* out))
               (with-input-from-string (*standard-input* (ensure-last-lf in-string))
                 (funcall func)))))))

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

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

#+swank
(defun run (&optional thing (out *standard-output*))
  (let ((*standard-output* out))
    (etypecase thing
      (null ; Runs #'MAIN with the string on clipboard
       (with-input-from-string (*standard-input* (delete #\Return (get-clipbrd)))
         (main)))
      (string
       (with-input-from-string (*standard-input* (delete #\Return thing))
         (main)))
      (symbol (5am:run! thing))
      (pathname ; Runs #'MAIN with the string in a text file
       (with-open-file (*standard-input* thing)
         (main))))))

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

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

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


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (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 with-output-buffer (&body body)
  "Buffers all outputs to *STANDARD-OUTPUT* in BODY and flushes them to
*STANDARD-OUTPUT* after BODY has been done (without error). Note that only
BASE-CHAR is allowed."
  (let ((out (gensym)))
    `(let ((,out (make-string-output-stream :element-type 'base-char)))
       (let ((*standard-output* ,out))
         ,@body)
       (write-string (get-output-stream-string ,out)))))

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

(setf *print-circle* t)

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

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

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

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

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

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

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

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

(defun treap-bisect (key treap)
  (declare #.OPT ((or null treap) treap))
  (labels ((recur (treap)
             (unless treap (return-from recur nil))
             (force-down treap)
             (if (treap-order key (%treap-key treap))
                 (recur (%treap-left treap))
                 (or (recur (%treap-right treap))
                     treap))))
    (let ((result (recur treap)))
      (if result
          (values (%treap-key result) (%treap-value result))
          (values nil nil)))))

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

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

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

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

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

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

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

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

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (q (read))
         (ss (make-array n :element-type 'uint32))
         (ts (make-array n :element-type 'uint32))
         (xs (make-array n :element-type 'uint32))
         treap)
    (declare (uint31 n q))
    (dotimes (i n)
      (let ((s (read-fixnum))
            (end (read-fixnum))
            (x (read-fixnum)))
        (setf (aref ss i) s
              (aref ts i) end
              (aref xs i) x)
        (setf treap (treap-ensure-key (- s x) most-positive-fixnum treap))
        (setf treap (treap-ensure-key (- end x) most-positive-fixnum treap))))
    (setf treap (treap-insert most-positive-fixnum most-positive-fixnum treap))
    (setf treap (treap-insert most-negative-fixnum most-positive-fixnum treap))
    (dotimes (i n)
      (setf treap
            (treap-update treap
                          (aref xs i)
                          (- (aref ss i) (aref xs i))
                          (- (aref ts i) (aref xs i)))))
    (with-output-buffer
      (dotimes (i q)
        (let* ((d (read-fixnum))
               (res (nth-value 1 (treap-bisect d treap))))
          (println
           (if (< (the fixnum res) most-positive-fixnum)
               res
               -1)))))))

#-swank(main)

Score : 500 points

Problem Statement

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

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

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

Find the distance each of the Q people will walk.

Constraints

All values in input are integers.

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

0 \leq S_i < T_i \leq 10^9

1 \leq X_i \leq 10^9

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

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

2
2
10
-1
13
-1

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

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

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


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

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

(setf *print-circle* t)

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

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

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

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

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

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

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

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

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

(defun treap-bisect (key treap)
  (declare #.OPT ((or null treap) treap))
  (labels ((recur (treap)
             (unless treap (return-from recur nil))
             (force-down treap)
             (if (treap-order key (%treap-key treap))
                 (recur (%treap-left treap))
                 (or (recur (%treap-right treap))
                     treap))))
    (let ((result (recur treap)))
      (if result
          (values (%treap-key result) (%treap-value result))
          (values nil nil)))))

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

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

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

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

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

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

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

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

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (q (read))
         (ss (make-array n :element-type 'uint32))
         (ts (make-array n :element-type 'uint32))
         (xs (make-array n :element-type 'uint32))
         treap)
    (declare (uint31 n q))
    (dotimes (i n)
      (let ((s (read-fixnum))
            (end (read-fixnum))
            (x (read-fixnum)))
        (setf (aref ss i) s
              (aref ts i) end
              (aref xs i) x)
        (setf treap (treap-ensure-key (- s x) most-positive-fixnum treap))
        (setf treap (treap-ensure-key (- end x) most-positive-fixnum treap))))
    (setf treap (treap-insert most-positive-fixnum most-positive-fixnum treap))
    (setf treap (treap-insert most-negative-fixnum most-positive-fixnum treap))
    (dotimes (i n)
      (setf treap
            (treap-update treap
                          (aref xs i)
                          (- (aref ss i) (aref xs i))
                          (- (aref ts i) (aref xs i)))))

    (with-output-buffer
      (dotimes (i q)
        (let* ((d (read-fixnum))
               (res (nth-value 1 (treap-bisect d treap))))
          (if (< (the fixnum res) most-positive-fixnum)
              (println res)
              (println -1)))))))

#-swank(main)


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

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

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

(setf *print-circle* t)

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

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

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

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

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

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

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

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

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

(defun treap-bisect-left (key treap)
  (declare #.OPT ((or null treap) treap))
  (labels ((recur (treap)
             (unless treap (return-from recur nil))
             (force-down treap)
             (if (treap-order (%treap-key treap) key)
                 (recur (%treap-right treap))
                 (or (recur (%treap-left treap))
                     treap))))
    (let ((result (recur treap)))
      (if result
          (values (%treap-key result) (%treap-value result))
          (values nil nil)))))

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

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

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

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

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

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

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

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

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (q (read))
         (ds (make-array q :element-type 'uint32))
         (ss (make-array n :element-type 'uint32))
         (ts (make-array n :element-type 'uint32))
         (xs (make-array n :element-type 'uint32))
         treap)
    (declare (uint31 n q))
    (dotimes (i n)
      (let ((s (read-fixnum))
            (end (read-fixnum))
            (x (read-fixnum)))
        (setf (aref ss i) s
              (aref ts i) end
              (aref xs i) x)
        (setf treap (treap-ensure-key (- s x) most-positive-fixnum treap))
        (setf treap (treap-ensure-key (- end x) most-positive-fixnum treap))))
    (setf treap (treap-insert most-positive-fixnum most-positive-fixnum treap))
    (setf treap (treap-insert most-negative-fixnum most-positive-fixnum treap))
    (dotimes (i q)
      (let ((d (read-fixnum)))
        (setf (aref ds i) d)))
    (dotimes (i n)
      (setf treap
            (treap-update treap
                          (aref xs i)
                          (- (aref ss i) (aref xs i))
                          (- (aref ts i) (aref xs i)))))

    (with-output-buffer
      (dotimes (i q)
        (let* ((d (aref ds i))
               (res (nth-value 1 (treap-bisect-left d treap))))
          (if (< (the fixnum res) most-positive-fixnum)
              (println res)
              (println -1)))))))

#-swank(main)


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

;; BEGIN_INSERTED_CONTENTS
(declaim (inline delete-adjacent-duplicates))
(defun delete-adjacent-duplicates (seq &key (test #'eql))
  "Destructively deletes adjacent duplicates of SEQ: e.g. #(1 1 1 2 2 1 3) ->
#(1 2 1 3)"
  (declare (sequence seq)
           (function test))
  (etypecase seq
    (vector
     (if (zerop (length seq))
         seq
         (let ((prev (aref seq 0))
               (end 1))
           (loop for pos from 1 below (length seq)
                 unless (funcall test prev (aref seq pos))
                 do (setf prev (aref seq pos)
                          (aref seq end) (aref seq pos)
                          end (+ 1 end)))
           (adjust-array seq end))))
    (list
     (loop for rest on seq
           unless (and (cdr rest)
                       (funcall test (first rest) (second rest)))
           collect (car rest)))))

(declaim (inline make-reverse-lookup-table))
(defun make-reverse-lookup-table (vector &key (test #'eql))
  "Assigns each value of the (usually sorted) VECTOR of length n to the integers
0, ..., n-1."
  (let ((table (make-hash-table :test test :size (length vector))))
    (dotimes (i (length vector) table)
      (setf (gethash (aref vector i) table) i))))

(setf *print-circle* t)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(declaim (inline itreap-delete))
(defun itreap-delete (itreap index)
  (declare ((integer 0 #.most-positive-fixnum) index))
  (unless (< index (itreap-count itreap))
    (error 'invalid-itreap-index-error :itreap itreap :index index))
  (multiple-value-bind (itreap1 itreap2)
      (itreap-split itreap (1+ index))
    (multiple-value-bind (itreap1 _)
        (itreap-split itreap1 index)
      (declare (ignore _))
      (itreap-merge itreap1 itreap2))))

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

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

(declaim (inline itreap-update))
(defun itreap-update (itreap x l r)
  "Updates ITREAP[i] := (OP ITREAP[i] X) for all i in [l, r)"
  (declare ((integer 0 #.most-positive-fixnum) l r))
  (unless (<= l r (itreap-count itreap))
    (error 'invalid-itreap-index-error :itreap itreap :index (cons l r)))
  (multiple-value-bind (itreap-0-l itreap-l-n)
      (itreap-split itreap l)
    (multiple-value-bind (itreap-l-r itreap-r-n)
        (itreap-split itreap-l-n (- r l))
      (when itreap-l-r
        (setf (%itreap-lazy itreap-l-r)
              (updater-op (%itreap-lazy itreap-l-r) x)))
      (itreap-merge itreap-0-l (itreap-merge itreap-l-r itreap-r-n)))))

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT (inline sort))
  (let* ((n (read))
         (q (read))
         (ds (make-array q :element-type 'uint32))
         (ss (make-array n :element-type 'uint32))
         (ts (make-array n :element-type 'uint32))
         (xs (make-array n :element-type 'uint32))
         (table (make-array 0 :element-type 'int32 :fill-pointer 0)))
    (dotimes (i n)
      (let ((s (read-fixnum))
            (end (read-fixnum))
            (x (read-fixnum)))
        (setf (aref ss i) s
              (aref ts i) end
              (aref xs i) x)
        (vector-push-extend (- s x) table)
        (vector-push-extend (- end x) table)))
    (dotimes (i q)
      (let ((d (read-fixnum)))
        (setf (aref ds i) d)
        (vector-push-extend d table)))
    (setf table (sort table #'<))
    (let ((revs (make-reverse-lookup-table table))
          (itreap (make-itreap (length table))))
      (dotimes (i n)
        (itreap-update itreap (aref xs i)
                       (gethash (- (aref ss i) (aref xs i)) revs)
                       (gethash (- (aref ts i) (aref xs i)) revs)))
      (dotimes (i q)
        (let ((d (aref ds i)))
          (let ((q (itreap-ref itreap (gethash d revs))))
            (if (< q most-positive-fixnum)
                (println q)
                (println -1))))))))

#-swank(main)

;; For Test
#+swank
(defun io-equal (in-string out-string &optional (func #'main))
  (labels ((ensure-last-lf (s)
             (if (and (> (length s) 0)
                      (eql (char s (- (length s) 1)) #\Linefeed))
                 s
                 (uiop:strcat s uiop:+lf+))))
    (equal (ensure-last-lf out-string)
           (with-output-to-string (out)
             (let ((*standard-output* out))
               (with-input-from-string (*standard-input* (ensure-last-lf in-string))
                 (funcall func)))))))

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

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

#+swank
(defun run (&optional thing (out *standard-output*))
  (let ((*standard-output* out))
    (etypecase thing
      (null ; Runs #'MAIN with the string on clipboard
       (with-input-from-string (*standard-input* (delete #\Return (get-clipbrd)))
         (main)))
      (string
       (with-input-from-string (*standard-input* (delete #\Return thing))
         (main)))
      (symbol (5am:run! thing))
      (pathname ; Runs #'MAIN with the string in a text file
       (with-open-file (*standard-input* thing)
         (main))))))

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

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

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


(defun split (input stack-string output-list)
  (let ((chara (car input)))
    (case chara
          ((nil) (append output-list (list stack-string)))
          (#\space (split (cdr input)
                                  '()
                                  (append output-list (list stack-string))))
          (otherwise (split (cdr input)
                                    (concatenate 'string stack-string (list chara))
                                    output-list)))))

(defun input-to-list (input)
  (mapcar #'parse-integer (split (concatenate 'list input)
                                 '()
                                 '())))
(defparameter param (input-to-list (readline)))
(princ (cond ((<= (car param) 5) 0)
  ((and (<= (car param) 12)
        (>= (car param) 6)) (/ (cadr param) 2))
  (t (cadr param))))

Score : 100 points

Problem Statement

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

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

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

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

Sample Input 2

12 100

Sample Output 2

50

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

Sample Input 3

0 100

Sample Output 3

0

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


(defun _ferris (a b)
  (cond ((<= a 5) 0)
        ((and (<= 6 a) (<= a 12)) (floor b 2))
        (t b)))

(defun ferris(a b)
  (print (_ferris a b)))

#|
(ferris 30 100)
(ferris 12 100)
(ferris 0 100)
|#
(let ((a (read))
      (b (read)))
  (ferris a b))


(defun solve (r d x)
  (loop for i below 10
        do (setf x (- (* r x) d))
        do (format t "~A~%" x)))
(solve (read) (read) (read))

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

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

x_{i+1} = rx_i - D

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

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

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

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

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

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


(defun next (r d xi c)
  (if (> c 9)
    xi
    (progn (format t "~a~%" (- (* r xi) d)) (next r d (- (* r xi) d) (1+ c)))))

(next (read) (read) (read) 0)


(defun solve (r d x i) (print (- (* r x ) d)) (if (equal i 9) () (solve r d ( - ( * r x ) d ) (+ i 1))))

(setq r (read))
(setq d (read))
(solve r d (read) 0)


(defvar N (read))

(loop repeat (read)
      with maxL = 0
      and minR = (1+ N)
      and L and R
      do
      (setf L (read)
            R (read))
      (if (> L maxL) (setf maxL L))
      (if (< R minR) (setf minR R))
      finally (princ (max (1+ (- minR maxL)) 0)))

Score : 300 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

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

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

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

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

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

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

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

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


(defun _prison (n m lst)
  (let* ((lr (reduce #'(lambda (a b)
                         (let ((a-l (car a))
                               (a-r (cdr a))
                               (b-l (car b))
                               (b-r (cdr b)))
                           ;(print `(:e ,a-l ,a-r ,b-l ,b-r))
                           (cons
                             (max a-l b-l)
                             (min a-r b-r)))) lst :initial-value `(1 . ,n)))
         (max-l (car lr))
         (min-r (cdr lr)))
    ;(print lr)
    (if (> max-l min-r) 0
      (+ (- min-r max-l) 1))))

(defun prison (n m lst)
  (print (_prison n m lst)))

#|
(prison 4 2
         '((1 . 3) (2 . 4)))

(prison 10 2
         '((3 . 6) (5 . 7) (6 . 9)))

(prison 100000 1
         '((1 . 100000)))
|#

(let* ((n (read))
       (m (read))
       (lst (labels ((read-m (my-m rv)
                             (if (= my-m 0) (nreverse rv)
                               (let ((l (read))
                                     (r (read)))
                               (read-m (- my-m 1) (cons (cons l r) rv))))))
              (read-m m nil))))
  ;(print lst)
  (prison n m lst))


(let* ((n (read))
       (m (read))
       (arr (make-array n :initial-element 0 :element-type 'fixnum))
       (gatea (make-array m :initial-element 0 :element-type 'fixnum))
       (gateb (make-array m :initial-element 0 :element-type 'fixnum)))
  (loop :for a :from 0 :upto (1- m) :do(setf (aref gatea a) (1- (read)))
        :do(setf (aref gateb a) (1- (read))))
  (map nil (lambda (a b) (loop :for x :from a :upto b :do(setf (aref arr x) (1+ (aref arr x))))) gatea gateb)
  (princ (count m arr)))


(defun _int-cards (n m lst m-lst)
  (let ((new-m-lst (sort m-lst #'(lambda (a b)
                                  (let ((a0 (car a))
                                        (b0 (car b)))
                                    (> a0 b0))))))
    (labels ((all-m-lst (_m-lst sum-m rv)
                        (if (or (null _m-lst) (>= sum-m n)) rv
                          (let* ((elm (car _m-lst))
                                 (b (car elm))
                                 (c (cdr elm))
                                 (new-lst (make-list b :initial-element c)))
                            (all-m-lst (cdr _m-lst) (+ sum-m b) (append rv new-lst))))))
      ;(print new-m-lst)
      (let ((all-lst (append lst (all-m-lst new-m-lst 0 nil))))
        (apply #'+
               (subseq (sort all-lst #'>)  0 n))))))

(defun int-cards (n m lst m-lst)
  (print (_int-cards n m lst m-lst)))

#|
(int-cards 3 2 '(5 1 4) '((2 . 3) (1 . 5)))
(int-cards 10 2 '(1 8 5 7 100 4 52 33 13 5) '((2 . 10) (4 . 30) (1 . 4)))
(int-cards 3 2 '(100 100 100) '((3 . 99) (3 . 99) ))
(int-cards 11 4 '(1 1 1 1 1 1 1 1 1 1 1) '((3 . 10000000000) (4 . 10000000000) (3 . 10000000000 )))
|#

(let* ((n (read))
       (m (read))
       (lst (labels ((read-n (my-n rv)
                             (if (= my-n 0) (nreverse rv)
                               (let ((a (read)))
                                 (read-n (- my-n 1) (cons a rv))))))
              (read-n n nil)))
       (m-lst (labels ((read-m (my-m rv)
                               (if (= my-m 0) (nreverse rv)
                                 (let ((b (read))
                                       (c (read)))
                                   (read-m (- my-m 1) (cons (cons b c) rv))))))
                (read-m m nil))))
  (int-cards n m lst m-lst))

Score : 400 points

Problem Statement

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

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

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

Sample Input 2

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

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

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

Sample Output 4

10000000001

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


(defun munipulate (bj cj as)
  (labels ((rec (lst n acc)
             (if (or (<= cj (car lst)) (<= n 0))
                 (nconc acc lst)
                 (rec (cdr lst) (1- n) (cons cj acc)))))
    (rec as bj '())))

(let ((n (read))
      (m (read)))
  (let ((as (sort (loop repeat n collect (read)) #'<=))
        (bcs (loop repeat m collect (cons (read) (read)))))
    (loop for bc in bcs
          do (let ((b (car bc))
                   (c (cdr bc)))
               (setf as (munipulate b c as))))
    (apply #'+ as)))