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

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

(setq *n* (read))
(setq *v* (make-array *n* :initial-contents (mapcar #'parse-integer (split " " (read-line)))))
(setq *c* (make-array *n* :initial-contents (mapcar #'parse-integer (split " " (read-line)))))

(setq *gains* nil)

(defun dfs (gain i)
  (let ((next-gain gain) (result nil))
      (if (>= i *n*)
        (setq *gains* (cons gain *gains*))
        (dotimes (n 2 result)
                 ;(print (list "next-gain " next-gain (aref *v* i) (aref *c* i)))
                 (when (= n 1) (setq next-gain (+ gain (- (aref *v* i) (aref *c* i)))))
                 (setq result (dfs next-gain (1+ i)))))))

  (dfs 0 0)
  (print (apply #'max *gains*))

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


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

(setq *n* (read))
(setq *v* (mapcar #'parse-integer (split " " (read-line))))
(setq *c* (mapcar #'parse-integer (split " " (read-line))))
(setq *f* 0)

(dotimes (bit (ash 1 *n*))
         (let ((tmp 0))
               (dotimes (i *n*)
                        (when
                          (= 1 (logand 1 (ash bit (* -1 i))))
                          (setq tmp (+ tmp (- (nth i *v*) (nth i *c*))))))
         (when (> tmp *f*)
           (setq *f* tmp))))

(print *f*)

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.


(let ((n (read))
      (a (make-array 0 :element-type 'integer
                       :adjustable t
                       :fill-pointer 0))
      (ans 0)
      temp)
     (dotimes (i n)
       (vector-push-extend (read) a))
     (dotimes (i n)
       (setf temp (read))
       (if (< 0 (- (aref a i) temp)) (incf ans (- (aref a i) temp))))
     (princ ans))


(let ((a (read))
     (b (read))
     (c (read)))
(princ(if (and (< (max a b) c) (> (min a b))) "Yes" "No")))

Score : 100 points

Problem Statement

There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively.
Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Constraints

0\leq A,B,C\leq 100

A, B and C are distinct integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Sample Input 1

3 8 5

Sample Output 1

Yes

We pass the coordinate 5 on the straight way from the house at coordinate 3 to the house at coordinate 8.

Sample Input 2

7 3 1

Sample Output 2

No

Sample Input 3

10 2 4

Sample Output 3

Yes

Sample Input 4

31 41 59

Sample Output 4

No


(let ((n (read))
    (s (read-line))
    (k (read))
    (a ""))
    (setq a (char s (- k 1)))
    (loop for char across s do
        (if (char= char a)
            (format t "~A" a)
            (format t "*")
        )
    )
    (format t "~%")
)

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters, and an integer K.
Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Constraints

1 \leq K \leq N\leq 10

S is a string of length N consisting of lowercase English letters.

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of S is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


(defun solve (n s)
  (let ((x (position #\# s))
        (y (count #\. s)))
    (if (null x)
        0
        (- y x))))
(format t "~A~%" (solve (read) (read-line)))

Score : 300 points

Problem Statement

There are N stones arranged in a row. Every stone is painted white or black.
A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

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

S is a string of length N consisting of . and #.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


(defparameter n (read))
(defparameter s (coerce (read-line) 'list))

(defun f (lst acc# acc)
  (cond ((or (endp lst)
             (endp (cdr lst)))
         acc)
        ((and (char= #\. (car lst))
              (char= #\# (cdr lst)))
         (f (cdr lst) acc# (cons (+ acc# (count #\. (cdr lst))) acc)))
        ((char= #\# (car lst))
         (f (cdr lst) (1+ acc#) acc))
        (t (f (cdr lst) acc# acc))))

(format t "~a" (f s 0 '()))


; ABC124-A
(defun max2(a b)
  (if (> a b) a b)
  )

(defun solve(a b)
  (setq r1 (max2 a b))
  (setq r2 (if (> a b) (max2 (- a 1) b) (max2 a (- b 1))))
  (+ r1 r2)
  )

(let ((a (read)) (b (read)))
  (format t "~d~%" (solve a b))
  )

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


(defun window-sumlist (list windowsize)
  (labels ((mappedreduce (function sequence)
             (if (= 1 (length sequence))
                 (list (elt sequence 0))
                 (let* ((n (elt sequence 0)))
                   (mapcar (lambda (x) (setf n (funcall function n x)))
                           (subseq sequence 1))))))
    (let* ((lst-k (cons 0 (cons (car list) (mappedreduce #'+ list)))))
      (loop :for k :in (subseq lst-k windowsize)
            :for l :in lst-k
            :collect (- k l)))))

(window-sumlist '(1 2 4 8 16) 3)

(defun compressor (list)
  (let* ((ret nil))
    (map 'nil (lambda (x)
                (if (and ret (equal x (caar ret)))
                    (incf (cdar ret))
                    (push (cons x 1) ret)))
         list)
    ret))
(let* ((n (read))
       (m (read))
       (lst (mapcar #'cdr (compressor (read-line)))))
  (princ (reduce #'max (window-sumlist lst (1+ (* 2 m))))))

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


(defparameter abcde
  (loop repeat 5
        collect (read)))

(defun f (abcde)
  (+ (* 10 (1- (loop for i in abcde
                     sum (ceiling i 10))))
     (reduce #'min
             (remove 0 (mapcar (lambda (i) (mod i 10))
                               abcde)))))

(princ (f abcde))

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


Score : 100 points

Problem Statement

You are given three integers A, B and C.

Determine if there exists an equilateral triangle whose sides have lengths A, B and C.

Constraints

All values in input are integers.

1 \leq A,B,C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

If there exists an equilateral triangle whose sides have lengths A, B and C, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

There exists an equilateral triangle whose sides have lengths 2, 2 and 2.

Sample Input 2

3 4 5

Sample Output 2

No

There is no equilateral triangle whose sides have lengths 3, 4 and 5.


(let ((n (read))
      (s (read-line)))
     (princ (if (< (count #\B s) (count #\R s)) "Yes" "No")))

Score : 200 points

Problem Statement

There are N people numbered 1 to N. Each person wears a red hat or a blue hat.

You are given a string s representing the colors of the people. Person i wears a red hat if s_i is R, and a blue hat if s_i is B.

Determine if there are more people wearing a red hat than people wearing a blue hat.

Constraints

1 \leq N \leq 100

|s| = N

s_i is R or B.

Input

Input is given from Standard Input in the following format:

N
s

Output

If there are more people wearing a red hat than there are people wearing a blue hat, print Yes; otherwise, print No.

Sample Input 1

4
RRBR

Sample Output 1

Yes

There are three people wearing a red hat, and one person wearing a blue hat.

Since there are more people wearing a red hat than people wearing a blue hat, the answer is Yes.

Sample Input 2

4
BRBR

Sample Output 2

No

There are two people wearing a red hat, and two people wearing a blue hat.

Since there are as many people wearing a red hat as people wearing a blue hat, the answer is No.


(let ((n (read))
      (lst (concatenate 'list (read-line))))
  (if (> (count #\R lst :test #'char=) (count #\B lst :test #'char=))
      (princ "Yes")
      (princ "No")))


(defparameter n (read))
(defparameter q (read))
(defparameter address (read-line))
(defparameter magic-words
  (loop repeat q
        collect (list (character (read)) (character (read)))))

(defparameter golem-vector
  (make-array n :initial-element 1))

(defun char-positions (char string)
  (declare (optimize (speed 3) (debug 0) (safety 0)))
  (let ((n (length string)))
    (labels ((rec (index acc)
               (cond ((< index 0) acc)
                     ((char= char (char string index))
                      (rec (1- index) (cons index acc)))
                     (t (rec (1- index) acc)))))
      (rec (1- n) nil))))

(defun f (size golem-vector address magic-words)
  (loop for magic-word in magic-words
        do (destructuring-bind (ti di) magic-word
             (let ((positions (char-positions ti address)))
               (mapc (lambda (pos)
                       (let ((cur-pos-golems (svref golem-vector pos))
                             (r-pos (1- pos))
                             (l-pos (1+ pos)))
                         (cond ((and (char= di #\R)
                                     (<= 0 r-pos (1- size)))
                                (incf (svref golem-vector r-pos)
                                      cur-pos-golems))
                               ((and (char= di #\L)
                                     (<= 0 r-pos (1- size)))
                                (incf (svref golem-vector l-pos)
                                      cur-pos-golems)))
                         (setf (svref golem-vector pos) 0)))
                     positions))))
  golem-vector)

(defun vector-sum (vector)
  (let ((n (length vector)))
    (labels ((rec (i acc)
               (if (zerop i)
                   acc
                   (rec (1- i) (+ (svref vector (1- i)) acc)))))
      (rec n 0))))

(princ (vector-sum (f n golem-vector address magic-words)))

Score : 500 points

Problem Statement

There are N squares numbered 1 to N from left to right.
Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.

Snuke cast Q spells to move the golems.

The i-th spell consisted of two characters t_i and d_i, where d_i is L or R.
When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is L, and moved to the square adjacent to the right if d_i is R.

However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.

Find the number of golems remaining after Snuke cast the Q spells.

Constraints

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

|s| = N

s_i and t_i are uppercase English letters.

d_i is L or R.

Input

Input is given from Standard Input in the following format:

N Q
s
t_1 d_1
\vdots
t_{Q} d_Q

Output

Print the answer.

Sample Input 1

3 4
ABC
A L
B L
B R
A R

Sample Output 1

2

Initially, there is one golem on each square.

In the first spell, the golem on Square 1 tries to move left and disappears.

In the second spell, the golem on Square 2 moves left.

In the third spell, no golem moves.

In the fourth spell, the golem on Square 1 moves right.

After the four spells are cast, there is one golem on Square 2 and one golem on Square 3, for a total of two golems remaining.

Sample Input 2

8 3
AABCBDBA
A L
B R
A R

Sample Output 2

5

After the three spells are cast, there is one golem on Square 2, two golems on Square 4 and two golems on Square 6, for a total of five golems remaining.

Note that a single spell may move multiple golems.

Sample Input 3

10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L

Sample Output 3

3


(let ((b (read-char)))
(if (string= b "A")
(princ "T")
)
(if (string= b "T")
(princ "A")
)
(if (string= b "C")
(princ "G")
)
(if (string= b "G")
(princ "C")
)
)

Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


(let ((s (read-line)))
     (case s
       ("A" (princ "T"))
       ("T" (princ "A"))
       ("G" (princ "C"))
       ("C" (princ "G"))))
(fresh-line)


(princ
 (if (equal "A" (setq b (read))) "T"
	(if (equal "T" b) "A"
	 (if (equal "C" b) "G"
		(if (equal "G" b) "C"
		)))))


(let* ((lst (concatenate 'list (read-line)))
       (k '()))
  (loop :for a :from 0 :upto (1- (length lst) ) :do
    (loop :for b :from a :upto (- (1- (length lst) ) a)
          :do(let* ((n (nth b lst)))
               (cond ((char= n #\A) t)
                     ((char= n #\T) t)
                     ((char= n #\C) t)
                     ((char= n #\G) t)
                     (t (progn (push (- b a) k) (loop-finish)))))))
  (princ (reduce #'max k)))

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

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

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


(let* ((n (read))
       (m (read))
       (str (read-line))
       (lst (loop :repeat m :collect (cons (read) (read)))))
  (defun f (p q)
    (let* ((k (search "AC" p :start2 q)))
      (if k (f p (1+ k)) q)))
  (map nil (lambda (a)
             (print (floor (f (subseq str (1- (car a)) (cdr a)) 0) 2))) lst))

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


(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 buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (terminate-char #\Space))
  "Note that the returned string will be reused."
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let ((,buffer (load-time-value (make-string ,buffer-size
                                                  :element-type 'base-char))))
       (declare (simple-base-string ,buffer))
       (loop for ,character 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= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (when (< ,idx ,buffer-size)
                       (setf (schar ,buffer ,idx) ,terminate-char))
                     (return (values ,buffer ,idx))))))

(defmacro split-ints-bind (vars string &body body)
  (let ((position (gensym))
        (s (gensym)))
    (labels ((expand (vars &optional init-pos)
               (if (null vars)
                   body
                   `((multiple-value-bind (,(car vars) ,position)
                         (parse-integer ,s :start ,(or init-pos position)
                                           :junk-allowed t)
                       ,@(when (null (cdr vars)) `((declare (ignore ,position))))
                       ,@(expand (cdr vars)))))))
      `(let ((,s ,string))
         (declare (string ,s))
         ,@(expand vars 0)))))

(declaim (inline read-line-into))
(defun read-line-into (buffer-string &key (in *standard-input*) (terminate-char #\Space))
  (declare (simple-base-string buffer-string))
  (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 (schar buffer-string idx) c)
        finally (when (< idx (length buffer-string))
                  (setf (schar buffer-string idx) terminate-char))
                (return (values buffer-string idx))))

(defmacro dbg (&rest forms)
  #+swank
  `(progn
     ,@(mapcar (lambda (form) `(format *error-output* "~A => ~A~%" ',form ,form))
               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)

(defmacro 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))
         (buf (make-string n :element-type 'base-char))
         (cumul (make-array (1+ n) :element-type 'uint32 :initial-element 0))
         (out (make-string-output-stream :element-type 'base-char)))
    (declare (uint32 n q))
    (read-line-into buf)
    (dotimes (i (- n 1))
      (when (and (char= #\A (schar buf i))
                 (char= #\C (schar buf (+ i 1))))
        (setf (aref cumul (+ i 2)) 1)))
    (loop for i from 1 to n
          do (incf (aref cumul i) (aref cumul (- i 1))))
    (dotimes (_ q (write-string (get-output-stream-string out)))
      (split-ints-bind (l r) (buffered-read-line 13)
        (println (- (aref cumul r) (aref cumul l)) out)))))

#-swank(main)


(defun calc (s left right)
  (let ((count 0)
        (current (- left 1)))
    (dotimes (n (+ 1 (- right left)))
      ;; (format t "Current: ~A Left: ~A Right: ~A~%" current left right)
      (when (>= (+ current 1) right)
        (return-from calc count))
      (when (equal (nth current s) #\A)
          (when (equal (nth (+ current 1) s) #\C)
            (incf count)
            (incf current)))
      (incf current))
    count))

(defun main ()
  (let ((N (read))
        (Q (read))
        (S (concatenate 'list (read-line)))
        (result (list nil)))
    (declare (ignore N))
    (dotimes (n Q)
      (push (calc S (read) (read)) result))
    (setq result (cdr (reverse result)))
    (dolist (n result)
      (print n))))

(main)


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

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

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

(defconstant +mod+ 1000000007)

;; Hauptteil

(defun main ()
  (let* ((n (read))
         (bs (make-array n :element-type 'uint7))
         (marked (make-array n :element-type 'boolean :initial-element nil))
         (cumul (make-array n :element-type 'uint7 :initial-element 0))
         res)
    (dotimes (i n) (setf (aref bs i) (- (read) 1)))
    (dotimes (time n)
      (loop for i from (- n 1) downto 0
            do (when (and (not (aref marked i))
                          (= (aref bs i) (aref cumul i)))
                 (push (aref bs i) res)
                 (setf (aref marked i) t)
                 (loop for j from (1+ i) below n
                       do (incf (aref cumul j)))
                 (return))
            finally (println -1)
                    (return-from main)))
    (dolist (b (reverse res))
      (println (1+ b)))))

#-swank(main)

Score : 400 points

Problem Statement

Snuke has an empty sequence a.

He will perform N operations on this sequence.

In the i-th operation, he chooses an integer j satisfying 1 \leq j \leq i, and insert j at position j in a (the beginning is position 1).

You are given a sequence b of length N. Determine if it is possible that a is equal to b after N operations. If it is, show one possible sequence of operations that achieves it.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq b_i \leq N

Input

Input is given from Standard Input in the following format:

N
b_1 \dots b_N

Output

If there is no sequence of N operations after which a would be equal to b, print -1.
If there is, print N lines. In the i-th line, the integer chosen in the i-th operation should be printed. If there are multiple solutions, any of them is accepted.

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

In this sequence of operations, the sequence a changes as follows:

After the first operation: (1)

After the second operation: (1,1)

After the third operation: (1,2,1)

Sample Input 2

2
2 2

Sample Output 2

-1

2 cannot be inserted at the beginning of the sequence, so this is impossible.

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1


(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 (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Queue with singly linked list
;;;

(defstruct (queue (:constructor make-queue
                      (&optional list &aux (tail (last list)))))
  (list nil :type list)
  (tail nil :type list))

(declaim (inline enqueue))
(defun enqueue (obj queue)
  "Pushes OBJ to the end of QUEUE."
  (symbol-macrolet ((list (queue-list queue))
                    (tail (queue-tail queue)))
    (if (null list)
        (setf tail (list obj)
              list tail)
        (setf (cdr tail) (list obj)
              tail (cdr tail))))
  queue)

(declaim (inline dequeue))
(defun dequeue (queue)
  "Removes and returns the element at the front of QUEUE. Returns NIL if QUEUE
is empty."
  (pop (queue-list queue)))

(declaim (inline queue-empty-p))
(defun queue-empty-p (queue)
  (null (queue-list queue)))

(declaim (inline queue-peek))
(defun queue-peek (queue)
  (car (queue-list queue)))

(declaim (inline enqueue-front))
(defun enqueue-front (obj queue)
  "Pushes OBJ to the front of QUEUE."
  (symbol-macrolet ((list (queue-list queue))
                    (tail (queue-tail queue)))
    (if (null list)
        (setf tail (list obj)
              list tail)
        (push obj list))
    queue))

(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 #\-))
                                  (setq 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))))))))

(in-package :cl-user)

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

;; 辺素なオイラー閉路を一点以上の点でくっつけるとオイラー閉路だから、オイラー閉路を1つ見つけて取り除いたときに、2つ以上のcomponentが残っていればOK。1つでもさらにオイラー閉路を取り除ければOK
;; けっきょく最短の単純閉路（=最短のサーキット）をどこかの点で見つけて、取り除く、ではだめ？

(defun find-cycle (graph e1 e2)
  (let* ((n (length graph))
         (dists (make-array n :element-type 'uint32 :initial-element #xffffffff))
         (paths (make-array n :element-type 'list :initial-element nil))
         (que (make-queue)))
    ;; #>graph
    (dbg e1 e2)
    (enqueue e1 que)
    (setf (aref dists e1) 0)
    (push e1 (aref paths e1))
    (loop until (queue-empty-p que)
          for v = (dequeue que)
          do (dolist (next (aref graph v))
               (when (and (= #xffffffff (aref dists next))
                          (not (and (= e1 v) (= e2 next))))
                 (enqueue next que)
                 (setf (aref paths next)
                       (cons next (aref paths v)))
                 (setf (aref dists next)
                       (+ (aref dists v) 1)))))
    (cons e1 (aref paths e2))))

(defun main ()
  (let* ((n (read))
         (m (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         (degs (make-array n :element-type 'uint31 :initial-element 0)))
    (labels ((no () (write-line "No") (return-from main)))
      (dotimes (i m)
        (let ((a (- (read-fixnum) 1))
              (b (- (read-fixnum) 1)))
          (push a (aref graph b))
          (push b (aref graph a))
          (incf (aref degs a))
          (incf (aref degs b))))
      (unless (loop for x across degs
                    always (evenp x))
        (no))
      (labels ((frob ()
                 (let ((e1 (position nil graph :test-not #'eq)))
                   #>e1
                   (unless e1 (no))
                   (let ((path (find-cycle graph e1 (car (aref graph e1))))
                         (table (make-hash-table :test #'equal)))
                     #>path
                     (loop for (u v) on path
                           while v
                           do (setf (gethash (cons u v) table) t
                                    (gethash (cons v u) table) t))
                     (dotimes (i n)
                       (setf (aref graph i)
                             (loop for j in (aref graph i)
                                   unless (gethash (cons i j) table)
                                   collect j)))
                     #>graph
                     (dotimes (i n)
                       (dolist (j (aref graph i))
                         (when (< i j)
                           (format t "~D ~D~%" i j))))
                     (unless (find nil graph :test-not #'eq)
                       (no))))))
        (frob)
        (frob)
        (write-line "Yes")))))

#-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 "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 "7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
"
    "Yes
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 3
1 2
2 3
3 1
"
    "No
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
"
    "Yes
")))

Score : 800 points

Problem Statement

You are given a simple connected undirected graph consisting of N vertices and M edges.
The vertices are numbered 1 to N, and the edges are numbered 1 to M.

Edge i connects Vertex a_i and b_i bidirectionally.

Determine if three circuits (see Notes) can be formed using each of the edges exactly once.

Notes

A circuit is a cycle allowing repetitions of vertices but not edges.

Constraints

All values in input are integers.

1 \leq N,M \leq 10^{5}

1 \leq a_i, b_i \leq N

The given graph is simple and connected.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

If three circuits can be formed using each of the edges exactly once, print Yes; if they cannot, print No.

Sample Input 1

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

Sample Output 1

Yes

Three circuits can be formed using each of the edges exactly once, as follows:

Sample Input 2

3 3
1 2
2 3
3 1

Sample Output 2

No

Three circuits are needed.

Sample Input 3

18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15

Sample Output 3

Yes


(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 (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; 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 2 4 7 8 15 16 31 32 62 63 64)

;;;
;;; Max flow (Dinic's algorithm)
;;;

(defconstant +graph-inf-distance+ #xffffffff)

(define-condition max-flow-overflow (error)
  ((graph :initarg :graph :reader max-flow-overflow-graph))
  (:report
   (lambda (condition stream)
     (format stream "MOST-POSITIVE-FIXNUM or more units can flow on graph ~W."
             (max-flow-overflow-graph condition)))))

(declaim (inline edge-to edge-capacity edge-reversed))
(defun edge-to (edge)
  (the (integer 0 #.most-positive-fixnum) (car edge)))
(defun edge-capacity (edge)
  (the (integer 0 #.most-positive-fixnum) (cadr edge)))
(defun edge-reversed (edge)
  (the list (cddr edge)))

(defun add-edge (graph from-idx to-idx capacity &key bidirectional)
  "FROM-IDX, TO-IDX := index of vertex
GRAPH := vector of lists of all the edges that goes from each vertex

If BIDIRECTIONAL is true, PUSH-EDGE adds the reversed edge of the same
capacity in addition."
  (declare (optimize (speed 3))
           ((simple-array list (*)) graph))
  (let* ((dep (list* to-idx capacity nil))
         (ret (list* from-idx
                     (if bidirectional capacity 0)
                     dep)))
    (setf (cddr dep) ret)
    (push dep (aref graph from-idx))
    (push ret (aref graph to-idx))))

(defun %fill-dist-table (graph src dist-table queue)
  "Does BFS and sets DIST-TABLE to the distance between SRC and each vertex of
GRAPH, where an edge of zero capacity is regarded as disconnected."
  (declare (optimize (speed 3) (safety 0))
           ((integer 0 #.most-positive-fixnum) src)
           ((simple-array list (*)) graph)
           ((simple-array (unsigned-byte 32) (*)) dist-table queue))
  (let* ((q-front 0)
         (q-end 0))
    (declare ((integer 0 #.most-positive-fixnum) q-front q-end))
    (labels ((enqueue (obj)
               (setf (aref queue q-end) obj)
               (incf q-end))
             (dequeue ()
               (prog1 (aref queue q-front)
                 (incf q-front))))
      (declare (inline enqueue dequeue))
      (fill dist-table +graph-inf-distance+)
      (setf (aref dist-table src) 0)
      (enqueue src)
      (loop until (= q-front q-end)
            for vertex = (dequeue)
            do (dolist (edge (aref graph vertex))
                 (let ((neighbor (edge-to edge)))
                   (when (and (> (edge-capacity edge) 0)
                              (= +graph-inf-distance+ (aref dist-table neighbor)))
                     (setf (aref dist-table neighbor)
                           (+ 1 (aref dist-table vertex)))
                     (enqueue neighbor)))))))
  dist-table)

(declaim (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional)) %find-path))
(defun %find-path (src dest tmp-graph dist-table)
  "Finds an augmenting path, sends the maximum flow through it, and returns the
amount of the flow."
  (declare (optimize (speed 3) (safety 0))
           ((integer 0 #.most-positive-fixnum) src dest)
           ((simple-array list (*)) tmp-graph)
           ((simple-array (unsigned-byte 32) (*)) dist-table))
  (labels ((dfs (v flow)
             (declare ((integer 0 #.most-positive-fixnum) v flow))
             (when (= v dest)
               (return-from dfs flow))
             (loop
               (unless (aref tmp-graph v)
                 (return 0))
               (let ((edge (car (aref tmp-graph v))))
                 (when (and (> (edge-capacity edge) 0)
                            (< (aref dist-table v) (aref dist-table (edge-to edge))))
                   (let ((result (dfs (edge-to edge) (min flow (edge-capacity edge)))))
                     (declare ((integer 0 #.most-positive-fixnum) result))
                     (when (> result 0)
                       (decf (the uint62 (cadr edge)) result)
                       (incf (the uint62 (cadr (cddr edge))) result)
                       (return result)))))
               (pop (aref tmp-graph v)))))
    (dfs src most-positive-fixnum)))

(declaim (ftype (function * (values (mod #.most-positive-fixnum) &optional)) max-flow!))
(defun max-flow! (graph src dest)
  "Destructively sends the maximum flow from SRC to DEST and returns the amount
of the flow. This function signals MAX-FLOW-OVERFLOW error when an infinite
flow (to be precise, >= MOST-POSITIVE-FIXNUM) is possible."
  (declare #+sbcl (muffle-conditions style-warning)
           ((integer 0 #.most-positive-fixnum) src dest)
           ((simple-array list (*)) graph))
  (let* ((n (length graph))
         (dist-table (make-array n :element-type '(unsigned-byte 32)))
         (queue (make-array n :element-type '(unsigned-byte 32)))
         (tmp-graph (make-array n :element-type 'list))
         (result 0))
    (declare ((integer 0 #.most-positive-fixnum) result))
    (loop
      (%fill-dist-table graph src dist-table queue)
      (when (= (aref dist-table dest) +graph-inf-distance+)
        ;; SRC and DEST are not connected on the current residual network.
        (return result))
      (dotimes (i n)
        (setf (aref tmp-graph i) (aref graph i)))
      (loop for delta = (%find-path src dest tmp-graph dist-table)
            until (zerop delta)
            do (when (>= (+ result delta) most-positive-fixnum)
                 (error 'max-flow-overflow :graph graph))
               (incf result delta)))))

(in-package :cl-user)

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (a (read))
         (b (read))
         (ps (make-array n :element-type 'uint31 :initial-element 0))
         (graph (make-array (+ (* 2 n) 2) :element-type 'list :initial-element nil))
         (source (* 2 n))
         (sink (+ (* 2 n) 1)))
    (dotimes (i n)
      (setf (aref ps i) (- (read) 1)))
    (dotimes (i n)
      (add-edge graph source i a)
      (add-edge graph (+ i n) sink b))
    (dotimes (i n)
      (loop for j from (+ i 1) below n
            when (> (aref ps i) (aref ps j))
            do (add-edge graph i (+ j n) most-positive-fixnum)))
    (println (max-flow! graph source sink))))

#-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 "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)))

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

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

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

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

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

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

Score : 1000 points

Problem Statement

You are given a permutation p = (p_1, \ldots, p_N) of \{ 1, \ldots, N \}.
You can perform the following two kinds of operations repeatedly in any order:

Pay a cost A. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the left by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, p_r with p_{l + 1}, p_{l + 2}, \ldots, p_r, p_l, respectively.

Pay a cost B. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the right by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, p_r with p_r, p_l, \ldots, p_{r - 2}, p_{r - 1}, respectively.

Find the minimum total cost required to sort p in ascending order.

Constraints

All values in input are integers.

1 \leq N \leq 5000

1 \leq A, B \leq 10^9

(p_1 \ldots, p_N) is a permutation of \{ 1, \ldots, N \}.

Input

Input is given from Standard Input in the following format:

N A B
p_1 \cdots p_N

Output

Print the minimum total cost required to sort p in ascending order.

Sample Input 1

3 20 30
3 1 2

Sample Output 1

20

Shifting (p_1, p_2, p_3) to the left by one results in p = (1, 2, 3).

Sample Input 2

4 20 30
4 2 3 1

Sample Output 2

50

One possible sequence of operations is as follows:

Shift (p_1, p_2, p_3, p_4) to the left by one. Now we have p = (2, 3, 1, 4).

Shift (p_1, p_2, p_3) to the right by one. Now we have p = (1, 2, 3, 4).

Here, the total cost is 20 + 30 = 50.

Sample Input 3

1 10 10
1

Sample Output 3

0

Sample Input 4

4 1000000000 1000000000
4 3 2 1

Sample Output 4

3000000000

Sample Input 5

9 40 50
5 3 4 7 6 1 2 9 8

Sample Output 5

220


(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 (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

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

(in-package :cl-user)

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defconstant +inf+ most-positive-fixnum)
(defun main ()
  (let* ((n (read))
         (a (read))
         (b (read))
         (ps (make-array n :element-type 'uint31 :initial-element 0))
         (invs (make-array n :element-type 'uint31 :initial-element 0))
         (dp (make-array (list (+ n 1) (+ n 1))
                         :element-type 'uint62
                         :initial-element +inf+)))
    (declare (uint31 n a b))
    (dotimes (i n)
      (setf (aref invs (- (read) 1)) i))
    (setf (aref dp 0 0) 0)
    (dotimes (x (+ n 1))
      (dotimes (y (+ n 1))
        (when (< y n)
          (minf (aref dp x (+ y 1))
                (aref dp x y)))
        (when (< x n)
          (cond ((< (aref invs x) y)
                 (minf (aref dp (+ x 1) y)
                       (+ (aref dp x y) a)))
                ((> (aref invs x) y)
                 (minf (aref dp (+ x 1) y)
                       (+ (aref dp x y) b)))
                (t
                 (minf (aref dp (+ x 1) (+ y 1))
                       (aref dp x y)))))))
    (println (aref dp n 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 "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)))

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

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

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

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

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

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


(defun string->duplicates-removed-list (string)
  (declare (optimize (speed 3) (safety 0) (debug 0)))
  (labels ((rec (n acc)
             (if (= n -1)
                 acc
                 (let ((c (char string n)))
                   (if (member c acc)
                       (rec (1- n) acc)
                       (rec (1- n) (cons c acc)))))))
    (rec (1- (length string)) nil)))

(defun f (str)
  (declare (optimize (speed 3) (safety 0) (debug 0)))
  (labels ((rec (lst acc)
             (if (null lst)
                 acc
                 (rec (cdr lst) (* (1+ (count (car lst) str)) acc)))))
    (1- (rec (string->duplicates-removed-list str) 1))))

(defparameter *n* (read))
(defparameter *s* (read))

(print (mod (f *s*) (+ 1e9 7)))

Score : 200 points

Problem Statement

You are given a string S of length N.
Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of the subsequences such that all characters are different, modulo 10^9+7.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in S itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17


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

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

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

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

(defconstant +mod+ 1000000007)

;; Hauptteil

(defun main ()
  (let* ((n (read))
         (m (read))
         (c (read))
         (bs (make-array m :element-type 'int32))
         (as (make-array m :element-type 'int32)))
    (split-ints-into-vector (read-line) bs)
    (println
     (loop repeat n
           do (split-ints-into-vector (read-line) as)
           count (> (+ c
                       (loop for a across as
                             for b across bs
                             sum (* a b)))
                    0)))))

#-swank(main)

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


(let* ((n (read))
    (m (read))
    (a (make-array (list n)))
    (money 0))
    (loop for i below n do
        (setf (aref a i) (list (read) (read)))
    )
    (setf a (sort a #'< :key #'car))
    (loop for i below n while (> m 0) do
        (progn
            (if (>= (second (aref a i)) m)
                (incf money (* (car (aref a i)) m))
                (incf money (* (car (aref a i)) (second (aref a i))))
            )
            (decf m (second (aref a i)))
        )
    )
    (princ money)
)

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

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


(setq a(read))(setq b(read))(setq k(read))
(loop for i from 100 downto 1 do(if(=(mod a i)(mod b i)0)(decf k))(if(= k 0)(progn(princ i)(decf k))))

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


(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 2 4 7 8 15 16 31 32 62 63 64)

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

(defconstant +mod+ 1000000007)

;; Hauptteil

(defun main ()
  (let* ((a (read))
         (b (read))
         (k (read))
         (gcd (gcd a b)))
    (loop with c = 1
          for num from gcd downto 1
          do (when (zerop (mod gcd num))
               (when (= k c)
                 (println num)
                 (return-from main))
               (incf c)))))

#-swank(main)


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

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

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

(defconstant +mod+ 1000000007)

;; Hauptteil

(defun main ()
  (let* ((n (read))
         (a (read))
         (b (read))
         (c (read))
         (ls (make-array n :element-type 'uint15))
         (min-cost most-positive-fixnum))
    (dotimes (i n) (setf (aref ls i) (read)))
    (loop for is from 0 below (expt 4 n)
          do (loop with set1 = 0
                   with set2 = 0
                   with set3 = 0
                   with set1-size = 0
                   with set2-size = 0
                   with set3-size = 0
                   for i from 0 below n
                   for mask = 3 then (ash mask 2)
                   do (let ((value (ash (logand mask is) (* -2 i))))
                        (cond ((= value 1)
                               (incf set1-size)
                               (incf set1 (aref ls i)))
                              ((= value 2)
                               (incf set2-size)
                               (incf set2 (aref ls i)))
                              ((= value 3)
                               (incf set3-size)
                               (incf set3 (aref ls i)))
                              ((zerop value) nil)
                              (t (error "Huh"))))
                   finally (unless (or (zerop set1-size)
                                       (zerop set2-size)
                                       (zerop set3-size))
                             (let* ((merge-cost (* 10 (+ (- set1-size 1)
                                                         (- set2-size 1)
                                                         (- set3-size 1))))
                                    (cost (+ merge-cost
                                             (abs (- a set1))
                                             (abs (- b set2))
                                             (abs (- c set3)))))
                               (when (< cost min-cost)
                                 (setf min-cost cost))))))
    (println min-cost)))

#-swank(main)

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


(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 (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

(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
(defpackage :cp/read-fixnum
  (:use :cl)
  (:export #:read-fixnum))
(in-package :cp/read-fixnum)

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  "NOTE: cannot read -2^62"
  (declare #.cl-user::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 #\-))
                                  (setq 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))))))))

(defpackage :cp/bisect
  (:use :cl)
  (:export #:bisect-left #:bisect-right))
(in-package :cp/bisect)

(declaim (inline bisect-left))
(defun bisect-left (target value &key (start 0) end (order #'<) (key #'identity))
  "TARGET := vector | function (taking an integer argument)
ORDER := strict order

Analogue of lower_bound() of C++ or bisect_left() of Python: Returns the
smallest index (or input) i that fulfills TARGET[i] >= VALUE, where '>=' is the
complement of ORDER. In other words, this function returns the leftmost index at
which VALUE can be inserted with keeping the order. Therefore, TARGET must be
monotonically non-decreasing with respect to ORDER.

- This function returns END if VALUE exceeds TARGET[END-1].
- The range [START, END) is half-open.
- END must be explicitly specified if TARGET is function.
- KEY is applied to each element of TARGET before comparison."
  (declare (function key order)
           (integer start)
           ((or null integer) end))
  (macrolet
      ((frob (accessor &optional declaration)
         `(labels
              ((%bisect-left (ng ok)
                 ;; TARGET[OK] >= VALUE always holds (assuming
                 ;; TARGET[END] = +infinity)
                 ,@(when declaration (list declaration))
                 (if (<= (- ok ng) 1)
                     ok
                     (let ((mid (ash (+ ng ok) -1)))
                       (if (funcall order (funcall key (,accessor target mid)) value)
                           (%bisect-left mid ok)
                           (%bisect-left ng mid))))))
            (assert (<= start end))
            (%bisect-left (- start 1) end))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (frob aref (declare ((integer -1 (#.most-positive-fixnum)) ng ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (frob funcall)))))

(declaim (inline bisect-right))
(defun bisect-right (target value &key (start 0) end (order #'<) (key #'identity))
  "TARGET := vector | function (taking an integer argument)
ORDER := strict order

Analogue of upper_bound() of C++ or bisect_right() of Python: Returns the
smallest index (or input) i that fulfills TARGET[i] > VALUE. In other words,
this function returns the rightmost index at which VALUE can be inserted with
keeping the order. Therefore, TARGET must be monotonically non-decreasing with
respect to ORDER.

- This function returns END if VALUE >= TARGET[END-1].
- The range [START, END) is half-open.
- END must be explicitly specified if TARGET is function.
- KEY is applied to each element of TARGET before comparison."
  (declare (function key order)
           (integer start)
           ((or null integer) end))
  (macrolet
      ((frob (accessor &optional declaration)
         `(labels
              ((%bisect-right (ng ok)
                 ;; TARGET[OK] > VALUE always holds (assuming
                 ;; TARGET[END] = +infinity)
                 ,@(when declaration (list declaration))
                 (if (<= (- ok ng) 1)
                     ok
                     (let ((mid (ash (+ ng ok) -1)))
                       (if (funcall order value (funcall key (,accessor target mid)))
                           (%bisect-right ng mid)
                           (%bisect-right mid ok))))))
            (assert (<= start end))
            (%bisect-right (- start 1) end))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (frob aref (declare ((integer -1 (#.array-total-size-limit)) ng ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (frob funcall)))))

;; BEGIN_USE_PACKAGE
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/bisect :cl-user))
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/read-fixnum :cl-user))
(in-package :cl-user)

;;;
;;; Body
;;;

(defconstant +pos-inf+ #.(expt 10 17))
(defconstant +neg-inf+ #.(- (expt 10 17)))
(defun main ()
  (declare #.cl-user::opt)
  (let* ((a (read))
         (b (read))
         (q (read))
         (ss (make-array (+ a 2) :element-type 'fixnum :initial-element 0))
         (ts (make-array (+ b 2) :element-type 'fixnum :initial-element 0)))
    (declare (uint31 a b q))
    (setf (aref ss 0) +neg-inf+
          (aref ss (+ a 1)) +pos-inf+
          (aref ts 0) +neg-inf+
          (aref ts (+ b 1)) +pos-inf+)
    (loop for i from 1 to a
          do (setf (aref ss i) (read-fixnum)))
    (loop for i from 1 to b
          do (setf (aref ts i) (read-fixnum)))
    (labels ((calc-dist (vec x)
               (if (< +neg-inf+ x +pos-inf+)
                   (let* ((r (bisect-left vec x))
                          (l (- r 1)))
                     (min (abs (- (aref vec r) x))
                          (abs (- (aref vec l) x))))
                   +pos-inf+)))
      (write-string
       (with-output-to-string (*standard-output* nil :element-type 'base-char)
         (dotimes (_ q)
           (let* ((x (read-fixnum))
                  (sr (bisect-left ss x))
                  (sl (- sr 1))
                  (tr (bisect-left ts x))
                  (tl (- tr 1)))
             (println
              (min (+ (abs (- x (aref ss sr)))
                      (calc-dist ts (aref ss sr)))
                   (+ (abs (- x (aref ss sl)))
                      (calc-dist ts (aref ss sl)))
                   (+ (abs (- x (aref ts tr)))
                      (calc-dist ss (aref ts tr)))
                   (+ (abs (- x (aref ts tl)))
                      (calc-dist ss (aref ts tl))))))))))))

#-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
  (it.bese.fiveam:is
   (equal "350
1400
301
399
"
          (run "2 3 4
100
600
400
900
1000
150
2000
899
799
" nil)))
  (it.bese.fiveam:is
   (equal "10000000000
10000000000
14999999998
"
          (run "1 1 3
1
10000000000
2
9999999999
5000000000
" nil))))

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


(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 2 4 7 8 15 16 31 32 62 63 64)

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

(defconstant +mod+ 1000000007)

;; Hauptteil

(defun main ()
  (let* ((k (read))
         (a (read))
         (b (read)))
    (if (or (>= a k) (>= a b))
        (println (+ 1 k))
        (if (evenp (+ k (- a) 1))
            (println (max (+ k 1)
                          (+ a (floor (* (- b a) (+ k (- a) 1)) 2))))
            (println (max (+ k 1)
                          (+ 1 a (floor (* (- b a) (- k a)) 2))))))))

#-swank(main)

Score : 400 points

Problem Statement

Snuke has one biscuit and zero Japanese yen (the currency) in his pocket.
He will perform the following operations exactly K times in total, in the order he likes:

Hit his pocket, which magically increases the number of biscuits by one.

Exchange A biscuits to 1 yen.

Exchange 1 yen to B biscuits.

Find the maximum possible number of biscuits in Snuke's pocket after K operations.

Constraints

1 \leq K,A,B \leq 10^9

K,A and B are integers.

Input

Input is given from Standard Input in the following format:

K A B

Output

Print the maximum possible number of biscuits in Snuke's pocket after K operations.

Sample Input 1

4 2 6

Sample Output 1

7

The number of biscuits in Snuke's pocket after K operations is maximized as follows:

Hit his pocket. Now he has 2 biscuits and 0 yen.

Exchange 2 biscuits to 1 yen. his pocket. Now he has 0 biscuits and 1 yen.

Hit his pocket. Now he has 1 biscuits and 1 yen.

Exchange 1 yen to 6 biscuits. his pocket. Now he has 7 biscuits and 0 yen.

Sample Input 2

7 3 4

Sample Output 2

8

Sample Input 3

314159265 35897932 384626433

Sample Output 3

48518828981938099


(defun f (a b c)
  (cond ((char= a b c) 0)
        ((char= a b) 1)
        ((char= b c) 1)
        ((char= a c) 1)
        (t 2)))
(let* ((n (read))
       (a (read-line))
       (b (read-line))
       (c (read-line)))
  (princ (loop :for k :from 0 :upto (1- n) :sum (f (aref a k) (aref b k) (aref c k)))))

Score : 200 points

Problem Statement

You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.

Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:

Operation: Choose one of the strings A, B and C, and specify an integer i between 1 and N (inclusive). Change the i-th character from the beginning of the chosen string to some other lowercase English letter.

What is the minimum number of operations required to achieve the objective?

Constraints

1 \leq N \leq 100

Each of the strings A, B and C is a string of length N.

Each character in each of the strings A, B and C is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
A
B
C

Output

Print the minimum number of operations required.

Sample Input 1

4
west
east
wait

Sample Output 1

3

In this sample, initially A = west、B = east、C = wait. We can achieve the objective in the minimum number of operations by performing three operations as follows:

Change the second character in A to a. A is now wast.

Change the first character in B to w. B is now wast.

Change the third character in C to s. C is now wast.

Sample Input 2

9
different
different
different

Sample Output 2

0

If A, B and C are already equal in the beginning, the number of operations required is 0.

Sample Input 3

7
zenkoku
touitsu
program

Sample Output 3

13


#-(or child-sbcl swank)
(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)))

(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

;; -*- coding:utf-8 -*-
(defstruct (queue (:constructor make-queue
                    (&optional list &aux (tail (last list)))))
  (list nil :type list)
  (tail nil :type (or null (cons t null))))

(declaim (inline enqueue!))
(defun enqueue! (obj queue)
  (symbol-macrolet ((list (queue-list queue))
                    (tail (queue-tail queue)))
    (if (null list)
        (setf tail (list obj)
              list tail)
        (setf (cdr tail) (list obj)
              tail (cdr tail))))
  queue)

(declaim (inline dequeue!))
(defun dequeue! (queue)
  (pop (queue-list queue)))

(defun empty-queue-p (queue)
  (null (queue-list queue)))

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

(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (terminate-char #\Space))
  "Note that the returned string will be reused."
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let ((,buffer (load-time-value (make-string ,buffer-size
                                                  :element-type 'base-char))))
       (declare (simple-base-string ,buffer))
       (loop for ,character 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= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (setf (schar ,buffer ,idx) ,terminate-char)
                     (return (values ,buffer ,idx))))))

(defmacro split-ints-bind (vars string &body body)
  (let ((position (gensym))
        (s (gensym)))
    (labels ((expand (vars &optional init-pos)
               (if (null vars)
                   body
                   `((multiple-value-bind (,(car vars) ,position)
                         (parse-integer ,s :start ,(or init-pos position)
                                           :junk-allowed t)
                       ,@(when (null (cdr vars)) `((declare (ignore ,position))))
                       ,@(expand (cdr vars)))))))
      `(let ((,s ,string))
         (declare (string ,s))
         ,@(expand vars 0)))))

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

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

(defconstant +mod+ 1000000007)

;; Hauptteil
(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))))))
(defun solve (graph root)
  (let* ((n (length graph))
         (cost-table (make-array n :element-type 'uint32 :initial-element 0))
         (parents-table (make-array n :element-type 'int32 :initial-element -1)))
    (setf (aref cost-table root) 0)
    (dotimes (i n)
      (nlet recurse ((graph graph))
        (unless (null graph)
          (let* ((pair (car graph))
                 (a (car pair))
                 (b (cdr pair)))
            (when (> (+ (aref cost-table a) 1) (aref cost-table b))
              (setf (aref cost-table b) (+ (aref cost-table a) 1))
              (setf (aref parents-table b) a))
            (recurse (cdr graph))))))
    parents-table))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (m (read))
         (n-1+m (+ n -1 m))
         graph
         (rev-graph (make-array n :element-type 'list :initial-element nil))
         (out (make-string-output-stream :element-type 'base-char)))
    (dotimes (i (+ n -1 m))
      (split-ints-bind (a b) (buffered-read-line 20)
        (declare (uint32 a b))
        (push (cons (- a 1) (- b 1)) graph)
        (push (- a 1) (aref rev-graph (- b 1)))))
    (let* ((root (nlet find-root ((node 0))
                   (if (null (aref rev-graph node))
                       node
                       (loop for next in (aref rev-graph node)
                             for root = (find-root next)
                             when root
                             do (return root)))))
           (parents (solve graph root)))
      (declare ((simple-array int32 (*)) parents))
      (dotimes (i n (write-string (get-output-stream-string out)))
        (println (1+ (aref parents i)) out)))))

#-swank(main)

Score : 500 points

Problem Statement

There is a rooted tree (see Notes) with N vertices numbered 1 to N.
Each of the vertices, except the root, has a directed edge coming from its parent.
Note that the root may not be Vertex 1.

Takahashi has added M new directed edges to this graph.
Each of these M edges, u \rightarrow v, extends from some vertex u to its descendant v.

You are given the directed graph with N vertices and N-1+M edges after Takahashi added edges.
More specifically, you are given N-1+M pairs of integers, (A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M}), which represent that the i-th edge extends from Vertex A_i to Vertex B_i.

Restore the original rooted tree.

Notes

For "tree" and other related terms in graph theory, see the article in Wikipedia, for example.

Constraints

3 \leq N

1 \leq M

N + M \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

If i \neq j, (A_i, B_i) \neq (A_j, B_j).

The graph in input can be obtained by adding M edges satisfying the condition in the problem statement to a rooted tree with N vertices.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_{N-1+M} B_{N-1+M}

Output

Print N lines.
In the i-th line, print 0 if Vertex i is the root of the original tree, and otherwise print the integer representing the parent of Vertex i in the original tree.

Note that it can be shown that the original tree is uniquely determined.

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

It can be seen that this graph is obtained by adding the edge 1 \rightarrow 3 to the rooted tree 1 \rightarrow 2 \rightarrow 3.

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2