Scanf.scanf "%s" (fun s ->
    let n = String.length s in
    let rec loop i acc =
        if i = n then acc else loop (i + 1) (acc + int_of_char s.[i] - 48)
    in
    print_endline @@ if loop 0 0 mod 9 = 0 then "Yes" else "No"
)

Score : 200 points

Problem Statement

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

0 \leq N < 10^{200000}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No


let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  Printf.printf "%d\n" @@
  fst @@
  Array.fold_left (fun (sum, prev) a ->
    sum + max prev a - a, max prev a) (0, min_int) as_

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

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.

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.


module Weighted01DirectedGraph
  (* 頂点を添字，経路長を要素とした配列の実装 *)
  (Array : sig
    type t
    type key
    type elt = int (* 全ての重さが0か1なグラフなので経路長は非負整数 *)
    val get : t -> key -> elt
    val set : t -> key -> elt -> unit
  end)
: sig
  type vertex = Array.key

  val shortest_path :
    (* 全ての頂点についての経路長が無限大で初期化された配列 *)
    Array.t ->
    (* 最短経路を求めたいグラフの，ある頂点から伸びる辺に対してのイテレータ
       重みが0の辺に対してはf0を，1の辺に対してはf1を用いる *)
    (vertex -> f0:(vertex -> unit) -> f1:(vertex -> unit) -> unit) ->
    (* 始点 *)
    vertex ->
    (* 終点を受け取って，始点からの最短距離を返す関数
       始点から辿り着けない場合，無限大を返す
       この関数を覚えておけば，呼び出しごとの途中までの計算結果がシェアされる *)
    (vertex -> int)
end =
struct
  type vertex = Array.key

  let shortest_path d es s =
    (* 始点への経路長を0にする *)
    Array.set d s 0;
    let w = ref 1 in
    let q = ref [s] in
    let rec bfs t =
      match !q with
      (* もう既に全ての頂点までの経路が分かっているので返す *)
      | [] -> Array.get d t
      | us ->
          match Array.get d t with
          (* 既に終点までの距離が分かっているので返す *)
          | x when x < !w -> x
          (* 終点までの距離が分かっていないので，BFSを続行 *)
          | _ ->
              q := [];
              List.iter dfs us;
              incr w;
              bfs t
    and dfs u =
      es u
        ~f0:(fun v ->
          if !w <= Array.get d v then
            (Array.set d v (!w - 1); dfs v))
        ~f1:(fun v ->
          if !w < Array.get d v then
            (Array.set d v !w; q := v :: !q)) in
    bfs
end

module G = Weighted01DirectedGraph (struct
  type t = (int, Bigarray.int_elt, Bigarray.c_layout) Bigarray.Genarray.t
  type elt = int
  type key = int array
  let get = Bigarray.Genarray.get
  let set = Bigarray.Genarray.set
end)

let () = Scanf.scanf "%d %d\n%d %d\n%d %d\n" @@ fun h w ch cw dh dw ->
  let ss = Array.init h @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
  let d =
    G.shortest_path
      (let d = Bigarray.Genarray.create Bigarray.int Bigarray.c_layout [| h; w |] in Bigarray.Genarray.fill d max_int; d)
      (fun [|i; j|] ~f0 ~f1 ->
        List.iter (fun (i', j') ->
          if 0 <= i' && i' < h && 0 <= j' && j' < w && ss.(i').[j'] = '.' then f0 [|i'; j'|])
        [(i - 1, j); (i + 1, j); (i, j - 1); (i, j + 1)];
        for i' = max 0 (i - 2) to min (h - 1) (i + 2) do
          for j' = max 0 (j - 2) to min (w - 1) (j + 2) do
            if ss.(i').[j'] = '.' then f1 [|i'; j'|]
          done
        done)
      [|ch - 1; cw - 1|]
      [|dh - 1; dw - 1|] in
  Printf.printf "%d\n" @@ if d = max_int then -1 else d

Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

Sample Input 1

4 4
1 1
4 4
..#.
..#.
.#..
.#..

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

4 4
1 4
4 1
.##.
####
####
.##.

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2


Scanf.scanf "%d %d" (fun n k ->
    let p = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a - 1)) in
    let c = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in

    let par = Array.init n (fun i -> i) in

    let rec root x =
        if x = par.(x) then x else
            let r = root par.(x) in
            let () = par.(x) <- r in
            r
    in

    let merge a b =
        if root a <> root b then
            par.(par.(b)) <- par.(a)
    in
    Array.iteri merge p;

    let cluster = Array.init n root in
    let size = Array.make n 0 in
    Array.iter (fun v -> size.(v) <- size.(v) + 1) cluster;

    let sum = Array.make n 0 in

    let calc_loop_score start len =
        let rec loop cur len acc =
            if len = 0 then acc else
                let cur = p.(cur) in
                let acc = acc + c.(cur) in
                loop cur (len - 1) acc
        in
        loop start len 0
    in
    Array.iteri (fun i sz -> if sz > 0 then sum.(i) <- calc_loop_score i sz) size;

    let calc_best start len =
        let rec loop cur len acc mx =
            if len = 0 then mx else
                let cur = p.(cur) in
                let acc = acc + c.(cur) in
                let mx = max mx acc in
                loop cur (len - 1) acc mx
        in
        loop start len 0 (-100000000000000)
    in

    let score = Array.init n (fun i ->
        let cl = cluster.(i) in
        let sz = size.(cl) in
        let kr = k / sz in
        let base = if sum.(cl) > 0 then kr * sum.(cl) else 0 in
        let len = k mod sz in
        let len = if len = 0 then sz else len in
        base + calc_best i len
    ) in
    (*
    Array.iter (Printf.printf "%d ") cluster;
    print_newline ();
    Array.iter (Printf.printf "%d ") size;
    print_newline ();
    Array.iter (Printf.printf "%d ") sum;
    print_newline ();
    Array.iter (Printf.printf "%d ") score;
    print_newline ();
    *)
    Array.fold_left max (-10000000000000) score |> Printf.printf "%d\n"
)

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

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

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


type point = {x:int; y:int}

let () = Scanf.scanf "%d %d" @@ fun n d ->
  let pp = Array.init n @@ fun _ ->
    Scanf.scanf " %d %d" @@ fun a b -> {x = a; y = b}
  in
  let ans = ref 0 in
  for i = 0 to n - 1 do
    if pp.(i).x * pp.(i).x + pp.(i).y * pp.(i).y <= d * d then ans := !ans + 1
  done;
  Printf.printf "%d\n" !ans

Score : 200 points

Problem Statement

We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).

Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?

We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

Constraints

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

0 \leq D \leq 2\times 10^5

|X_i|,|Y_i| \leq 2\times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
\vdots
X_N Y_N

Output

Print an integer representing the number of points such that the distance from the origin is at most D.

Sample Input 1

4 5
0 5
-2 4
3 4
4 -4

Sample Output 1

3

The distance between the origin and each of the given points is as follows:

\sqrt{0^2+5^2}=5

\sqrt{(-2)^2+4^2}=4.472\ldots

\sqrt{3^2+4^2}=5

\sqrt{4^2+(-4)^2}=5.656\ldots

Thus, we have three points such that the distance from the origin is at most 5.

Sample Input 2

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Sample Output 2

7

Multiple points may exist at the same coordinates.

Sample Input 3

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Sample Output 3

6


let () =
  Scanf.scanf "%d\n" @@ fun x ->
  Printf.printf "%d\n"
    (if 400 <= x && x < 600 then 8
     else if 600 <= x && x < 800 then 7
     else if 800 <= x && x < 1000 then 6
     else if 1000 <= x && x < 1200 then 5
     else if 1200 <= x && x < 1400 then 4
     else if 1400 <= x && x < 1600 then 3
     else if 1600 <= x && x < 1800 then 2
     else 1)

Score: 100 points

Problem Statement

M-kun is a competitor in AtCoder, whose highest rating is X.

In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given:

From 400 through 599: 8-kyu

From 600 through 799: 7-kyu

From 800 through 999: 6-kyu

From 1000 through 1199: 5-kyu

From 1200 through 1399: 4-kyu

From 1400 through 1599: 3-kyu

From 1600 through 1799: 2-kyu

From 1800 through 1999: 1-kyu

What kyu does M-kun have?

Constraints

400 \leq X \leq 1999

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the kyu M-kun has, as an integer.
For example, if he has 8-kyu, print 8.

Sample Input 1

725

Sample Output 1

7

M-kun's highest rating is 725, which corresponds to 7-kyu.

Thus, 7 is the correct output.

Sample Input 2

1600

Sample Output 2

2

M-kun's highest rating is 1600, which corresponds to 2-kyu.

Thus, 2 is the correct output.


let kyu x =
  if 400 <= x && x <= 599 then 8
  else if 600 <= x && x <= 799 then 7
  else if 800 <= x && x <= 999 then 6
  else if 1000 <= x && x <= 1199 then 5
  else if 1200 <= x && x <= 1399 then 4
  else if 1400 <= x && x <= 1599 then 3
  else if 1600 <= x && x <= 1799 then 2
  else 1

let () = Printf.printf "%d\n" (kyu (read_int ()))


open Printf
open Scanf

let solve a b c k =
  let rec f x y z = if x < y then (y, z) else f x (y * 2) (z + 1) in
  let (b2, k2) = f a b 0 in
  let (_, k3) = f b2 c k2 in
  if k >= k3 then "Yes" else "No"

let () =
  scanf "%d %d %d %d " solve |> printf "%s\n"

Score: 200 points

Problem Statement

M-kun has the following three cards:

A red card with the integer A.

A green card with the integer B.

A blue card with the integer C.

He is a genius magician who can do the following operation at most K times:

Choose one of the three cards and multiply the written integer by 2.

His magic is successful if both of the following conditions are satisfied after the operations:

The integer on the green card is strictly greater than the integer on the red card.

The integer on the blue card is strictly greater than the integer on the green card.

Determine whether the magic can be successful.

Constraints

1 \leq A, B, C \leq 7

1 \leq K \leq 7

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C
K

Output

If the magic can be successful, print Yes; otherwise, print No.

Sample Input 1

7 2 5
3

Sample Output 1

Yes

The magic will be successful if, for example, he does the following operations:

First, choose the blue card. The integers on the red, green, and blue cards are now 7, 2, and 10, respectively.

Second, choose the green card. The integers on the red, green, and blue cards are now 7, 4, and 10, respectively.

Third, choose the green card. The integers on the red, green, and blue cards are now 7, 8, and 10, respectively.

Sample Input 2

7 4 2
3

Sample Output 2

No

He has no way to succeed in the magic with at most three operations.


let () =
  Scanf.scanf "%d %d\n" @@ fun n k ->
  let arr = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun d -> d in
  let rec makeHyoka i k ans =
    if k = 0 then ans else makeHyoka (i-1) (k-1) (arr.(i)*ans) in
  let brr = Array.make (n-k+1) 0 in
  for i = k to n do
    if i = k then brr.(i-k) <- makeHyoka (i-1) k 1
    else brr.(i-k) <- brr.(i-k-1) * arr.(i-1) / arr.(i-k-1)
  done;
  let h::t = Array.to_list brr in
  let bfr = ref h in
  List.iter (fun x -> if !bfr < x then (bfr := x; print_endline "Yes")
              else (bfr := x; print_endline "No")) t

Score: 300 points

Problem Statement

M-kun is a student in Aoki High School, where a year is divided into N terms.

There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:

For the first through (K-1)-th terms: not given.

For each of the K-th through N-th terms: the multiplication of the scores in the last K exams, including the exam in the graded term.

M-kun scored A_i in the exam at the end of the i-th term.

For each i such that K+1 \leq i \leq N, determine whether his grade for the i-th term is strictly greater than the grade for the (i-1)-th term.

Constraints

2 \leq N \leq 200000

1 \leq K \leq N-1

1 \leq A_i \leq 10^{9}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 A_3 \ldots A_N

Output

Print the answer in N-K lines.

The i-th line should contain Yes if the grade for the (K+i)-th term is greater than the grade for the (K+i-1)-th term, and No otherwise.

Sample Input 1

5 3
96 98 95 100 20

Sample Output 1

Yes
No

His grade for each term is computed as follows:

3-rd term: (96 \times 98 \times 95) = 893760

4-th term: (98 \times 95 \times 100) = 931000

5-th term: (95 \times 100 \times 20) = 190000

Sample Input 2

3 2
1001 869120 1001

Sample Output 2

No

Note that the output should be No if the grade for the 3-rd term is equal to the grade for the 2-nd term.

Sample Input 3

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

Sample Output 3

Yes
Yes
No
Yes
Yes
No
Yes
Yes


open Printf
open Scanf

let id x = x

let solve n k =
  let aa = Array.init n @@ fun _ -> scanf "%d " id in
  for i = k to n - 1 do
    printf "%s\n" @@ if aa.(i-k) < aa.(i) then "Yes" else "No"
  done

let () =
  scanf "%d %d " solve


open Batteries
open Printf

let ($) g f x = g (f x)

let swap = Tuple2.swap

let s2i = int_of_string
let i2s = string_of_int
let s2f = float_of_string
let f2s = string_of_float
let c2i = int_of_char
let i2c = char_of_int
let f2i = int_of_float
let i2f = float_of_int

let c2s = String.of_char
let s2cl = String.to_list
let cl2s = String.of_list

let puts s = print_endline s
let putw ?yn:(yn=("Yes", "No")) b = puts (if b then fst yn else snd yn)
let puti i = puts @@ i2s i

module StaleList = struct
  include List

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let nempty l = not @@ is_empty l

  let hdop l = if nempty l then Some (hd l) else None

  (* let taker = drop *)
  let takewh = take_while

  (* let dropr = take *)
  let dropwh = drop_while

  let split_by = span

  let chunk = ntake

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  let partition_to_map f l =
    foldr (fun x m -> Map.modify_opt (f x) (function
      | None -> Some [x]
      | Some [] -> Some [x]
      | Some vl -> Some (x::vl)) m) Map.empty l;;

  let scanl f z ls =
    let rec loop acl acc = function
      | [] -> rev acl
      | h::t ->
        let r = f acc h in
        loop (r::acl) r t
    in loop [] z ls

  let scanr f z ls =
    let rec loop acl acc = function
      | [] -> acl
      | h::t ->
        let r = f h acc in
        loop (r::acl) r t
    in loop [] z (rev ls)

  (* let scanli = scan_lefti *)
  (* let scanri = scan_righti *)

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i

end

module L = StaleList

module StaleArray = struct
  include Array

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let is_empty r = len r = 0
  let nempty r = len r > 0

  let take n r = left r n
  let taker n r = right r n

  let takeb x r =
    let l = len r in
    let rec loop i =
      if i >= l then r
      else if r.(i) = x then take i r
      else loop (i + 1)
    in loop 0

  (* let takewh = take_while *)

  let drop n r = tail r n
  let dropr n r = take ((len r) - n) r
  (* let dropwh = drop_while *)

  let index_of x r =
    let l = len r in
    let rec loop i =
      if i >= l then None
      else if r.(i) = x then Some i
      else loop (i + 1)
    in loop 0

  (* let split_by = span *)

  (* let chunk = ntake *)

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  (* let partition_to_map f l = *)
  (*   foldr (fun x m -> Map.modify_opt (f x) (function *)
  (*     | None -> Some [x]  *)
  (*     | Some [] -> Some [x]  *)
  (*     | Some vl -> Some (x::vl)) m) Map.empty l;; *)

  (* let scanl = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let concat2 = append

  let flatmap (f : 'a -> 'b array) a =
    map f a |> enum |> L.of_enum |> concat

  let zipf = map2
  (* let zipfi = map2i *)

end

module A = StaleArray

module StaleString = struct
  include String

  let len = length

  let replace_chars = map
  let map = replace

  let maptol f s = L.map f (s2cl s)
  let maptoli f s = L.map f (s2cl s)

  let zipf f a b = L.zipf f (s2cl a) (s2cl b)
  let zipfi f a b = L.zipfi f (s2cl a) (s2cl b)

  let mkstr f sep ls =
    L.foldl (fun acc x -> acc ^ sep ^ (f x)) (f @@ L.hd ls) (List.tl ls)

end

module S = StaleString

let spsp s = S.split_on_char ' ' s

module StaleSortedSet = struct
  include Set

  module Make (Ord : Set.OrderedType) = struct
    include Set.Make(Ord)

    let nmem x st = not @@ mem x st

    let foldl f s z = fold (fun x a -> f a x) z s

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let foldl f s z = fold (fun x a -> f a x) z s

  let size = cardinal
end

module Ss = StaleSortedSet

module StaleSortedMap  = struct
  include Map

  module Make (Ord : Map.OrderedType) = struct
    include Map.Make(Ord)

    let nmem x st = not @@ mem x st

    let get = find
    let get_or x d m = find_default d x m

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let get = find
  let get_or x d m = find_default d x m

  let size = cardinal
end

module Ms = StaleSortedMap

module StaleRange = struct

  type t = Range of int * int

  let make lb ub = Range (lb, ub)

  let to_list r =
    let Range (lb, ub) = r in
    L.make (ub - lb) ((+) lb)

  let to_array r =
    let Range (lb, ub) = r in
      A.make (ub - lb) ((+) lb)

  let iter r f =
    let Range (lb, ub) = r in
    for i = lb to ub do f i done

  let iter2 r1 r2 f =
    let Range (lb1, ub1) = r1 and Range (lb2, ub2) = r2 in
      for i = lb1 to ub2 do
        for j = lb2 to ub2 do
          f i j
        done
      done
end

module R = StaleRange

let (---) lb ub = R.make lb ub
let (--^) lb ub = R.make lb (ub - 1)

module StaleGenericAlgorithms = struct

  let set_power ls =
    let rec loop ls pls =
      match ls with
      | [] -> pls
      | hd::tl -> loop tl (L.flatmap (fun p -> [p; hd::p]) pls)
    in loop ls [[]]

  let rec bsearch_max_int f lb ub =
    if lb >= ub then (if f lb then lb else (lb - 1))
    else (
      let m = (lb + ub) / 2 in
      if f m then bsearch_max_int f (m + 1) ub
      else bsearch_max_int f lb m
    )

  let partial_sum n ls =
    let rec loop s k = function
      | [] -> s
      | h::t ->
        if k >= n then s
        else loop (s +. h) (k + 1) t
    in
    loop 0.0 0 ls

  let partial_mul n ls =
    let rec loop s k = function
      | [] -> s
      | h::t ->
        if k >= n then s
        else loop (s * h) (k + 1) t
    in
    loop 1 0 ls
end

module Gal = StaleGenericAlgorithms

let rds () = read_line ()

let rdi () = s2i @@ rds ()

let rdhs () = spsp @@ rds ()
let rdhi () = rdhs () |> L.map s2i

let rdhf () = rdhs () |> L.map s2f

let rdf2 () = match rdhf () with
| a::b::_ -> (a, b)
| _ -> (0., 0.)

let rdf3 () = match rdhf () with
| a::b::c::_ -> (a, b, c)
| _ -> (0., 0., 0.)

let rdf4 () = match rdhf () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0., 0., 0., 0.)

let rds2 () = match rdhs () with
  | a::b::_ -> (a, b)
  | _ -> ("", "")

let rdi2 () = match rdhi () with
  | a::b::_ -> (a, b)
  | _ -> (0, 0)

let rdi3 () = match rdhi () with
| a::b::c::_ -> (a, b, c)
| _ -> (0, 0, 0)

let rdi4 () = match rdhi () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0, 0, 0, 0)

let rdi5 () = match rdhi () with
| a::b::c::d::e::_ -> (a, b, c, d, e)
| _ -> (0, 0, 0, 0, 0)

let rdv n rf =
  let rec loop n =
    if n <= 0 then []
    else (
      let s = rf () in
      s::(loop (n - 1))
    )
  in loop n

let rdvi n = rdv n rdi
let rdvi2 n = rdv n rdi2
let rdvi3 n = rdv n rdi3
let rdvi4 n = rdv n rdi4

let print_list aa =
  printf "[ "; aa |> L.iter (fun a -> printf "%d " a); puts "]"

let print_array aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%d " a); puts "]"

let print_carray aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%c " a); puts "]"

let print_matrix mat =
  puts "----";
  mat |> A.iter (fun r -> print_carray r);
  puts "----"

let _ =
  let (n, k) = rdi2 () in
  let al = rdhi () |> L.map i2f |> L.map log in
  let scores = A.make (n+1) 0.0 in
  scores.(k) <- Gal.partial_sum k al;
  let aa = A.of_list (1.0::al) in
  R.iter ((k+1)---n)  (fun t ->
    scores.(t) <- scores.(t - 1) +. aa.(t) -. aa.(t - k));
  R.iter ((k+1)---n) (fun i -> putw (scores.(i - 1) < scores.(i)));
  ()


open Batteries
open Printf

let ($) g f x = g (f x)

let swap = Tuple2.swap

let s2i = int_of_string
let i2s = string_of_int
let s2f = float_of_string
let f2s = string_of_float
let c2i = int_of_char
let i2c = char_of_int
let f2i = int_of_float
let i2f = float_of_int

let c2s = String.of_char
let s2cl = String.to_list
let cl2s = String.of_list

let puts s = print_endline s
let putw ?yn:(yn=("Yes", "No")) b = puts (if b then fst yn else snd yn)
let puti i = puts @@ i2s i

module StaleList = struct
  include List

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let nempty l = not @@ is_empty l

  let hdop l = if nempty l then Some (hd l) else None

  (* let taker = drop *)
  let takewh = take_while

  (* let dropr = take *)
  let dropwh = drop_while

  let split_by = span

  let chunk = ntake

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  let partition_to_map f l =
    foldr (fun x m -> Map.modify_opt (f x) (function
      | None -> Some [x]
      | Some [] -> Some [x]
      | Some vl -> Some (x::vl)) m) Map.empty l;;

  let scanl f z ls =
    let rec loop acl acc = function
      | [] -> rev acl
      | h::t ->
        let r = f acc h in
        loop (r::acl) r t
    in loop [] z ls

  let scanr f z ls =
    let rec loop acl acc = function
      | [] -> acl
      | h::t ->
        let r = f h acc in
        loop (r::acl) r t
    in loop [] z (rev ls)

  (* let scanli = scan_lefti *)
  (* let scanri = scan_righti *)

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i

end

module L = StaleList

module StaleArray = struct
  include Array

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let is_empty r = len r = 0
  let nempty r = len r > 0

  let take n r = left r n
  let taker n r = right r n

  let takeb x r =
    let l = len r in
    let rec loop i =
      if i >= l then r
      else if r.(i) = x then take i r
      else loop (i + 1)
    in loop 0

  (* let takewh = take_while *)

  let drop n r = tail r n
  let dropr n r = take ((len r) - n) r
  (* let dropwh = drop_while *)

  let index_of x r =
    let l = len r in
    let rec loop i =
      if i >= l then None
      else if r.(i) = x then Some i
      else loop (i + 1)
    in loop 0

  (* let split_by = span *)

  (* let chunk = ntake *)

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  (* let partition_to_map f l = *)
  (*   foldr (fun x m -> Map.modify_opt (f x) (function *)
  (*     | None -> Some [x]  *)
  (*     | Some [] -> Some [x]  *)
  (*     | Some vl -> Some (x::vl)) m) Map.empty l;; *)

  (* let scanl = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let concat2 = append

  let flatmap (f : 'a -> 'b array) a =
    map f a |> enum |> L.of_enum |> concat

  let zipf = map2
  (* let zipfi = map2i *)

end

module A = StaleArray

module StaleString = struct
  include String

  let len = length

  let replace_chars = map
  let map = replace

  let maptol f s = L.map f (s2cl s)
  let maptoli f s = L.map f (s2cl s)

  let zipf f a b = L.zipf f (s2cl a) (s2cl b)
  let zipfi f a b = L.zipfi f (s2cl a) (s2cl b)

  let mkstr f sep ls =
    L.foldl (fun acc x -> acc ^ sep ^ (f x)) (f @@ L.hd ls) (List.tl ls)

end

module S = StaleString

let spsp s = S.split_on_char ' ' s

module StaleSortedSet = struct
  include Set

  module Make (Ord : Set.OrderedType) = struct
    include Set.Make(Ord)

    let nmem x st = not @@ mem x st

    let foldl f s z = fold (fun x a -> f a x) z s

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let foldl f s z = fold (fun x a -> f a x) z s

  let size = cardinal
end

module Ss = StaleSortedSet

module StaleSortedMap  = struct
  include Map

  module Make (Ord : Map.OrderedType) = struct
    include Map.Make(Ord)

    let nmem x st = not @@ mem x st

    let get = find
    let get_or x d m = find_default d x m

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let get = find
  let get_or x d m = find_default d x m

  let size = cardinal
end

module Ms = StaleSortedMap

module StaleRange = struct

  type t = Range of int * int

  let make lb ub = Range (lb, ub)

  let to_list r =
    let Range (lb, ub) = r in
    L.make (ub - lb) ((+) lb)

  let to_array r =
    let Range (lb, ub) = r in
      A.make (ub - lb) ((+) lb)

  let iter r f =
    let Range (lb, ub) = r in
    for i = lb to ub do f i done

  let iter2 r1 r2 f =
    let Range (lb1, ub1) = r1 and Range (lb2, ub2) = r2 in
      for i = lb1 to ub2 do
        for j = lb2 to ub2 do
          f i j
        done
      done
end

module R = StaleRange

let (---) lb ub = R.make lb ub
let (--^) lb ub = R.make lb (ub - 1)

module StaleGenericAlgorithms = struct

  let set_power ls =
    let rec loop ls pls =
      match ls with
      | [] -> pls
      | hd::tl -> loop tl (L.flatmap (fun p -> [p; hd::p]) pls)
    in loop ls [[]]

  let rec bsearch_max_int f lb ub =
    if lb >= ub then (if f lb then lb else (lb - 1))
    else (
      let m = (lb + ub) / 2 in
      if f m then bsearch_max_int f (m + 1) ub
      else bsearch_max_int f lb m
    )

  let partial_sum n ls =
    let rec loop s k = function
      | [] -> s
      | h::t ->
        if k >= n then s
        else loop (s + h) (k + 1) t
    in
    loop 0 0 ls

  let partial_mul n ls =
    let rec loop s k = function
      | [] -> s
      | h::t ->
        if k >= n then s
        else loop (s * h) (k + 1) t
    in
    loop 1 0 ls
end

module Gal = StaleGenericAlgorithms

let rds () = read_line ()

let rdi () = s2i @@ rds ()

let rdhs () = spsp @@ rds ()
let rdhi () = rdhs () |> L.map s2i

let rdhf () = rdhs () |> L.map s2f

let rdf2 () = match rdhf () with
| a::b::_ -> (a, b)
| _ -> (0., 0.)

let rdf3 () = match rdhf () with
| a::b::c::_ -> (a, b, c)
| _ -> (0., 0., 0.)

let rdf4 () = match rdhf () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0., 0., 0., 0.)

let rds2 () = match rdhs () with
  | a::b::_ -> (a, b)
  | _ -> ("", "")

let rdi2 () = match rdhi () with
  | a::b::_ -> (a, b)
  | _ -> (0, 0)

let rdi3 () = match rdhi () with
| a::b::c::_ -> (a, b, c)
| _ -> (0, 0, 0)

let rdi4 () = match rdhi () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0, 0, 0, 0)

let rdi5 () = match rdhi () with
| a::b::c::d::e::_ -> (a, b, c, d, e)
| _ -> (0, 0, 0, 0, 0)

let rdv n rf =
  let rec loop n =
    if n <= 0 then []
    else (
      let s = rf () in
      s::(loop (n - 1))
    )
  in loop n

let rdvi n = rdv n rdi
let rdvi2 n = rdv n rdi2
let rdvi3 n = rdv n rdi3
let rdvi4 n = rdv n rdi4

let print_list aa =
  printf "[ "; aa |> L.iter (fun a -> printf "%d " a); puts "]"

let print_array aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%d " a); puts "]"

let print_carray aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%c " a); puts "]"

let print_matrix mat =
  puts "----";
  mat |> A.iter (fun r -> print_carray r);
  puts "----"

let _ =
  let (n, k) = rdi2 () in
  let al = rdhi () in
  let scores = A.make (n+1) 0 in
  scores.(k) <- Gal.partial_mul k al;
  let aa = A.of_list (1::al) in
  R.iter ((k+1)---n)  (fun t ->
    scores.(t) <- scores.(t - 1) * aa.(t) / aa.(t - k));
  R.iter ((k+1)---n) (fun i -> putw (scores.(i - 1) < scores.(i)));
  ()


Scanf.scanf "%d" (fun n ->
    let xyp = Array.init n (fun _ -> Scanf.scanf " %d %d %d" (fun x y p -> x, y, p)) in

    let vp = Array.init n (fun i ->
        let me, _, p = xyp.(i) in
        Array.init (1 lsl n) (fun bit ->
            let rec loop j acc =
                if j = n then acc * p else
                    if bit land (1 lsl j) = 0 then loop (j + 1) acc else
                        let k, _, _ = xyp.(j) in
                        let acc = min acc (abs (k - me)) in
                        loop (j + 1) acc
            in
            loop 0 (abs me)
        )
    ) in
    let hp = Array.init n (fun i ->
        let _, me, p = xyp.(i) in
        Array.init (1 lsl n) (fun bit ->
            let rec loop j acc =
                if j = n then acc * p else
                    if bit land (1 lsl j) = 0 then loop (j + 1) acc else
                        let _, k, _ = xyp.(j) in
                        let acc = min acc (abs (k - me)) in
                        loop (j + 1) acc
            in
            loop 0 (abs me)
        )
    ) in

    let best = Array.make (n + 1) max_int in
    let calc h v =
        let rec loop i acc =
            if i = n then acc else
                loop (i + 1) (acc + min vp.(i).(v) hp.(i).(h))
        in
        loop 0 0
    in

    let rec loop i c hbit vbit =
        best.(c) <- if best.(c) = 0 then 0 else min best.(c) (calc hbit vbit);
        if i < n then (
            let li = 1 lsl i in
            loop (i + 1) c       hbit          vbit;
            loop (i + 1) (c + 1) (hbit lor li) vbit;
            loop (i + 1) (c + 1) hbit          (vbit lor li);
        )
    in
    loop 0 0 0 0;

    Array.iter (Printf.printf "%d\n") best;
)

Score: 500 points

Problem Statement

New AtCoder City has an infinite grid of streets, as follows:

At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.

A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.

A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.

There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.

The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.

M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.

Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.

M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.

For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?

Constraints

1 \leq N \leq 15

-10 \ 000 \leq X_i \leq 10 \ 000

-10 \ 000 \leq Y_i \leq 10 \ 000

1 \leq P_i \leq 1 \ 000 \ 000

The locations of the N residential areas, (X_i, Y_i), are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N

Output

Print the answer in N+1 lines.

The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.

Sample Input 1

3
1 2 300
3 3 600
1 4 800

Sample Output 1

2900
900
0
0

When K = 0, the residents of Area 1, 2, and 3 have to walk the distances of 1, 3, and 1, respectively, to reach a railroad.

Thus, the sum of the walking distances of all citizens, S, is 1 \times 300 + 3 \times 600 + 1 \times 800 = 2900.

When K = 1, if we build a railroad along the street corresponding to the line y = 4 in the coordinate plane, the walking distances of the citizens of Area 1, 2, and 3 become 1, 1, and 0, respectively.

Then, S = 1 \times 300 + 1 \times 600 + 0 \times 800 = 900.

We have many other options for where we build the railroad, but none of them makes S less than 900.

When K = 2, if we build a railroad along the street corresponding to the lines x = 1 and x = 3 in the coordinate plane, all citizens can reach a railroad with the walking distance of 0, so S = 0. We can also have S = 0 when K = 3.

The figure below shows the optimal way to build railroads for the cases K = 0, 1, 2.

The street painted blue represents the roads along which we build railroads.

Sample Input 2

5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400

Sample Output 2

13800
1600
0
0
0
0

The figure below shows the optimal way to build railroads for the cases K = 1, 2.

Sample Input 3

6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200

Sample Output 3

26700
13900
3200
1200
0
0
0

The figure below shows the optimal way to build railroads for the case K = 3.

Sample Input 4

8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903

Sample Output 4

2576709
1569381
868031
605676
366338
141903
0
0
0

The figure below shows the optimal way to build railroads for the case K = 4.


Scanf.scanf "%d %d %d" (fun l r d -> Printf.printf "%d" (r / d - (l - 1) / d))

Score : 100 points

Problem Statement

How many multiples of d are there among the integers between L and R (inclusive)?

Constraints

All values in input are integers.

1 \leq L \leq R \leq 100

1 \leq d \leq 100

Input

Input is given from Standard Input in the following format:

L R d

Output

Print the number of multiples of d among the integers between L and R (inclusive).

Sample Input 1

5 10 2

Sample Output 1

3

Among the integers between 5 and 10, there are three multiples of 2: 6, 8, and 10.

Sample Input 2

6 20 7

Sample Output 2

2

Among the integers between 6 and 20, there are two multiples of 7: 7 and 14.

Sample Input 3

1 100 1

Sample Output 3

100


open Printf
open Scanf

let solve l r d = r / d - (l - 1) / d

let () =
  scanf "%d %d %d " solve |> printf "%d\n"


module IntMap = Map.Make (struct
  type t = int
  let compare = compare
end)

let rec inchworm i j m (((k, d) :: klrs') as klrs) c =
  if i < k
  then c klrs j m
  else inchworm i (j + 1) (IntMap.update d (fun o -> Some (1 + Option.value ~default:0 o)) m) klrs' c

let rec sieve i k j m =
  if j <= i + 1
  then k j m
  else
    sieve i k (j - 1) @@
    match IntMap.min_binding m with
    | (d, 1) -> IntMap.remove d m
    | (d, n) -> IntMap.add d (n - 1) m

let rec solve n i klrs j m =
  if n <= i
  then IntMap.fold (fun d n -> ( + ) @@ d * n) m 0
  else
    inchworm i j m klrs @@ fun klrs ->
      sieve i @@ solve n (i + 1) klrs

let () = Scanf.scanf "%d\n" @@ fun t ->
  for i = 1 to t do
    Scanf.scanf "%d\n" @@ fun n ->
      let klrs = List.init n @@ fun _ ->
        Scanf.scanf "%d %d %d\n" @@ fun k l r -> (k - 1, l, r) in
      let left, right = List.partition (fun (_, l, r) -> r <= l) klrs in
      Printf.printf "%d\n" @@
      List.fold_left (fun sum (_, l, r) -> sum + min l r) 0 klrs
      + solve n 0
          (List.sort (fun (k, _) (k', _) -> compare k k')
            ((n, 0) :: List.map (fun (k, l, r) -> (k, l - r)) left)) 0 IntMap.empty
      + solve n 0
          (List.sort (fun (k, _) (k', _) -> compare k k')
            ((n, 0) :: List.filter_map (fun (k, l, r) -> if n - k - 2 < 0 then None else Some (n - k - 2, r - l)) right)) 0 IntMap.empty
  done

Score : 500 points

Problem Statement

We have N camels numbered 1,2,\ldots,N.
Snuke has decided to make them line up in a row.

The happiness of Camel i will be L_i if it is among the K_i frontmost camels, and R_i otherwise.

Snuke wants to maximize the total happiness of the camels. Find the maximum possible total happiness of the camel.

Solve this problem for each of the T test cases given.

Constraints

All values in input are integers.

1 \leq T \leq 10^5

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

1 \leq K_i \leq N

1 \leq L_i, R_i \leq 10^9

The sum of values of N in each input file is at most 2 \times 10^5.

Input

Input is given from Standard Input in the following format:

T
\mathrm{case}_1
\vdots
\mathrm{case}_T

Each case is given in the following format:

N
K_1 L_1 R_1
\vdots
K_N L_N R_N

Output

Print T lines. The i-th line should contain the answer to the i-th test case.

Sample Input 1

3
2
1 5 10
2 15 5
3
2 93 78
1 71 59
3 57 96
19
19 23 16
5 90 13
12 85 70
19 67 78
12 16 60
18 48 28
5 4 24
12 97 97
4 57 87
19 91 74
18 100 76
7 86 46
9 100 57
3 76 73
6 84 93
1 6 84
11 75 94
19 15 3
12 11 34

Sample Output 1

25
221
1354

In the first test case, it is optimal to line up the camels in the order 2, 1.

Camel 1 is not the frontmost camel, so its happiness will be 10.

Camel 2 is among the two frontmost camels, so its happiness will be 15.

In the second test case, it is optimal to line up the camels in the order 2, 1, 3.

Camel 1 is among the two frontmost camels, so its happiness will be 93.

Camel 2 is the frontmost camel, so its happiness will be 71.

Camel 3 is among the three frontmost camels, so its happiness will be 57.


Scanf.scanf "%d" (fun t ->
    let module S = Set.Make (struct type t = int * int let compare = compare end) in
    for i = 1 to t do
        Scanf.scanf " %d" (fun n ->
            let klr = Array.init n (fun _ -> Scanf.scanf " %d %d %d" (fun k l r -> k, l, r)) in
            let sum = Array.fold_left (fun acc (_, l, r) -> acc + min l r) 0 klr in

            let rec loop i left right =
                if i = n then Array.of_list left, Array.of_list right else
                    let k, l, r = klr.(i) in
                    if l > r then loop (i + 1) ((k, l - r) :: left) right
                             else loop (i + 1) left ((n - k, r - l) :: right)
            in
            let left, right = loop 0 [] [] in
            Array.sort compare left;
            Array.sort compare right;
            let proc a =
                let len = Array.length a in
                let rec loop i j acc set ct =
                    if i = len then acc else
                        let k, dif =  a.(i) in
                        if k > j then loop i (j + 1) acc set ct else
                            let set = S.add (dif, i) set in
                            let ct = ct + 1 in
                            let acc = acc + dif in
                            if ct <= k then loop (i + 1) j acc set ct else
                                let ((dif, _) as m) = S.min_elt set in
                                let set = S.remove m set in
                                let ct = ct - 1 in
                                let acc = acc - dif in
                                loop (i + 1) j acc set ct
                in
                loop 0 0 0 S.empty 0
            in
            Printf.printf "%d\n" @@ sum + proc left + proc right
        )
    done
)


open Batteries
open Printf

let ($) g f x = g (f x)

let swap = Tuple2.swap

let s2i = int_of_string
let i2s = string_of_int
let s2f = float_of_string
let f2s = string_of_float
let c2i = int_of_char
let i2c = char_of_int
let f2i = int_of_float
let i2f = float_of_int

let c2s = String.of_char
let s2cl = String.to_list
let cl2s = String.of_list

let puts s = print_endline s
let putyn b = puts (if b then "Yes" else "No")
let puti i = puts @@ i2s i

let rep lb bnd ub f = match bnd with
  | `To -> for i = lb to ub do f i done
  | `Til -> for i = lb to (ub - 1) do f i done

let rep2 lb1 bnd1 ub1 () lb2 bnd2 ub2 f =
  match (bnd1, bnd2) with
  | (`To, `To) -> for i = lb1 to ub1 do for j = lb2 to ub2 do f i j done done
  | (`To, `Til) -> for i = lb1 to ub1 do for j = lb2 to (ub2 - 1) do f i j done done
  | (`Til, `To) -> for i = lb1 to (ub1 - 1) do for j = lb2 to ub2 do f i j done done
  | (`Til, `Til) -> for i = lb1 to (ub1 - 1) do for j = lb2 to (ub2 - 1) do f i j done done

module JunkList = struct
  include List

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let nempty l = not @@ is_empty l

  let hdop l = if nempty l then Some (hd l) else None

  (* let taker = drop *)
  let takewh = take_while

  (* let dropr = take *)
  let dropwh = drop_while

  let split_by = span

  let chunk = ntake

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  let partition_to_map f l =
    foldr (fun x m -> Map.modify_opt (f x) (function
      | None -> Some [x]
      | Some [] -> Some [x]
      | Some vl -> Some (x::vl)) m) Map.empty l;;

  let scanl f z ls =
    let rec loop acl acc = function
      | [] -> rev acl
      | h::t ->
        let r = f acc h in
        loop (r::acl) r t
    in loop [] z ls

  let scanr f z ls =
    let rec loop acl acc = function
      | [] -> acl
      | h::t ->
        let r = f h acc in
        loop (r::acl) r t
    in loop [] z (rev ls)

  (* let scanli = scan_lefti *)
  (* let scanri = scan_righti *)

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i

end

module L = JunkList

module JunkArray = struct
  include Array

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let is_empty r = len r = 0
  let nempty r = len r > 0

  let take n r = left r n
  let taker n r = right r n

  let takeb x r =
    let l = len r in
    let rec loop i =
      if i >= l then r
      else if r.(i) = x then take i r
      else loop (i + 1)
    in loop 0

  (* let takewh = take_while *)

  let drop n r = tail r n
  let dropr n r = take ((len r) - n) r
  (* let dropwh = drop_while *)

  let index_of x r =
    let l = len r in
    let rec loop i =
      if i >= l then None
      else if r.(i) = x then Some i
      else loop (i + 1)
    in loop 0

  (* let split_by = span *)

  (* let chunk = ntake *)

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  (* let partition_to_map f l = *)
  (*   foldr (fun x m -> Map.modify_opt (f x) (function *)
  (*     | None -> Some [x]  *)
  (*     | Some [] -> Some [x]  *)
  (*     | Some vl -> Some (x::vl)) m) Map.empty l;; *)

  (* let scanl = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let concat2 = append

  let flatmap (f : 'a -> 'b array) a =
    map f a |> enum |> L.of_enum |> concat

  let zipf = map2
  (* let zipfi = map2i *)

end

module A = JunkArray

module JunkString = struct
  include String

  let len = length

  let replace_chars = map
  let map = replace

  let maptol f s = L.map f (s2cl s)
  let maptoli f s = L.map f (s2cl s)

  let zipf f a b = L.zipf f (s2cl a) (s2cl b)
  let zipfi f a b = L.zipfi f (s2cl a) (s2cl b)

  let mkstr f sep ls =
    L.foldl (fun acc x -> acc ^ sep ^ (f x)) (f @@ L.hd ls) (List.tl ls)

end

module S = JunkString

let spsp s = S.split_on_char ' ' s

module JunkSortedSet = struct
  include Set

  module Make (Ord : Set.OrderedType) = struct
    include Set.Make(Ord)

    let nmem x st = not @@ mem x st

    let foldl f s z = fold (fun x a -> f a x) z s

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let foldl f s z = fold (fun x a -> f a x) z s

  let size = cardinal
end

module Ss = JunkSortedSet

module JunkSortedMap  = struct
  include Map

  module Make (Ord : Map.OrderedType) = struct
    include Map.Make(Ord)

    let nmem x st = not @@ mem x st

    let get = find
    let get_or x d m = find_default d x m

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let get = find
  let get_or x d m = find_default d x m

  let size = cardinal
end

module Ms = JunkSortedMap

let set_power ls =
  let rec loop ls pls =
    match ls with
    | [] -> pls
    | hd::tl -> loop tl (L.flatmap (fun p -> [p; hd::p]) pls)
  in loop ls [[]]

exception ArithmeticException of string

module JunkIntArithmetic = struct

  let rec power x e =
    if e = 0 then x
    else
      let rec loop r x2 e' =
        if e' = 0 then r
        else if e' land 1 = 0 then loop r (x2 * x2) (e' lsr 1)
        else loop (r * x2) (x2 * x2) (e' lsr 1)
      in loop 1 x e

  let rec powers_le_1000 x =
    if x > 32 then [x]
    else
      L.init 9 (fun e -> power x (e + 1))
      |> L.filter (fun y -> y < 1000)

  let primes_le_1000 = [2;3;5;7;11;13;17;19;23;29;31;37;41;
    43;47;53;59;61;67;71;73;79;83;89;97;101;
    103;107;109;113;127;131;137;139;149;151;157;163;167;
    173;179;181;191;193;197;199;211;223;227;229;233;239;
    241;251;257;263;269;271;277;281;283;293;307;311;313;
    317;331;337;347;349;353;359;367;373;379;383;389;397;
    401;409;419;421;431;433;439;443;449;457;461;463;467;
    479;487;491;499;503;509;521;523;541;547;557;563;569;
    571;577;587;593;599;601;607;613;617;619;631;641;643;
    647;653;659;661;673;677;683;691;701;709;719;727;733;
    739;743;751;757;761;769;773;787;797;809;811;821;823;
    827;829;839;853;857;859;863;877;881;883;887;907;911;
    919;929;937;941;947;953;967;971;977;983;991;997]

    let primes_and_powers_le_1000 =
      [2;3;4;5;7;8;9;11;13;16;17;19;23;25;27;29;31;32;37;41;
      43;47;49;53;59;61;64;67;71;73;79;81;83;89;97;
      101;103;107;109;113;121;125;127;128;131;137;139;149;151;
      157;163;167;169;173;179;181;191;193;197;199;211;223;227;
      229;233;239;241;243;251;256;257;263;269;271;277;281;283;
      289;293;307;311;313;317;331;337;343;347;349;353;359;361;
      367;373;379;383;389;397;401;409;419;421;431;433;439;443;
      449;457;461;463;467;479;487;491;499;503;509;512;521;523;
      529;541;547;557;563;569;571;577;587;593;599;601;607;613;
      617;619;625;631;641;643;647;653;659;661;673;677;683;691;
      701;709;719;727;729;733;739;743;751;757;761;769;773;787;
      797;809;811;821;823;827;829;839;841;853;857;859;863;877;
      881;883;887;907;911;919;929;937;941;947;953;961;967;971;
      977;983;991;997]

  let factorize_with ps n =
    let rec loop acc ps e n' =
      if n' <= 1 then ([], n')
      else
        match ps with
        | [] -> (acc, n')
        | p::t ->
          let r = n' mod p in
          if r = 0 then (
            if n' = p then ((p, e + 1) :: acc, 1)
            else loop acc ps (e + 1) (n' / p)
          ) else
            loop (if e = 0 then acc else (p, e) :: acc) t 0 n'
    in
    let (fs, r) = loop [] ps 0 n in
    (L.rev fs, r)

  let factorize_le_million n =
    factorize_with primes_le_1000 n

  let rec to_bits_le n =
    if n = 0 then []
    else (n mod 2) :: to_bits_le (n lsr 1)

  let rec gcd x y =
    match x mod y with
    | 0 -> y
    | z -> gcd y z

  let ext_euclid a b =
    let rec next (r0, s0, t0) (r1, s1, t1) =
      match r1 with
      | 0 -> (r0, s0, t0)
      | r2 ->
        let q = r0 / r1 in
        next (r1, s1, t1) (r0 - q * r1, s0 - q * s1, t0 - q * t1)
    in
    if a < b then
      let (g, y, x) = next (b, 1, 0) (a, 0, 1) in (g, x, y)
    else
      next (a, 1, 0) (b, 0, 1)

  let modinv x m =
    let (g, y, z) = ext_euclid x m in
    match g with
    | 1 -> y mod m
    | _ -> raise @@ ArithmeticException "Not relatively prime"

end

module N = JunkIntArithmetic

let rds () = read_line ()

let rdi () = s2i @@ rds ()

let rdhs () = spsp @@ rds ()
let rdhi () = rdhs () |> L.map s2i

let rdhf () = rdhs () |> L.map s2f

let rdf2 () = match rdhf () with
| a::b::_ -> (a, b)
| _ -> (0., 0.)

let rdf3 () = match rdhf () with
| a::b::c::_ -> (a, b, c)
| _ -> (0., 0., 0.)

let rdf4 () = match rdhf () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0., 0., 0., 0.)

let rds2 () = match rdhs () with
  | a::b::_ -> (a, b)
  | _ -> ("", "")

let rdi2 () = match rdhi () with
  | a::b::_ -> (a, b)
  | _ -> (0, 0)

let rdi3 () = match rdhi () with
| a::b::c::_ -> (a, b, c)
| _ -> (0, 0, 0)

let rdi4 () = match rdhi () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0, 0, 0, 0)

let rdi5 () = match rdhi () with
| a::b::c::d::e::_ -> (a, b, c, d, e)
| _ -> (0, 0, 0, 0, 0)

let rdv n rf =
  let rec loop n =
    if n <= 0 then []
    else (
      let s = rf () in
      s::(loop (n - 1))
    )
  in loop n

let rdvi n = rdv n rdi
let rdvi2 n = rdv n rdi2
let rdvi3 n = rdv n rdi3
let rdvi4 n = rdv n rdi4

let print_list aa =
  printf "[ "; aa |> L.iter (fun a -> printf "%d " a); puts "]"

let print_array aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%d " a); puts "]"

let _ =
  let n = rdi () in
  let ss = rdv n rds in
  let res = A.make 4 0 in

  let inc i = res.(i) <- res.(i) + 1 in

  let rec loop = function
  | [] -> ()
  | "AC"::t -> inc 0; loop t
  | "WA"::t -> inc 1; loop t
  | "TLE"::t -> inc 2; loop t
  | "RE"::t -> inc 3; loop t
  | _ -> ()
  in

  loop ss;
  printf "AC x %d\nWA x %d\nTLE x %d\nRE x %d\n" res.(0) res.(1) res.(2) res.(3);
  ()

Score : 200 points

Problem Statement

Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.

The problem has N test cases.

For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively.

See the Output section for the output format.

Constraints

1 \leq N \leq 10^5

S_i is AC, WA, TLE, or RE.

Input

Input is given from Standard Input in the following format:

N
S_1
\vdots
S_N

Output

Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively. Print the following:

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Sample Input 1

6
AC
TLE
AC
AC
WA
TLE

Sample Output 1

AC x 3
WA x 1
TLE x 2
RE x 0

We have 3, 1, 2, and 0 test case(s) for which the verdict is AC, WA, TLE, and RE, respectively.

Sample Input 2

10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC

Sample Output 2

AC x 10
WA x 0
TLE x 0
RE x 0


let () =
	let arr = Array.make 4 0 in
	Scanf.scanf "%d\n" @@ fun n ->
    for i = 0 to n - 1 do
    	Scanf.scanf "%s\n" @@ fun s ->
        if s = "AC" then arr.(0) <- arr.(0) + 1
        else if s = "WA" then arr.(1) <- arr.(1) + 1
        else if s = "TLE" then arr.(2) <- arr.(2) + 1
        else arr.(3) <- arr.(3) + 1
    done;
    Printf.printf "AC x %d\n" arr.(0);
    Printf.printf "WA x %d\n" arr.(1);
    Printf.printf "TLE x %d\n" arr.(2);
    Printf.printf "RE x %d\n" arr.(3);


let split_string ?(pattern="") = Str.split @@ Str.regexp pattern
let n = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n
let a = read_line () |> split_string ~pattern:" " |> List.map int_of_string |> List.sort compare |> List.rev

let rec loop sum acc = function
  | 0 -> sum
  | 1 -> sum + (List.hd acc)
  | i -> loop (sum + (List.hd acc) * 2) (List.tl acc) (i - 2)

let () = Printf.printf "%d\n" @@ loop (List.hd a) (List.tl a) (n - 2)

Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6


let m = 1000000007
let ( *^ ) x y = (x * y) mod m

let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  let pos, neg =
    List.partition (( <= ) 0) @@
    List.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let l = List.length pos in
  let l' = List.length neg in
  let pos' = Array.make (l + 1) 1 in
  let pos'' = Array.make (l + 1) 0.  in
  let neg' = Array.make (l' + 1) 1 in
  let neg'' = Array.make (l' + 1) 0.  in
  let neg''' = Array.make (l' + 1) 1 in
  let neg'''' = Array.make (l' + 1) 0.  in
  List.iteri (fun i a ->
    pos'.(i + 1) <- pos'.(i) *^ a;
    pos''.(i + 1) <- pos''.(i) +. log (float_of_int a)) (List.sort (Fun.flip compare) pos);
  List.iteri (fun i a ->
    neg'.(i + 1) <- neg'.(i) *^ (a + m);
    neg''.(i + 1) <- neg''.(i) +. log (float_of_int (~- a))) (List.sort compare neg);
  List.iteri (fun i a ->
    neg'''.(i + 1) <- neg'''.(i) *^ (a + m);
    neg''''.(i + 1) <- neg''''.(i) +. log (float_of_int (~- a))) (List.sort (Fun.flip compare) neg);
  Printf.printf "%d\n" @@
  snd @@
  snd @@
  Array.fold_left max (0, (neg_infinity, 0)) @@
  Array.init (1 + k) @@ fun i ->
    if l < k - i || l' < i then (0, (neg_infinity, 0))
    else if i mod 2 = 1
    then (0, (~-. (pos''.(k - i)) -. neg''''.(i), pos'.(k - i) *^ neg'''.(i)))
    else (1, (pos''.(k - i) +. neg''.(i), pos'.(k - i) *^ neg'.(i)))

Score : 500 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

We will choose exactly K of these elements. Find the maximum possible product of the chosen elements.

Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Constraints

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

|A_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 \ldots A_N

Output

Print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Sample Input 1

4 2
1 2 -3 -4

Sample Output 1

12

The possible products of the two chosen elements are 2, -3, -4, -6, -8, and 12, so the maximum product is 12.

Sample Input 2

4 3
-1 -2 -3 -4

Sample Output 2

1000000001

The possible products of the three chosen elements are -24, -12, -8, and -6, so the maximum product is -6.

We print this value modulo (10^9+7), that is, 1000000001.

Sample Input 3

2 1
-1 1000000000

Sample Output 3

1000000000

The possible products of the one chosen element are -1 and 1000000000, so the maximum product is 1000000000.

Sample Input 4

10 10
1000000000 100000000 10000000 1000000 100000 10000 1000 100 10 1

Sample Output 4

999983200

Be sure to print the product modulo (10^9+7).


let split_string ?(pattern="") = Str.split @@ Str.regexp pattern
let n, k = Scanf.sscanf (read_line ()) "%d %d" @@ fun n k -> (n, k)
let a = read_line () |> split_string ~pattern:" " |> List.map int_of_string

let m_1e9 = int_of_float 1e9 + 7
let ( +^ ) x y = (x + y) mod m_1e9
let ( -^ ) x y = x - y + if x < y then m_1e9 else 0
let ( *^ ) x y = ((x mod m_1e9) * (y mod m_1e9)) mod m_1e9

let rec take res n acc = match (n, acc) with
  | (_, []) | (0, _) -> List.rev res
  | (i, x :: xs) -> take (x :: res) (n - 1) xs
let take = take []

let rec drop n acc = match (n, acc) with
  | (0, acc) -> acc
  | (_, []) -> []
  | (n, x :: xs) -> drop (n - 1) xs

let rec split a b = function
  | [] -> (List.sort compare a |> List.rev, List.sort compare b)
  | x :: rest when x > 0 -> split (x :: a) b rest
  | x :: rest -> split a (x :: b) rest
let plus, minus = split [] [] a

let rec two res = function
  | [] -> res
  | x :: [] -> (x, 1) :: res
  | x :: y :: rest -> two ((x, y) :: res) rest

let solve1 () =
  let ps = two [] plus in
  let ms = two [] minus in
  let acc = (ps @ ms) |> List.sort (fun (a, b) (c, d) -> abs (c * d) - abs (a * b)) in
  let sum = List.fold_left (fun sum (a, b) -> sum *^ a *^ b) 1 @@ take (k / 2) acc in
  let rec g sum = function
    | [] -> failwith ""
    | (a, _) :: _ when a > 0 -> sum *^ a
    | _ :: rest -> g sum rest
  in
  if k mod 2 = 1 then g sum (drop (k / 2) acc) else sum

let solve2 () =
  let rec take res n acc = match (n, acc) with
    | (_, []) | (0, _) -> List.rev res
    | (i, x :: xs) -> take (x :: res) (n - 1) xs in
  let take = take [] in
  let a = List.sort (fun a b -> abs a - abs b) a in
  List.fold_left ( *^ ) 1 @@ take k a

let f n = (n + m_1e9) mod m_1e9

let () =
  let p_len = List.length plus in
  Printf.printf "%d\n" @@ f @@
  if p_len >= k || (k - p_len) mod 2 = 0 then solve1 () else solve2 ()


let () = Scanf.scanf "%d\n" @@ fun n ->
  let es = Array.init (n - 1) @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun u v -> u, v in
  let vs =
    Array.fold_left ( + ) 0 @@
    Array.init n @@ fun i -> (i + 1) * (n - i) in
  Printf.printf "%d\n" @@
  Array.fold_left (fun acc (u, v) ->
    let [u; v] = List.sort compare [u; v] in
    acc - u * (n - v + 1)) vs es

Score : 600 points

Problem Statement

We have a tree with N vertices and N-1 edges, respectively numbered 1, 2,\cdots, N and 1, 2, \cdots, N-1. Edge i connects Vertex u_i and v_i.

For integers L, R (1 \leq L \leq R \leq N), let us define a function f(L, R) as follows:

Let S be the set of the vertices numbered L through R. f(L, R) represents the number of connected components in the subgraph formed only from the vertex set S and the edges whose endpoints both belong to S.

Compute \sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R).

Constraints

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

1 \leq u_i, v_i \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

Print \sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R).

Sample Input 1

3
1 3
2 3

Sample Output 1

7

We have six possible pairs (L, R) as follows:

For L = 1, R = 1, S = \{1\} and we have 1 connected component.

For L = 1, R = 2, S = \{1, 2\} and we have 2 connected components.

For L = 1, R = 3, S = \{1, 2, 3\} and we have 1 connected component, since S contains both endpoints of each of the edges 1, 2.

For L = 2, R = 2, S = \{2\} and we have 1 connected component.

For L = 2, R = 3, S = \{2, 3\} and we have 1 connected component, since S contains both endpoints of Edge 2.

For L = 3, R = 3, S = \{3\} and we have 1 connected component.

The sum of these is 7.

Sample Input 2

2
1 2

Sample Output 2

3

Sample Input 3

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

Sample Output 3

113


Scanf.scanf "%d" (fun d ->
    let c = Array.init 26 (fun _ -> Scanf.scanf " %d" (fun c -> c)) in
    let s = Array.init d (fun _ ->
        Array.init 26 (fun _ ->
            Scanf.scanf " %d" (fun s -> s)))
    in
    let t = Array.init d (fun _ -> Scanf.scanf " %d" (fun t -> t - 1)) in
    let last = Array.make 26 (-1) in
    let rec loop i sat =
        if i < d then (
            let sat = sat + s.(i).(t.(i)) in
            last.(t.(i)) <- i;
            let rec loop2 j sat =
                if j = 26 then sat else
                    loop2 (j + 1) (sat - c.(j) * (i - last.(j)))
            in
            let sat = loop2 0 sat in
            Printf.printf "%d\n" sat;
            loop (i + 1) sat
        )
    in
    loop 0 0
)

(Please read problem A first. The maximum score you can get by solving this problem B is 1, which will have almost no effect on your ranking.)

Beginner's Guide

Let's first write a program to calculate the score from a pair of input and output. You can know the total score by submitting your solution, or an official program to calculate a score is often provided for local evaluation as in this contest. Nevertheless, writing a score calculator by yourself is still useful to check your understanding of the problem specification. Moreover, the source code of the score calculator can often be reused for solving the problem or debugging your solution. So it is worthwhile to write a score calculator unless it is very complicated.

Problem Statement

You will be given a contest schedule for D days.
For each d=1,2,\ldots,D, calculate the satisfaction at the end of day d.

Input

Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A.

D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,2} \cdots s_{D,26}
t_1
t_2
\vdots
t_D

The constraints and generation methods for the input part are the same as those for Problem A.

For each d, t_d is an integer satisfying 1\leq t_d \leq 26, and your program is expected to work correctly for any value that meets the constraints.

Output

Let v_d be the satisfaction at the end of day d.
Print D integers v_d to Standard Output in the following format:

v_1
v_2
\vdots
v_D

Sample Input 1

5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192
1
17
13
14
13

Sample Output 1

18398
35037
51140
65837
79325

Note that this example is a small one for checking the problem specification. It does not satisfy the constraint D=365 and is never actually given as a test case.

Next Step

We can build a solution (schedule) for this problem in the order of day 1, day 2, and so on. And for every partial solution we have built, we can calculate the goodness (satisfaction) by using the above score calculator. So we can construct the following algorithm: for each d=1,2,\ldots,D, we select the contest type that maximizes the satisfaction at the end of day d. You may have already encountered this kind of "greedy algorithms" in algorithm contests such as ABC. Greedy algorithms can guarantee the optimality for several problems, but unfortunately, it doesn't ensure optimality for this problem. However, even if it does not ensure optimality, we can still obtain a reasonable solution in many cases. Let's go back to Problem A and implement the greedy algorithm by utilizing the score calculator you just implemented!

Greedy methods can be applied to a variety of problems, are easy to implement, and often run relatively fast compared to other methods. Greedy is often the most powerful method when we need to process huge inputs.
We can further improve the score by changing the greedy selection criteria (evaluation function), keeping multiple candidates instead of focusing on one best partial solution (beam search), or using the output of greedy algorithms as an initial solution of other methods.
For more information, please refer to the editorial that will be published after the contest.


open Scanf
open Printf

let a = scanf "%d" (fun a -> a)
let () = printf "%d\n" (a + a * a + a * a * a)

Score : 100 points

Problem Statement

Given an integer a as input, print the value a + a^2 + a^3.

Constraints

1 \leq a \leq 10

a is an integer.

Input

Input is given from Standard Input in the following format:

a

Output

Print the value a + a^2 + a^3 as an integer.

Sample Input 1

2

Sample Output 1

14

When a = 2, we have a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

Sample Input 2

10

Sample Output 2

1110


Scanf.scanf "%d" (fun a ->
    Printf.printf "%d\n" @@ a + a * a + a * a * a
)


open Scanf
open Printf

let () =
  let s,t = scanf "%s %s" (fun s t -> (s, t)) in
  let s_length = String.length s in
  let rec loop s t i =
    if i > s_length -1 then 0
    else if s.[i] <> t.[i] then 1 + loop s t (i + 1)
                           else loop s t (i + 1)
  in
    printf "%d\n" (loop s t 0)

Score : 200 points

Problem Statement

Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.

Operation: Choose one character of S and replace it with a different character.

Constraints

S and T have lengths between 1 and 2\times 10^5 (inclusive).

S and T consists of lowercase English letters.

S and T have equal lengths.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the answer.

Sample Input 1

cupofcoffee
cupofhottea

Sample Output 1

4

We can achieve the objective in four operations, such as the following:

First, replace the sixth character c with h.

Second, replace the eighth character f with t.

Third, replace the ninth character f with t.

Fourth, replace the eleventh character e with a.

Sample Input 2

abcde
bcdea

Sample Output 2

5

Sample Input 3

apple
apple

Sample Output 3

0

No operations may be needed to achieve the objective.


let () =
  let num = Array.make 100001 0 in
  let sum = ref 0 in
  let n = Scanf.scanf "%d\n" @@ fun n -> n in
  for i = 0 to n - 1 do
    Scanf.scanf "%d " @@ fun d ->
    num.(d) <- num.(d) + 1; sum := !sum + d
  done;
  Scanf.scanf "%d\n" @@ fun q ->
  for i = 0 to q - 1 do
    Scanf.scanf "%d %d\n" @@ fun b c ->
    sum := !sum + (c - b) * num.(b); num.(c) <- num.(c) + num.(b); num.(b) <- 0;
    Printf.printf "%d\n" !sum
  done;

Score : 100 points

Problem Statement

An uppercase or lowercase English letter \alpha will be given as input.
If \alpha is uppercase, print A; if it is lowercase, print a.

Constraints

\alpha is an uppercase (A - Z) or lowercase (a - z) English letter.

Input

Input is given from Standard Input in the following format:

α

Output

If \alpha is uppercase, print A; if it is lowercase, print a.

Sample Input 1

B

Sample Output 1

A

B is uppercase, so we should print A.

Sample Input 2

a

Sample Output 2

a

a is lowercase, so we should print a.


open Batteries
module EnumL = Enum.Labels
module ListL = List.Labels
module ArrayL = Array.Labels

let dbg0 x = Printf.eprintf "[debug]%s\n" @@ dump x
let dbg1 x = dbg0 x; x

let id = identity

let (++) n m = if n <= m then  List.range n `To m else []
let (++-) n m = if n >= m then List.range n `Downto m else []
let (++^) n m = if n < m then List.range n `To (pred m) else []

let scan fmt = Scanf.sscanf (read_line ()) fmt

let scan_lines n fmt f =
  if n = 0 then []
  else List.map (fun _ -> scan fmt f) (0 ++^ n)

let scan_list ?sep cnv =
  let line = read_line () in
  (match sep with
   | None -> List.map String.of_char @@ String.to_list line
   | Some sep -> String.split_on_char sep line)
  |> List.map cnv
let scan_array ?sep cnv = Array.of_list @@ scan_list ?sep cnv
let scan_matrix n m e ?sep conv =
  let arr = Array.make_matrix n m e in
  ListL.iter (0 ++^ n)
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list ?sep conv);
  arr

let atoi c = Char.code c - Char.code '0'
let itoa n = Char.chr (n + Char.code '0')

let between n x m = n <= x && x < m

(* ===== MAIN ===== *)

let s = scan "%s" id

let () =
  if s = String.uppercase s then
    Printf.printf "A\n"
  else
    Printf.printf "a\n"


let () =
  Scanf.scanf "%s\n" @@ fun a ->
  let b = (a = String.uppercase a) in
  Printf.printf "%s\n" (if b then "A" else "a")


open Batteries
open Printf

let ($) g f x = g (f x)

let swap = Tuple2.swap

let s2i = int_of_string
let i2s = string_of_int
let s2f = float_of_string
let f2s = string_of_float
let c2i = int_of_char
let i2c = char_of_int
let f2i = int_of_float
let i2f = float_of_int

let c2s = String.of_char
let s2cl = String.to_list
let cl2s = String.of_list

let puts s = print_endline s
let putyn b = puts (if b then "Yes" else "No")
let puti i = puts @@ i2s i

let rep lb bnd ub f = match bnd with
  | `To -> for i = lb to ub do f i done
  | `Til -> for i = lb to (ub - 1) do f i done

let rep2 lb1 bnd1 ub1 () lb2 bnd2 ub2 f =
  match (bnd1, bnd2) with
  | (`To, `To) -> for i = lb1 to ub1 do for j = lb2 to ub2 do f i j done done
  | (`To, `Til) -> for i = lb1 to ub1 do for j = lb2 to (ub2 - 1) do f i j done done
  | (`Til, `To) -> for i = lb1 to (ub1 - 1) do for j = lb2 to ub2 do f i j done done
  | (`Til, `Til) -> for i = lb1 to (ub1 - 1) do for j = lb2 to (ub2 - 1) do f i j done done

module JunkList = struct
  include List

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let nempty l = not @@ is_empty l

  let hdop l = if nempty l then Some (hd l) else None

  (* let taker = drop *)
  let takewh = take_while

  (* let dropr = take *)
  let dropwh = drop_while

  let split_by = span

  let chunk = ntake

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  let partition_to_map f l =
    foldr (fun x m -> Map.modify_opt (f x) (function
      | None -> Some [x]
      | Some [] -> Some [x]
      | Some vl -> Some (x::vl)) m) Map.empty l;;

  (* let scanl = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i

end

module L = JunkList

module JunkArray = struct
  include Array

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let is_empty r = len r = 0
  let nempty r = len r > 0

  let take n r = left r n
  let taker n r = right r n

  let takeb x r =
    let l = len r in
    let rec loop i =
      if i >= l then r
      else if r.(i) = x then take i r
      else loop (i + 1)
    in loop 0

  (* let takewh = take_while *)

  let drop n r = tail r n
  let dropr n r = take ((len r) - n) r
  (* let dropwh = drop_while *)

  let index_of x r =
    let l = len r in
    let rec loop i =
      if i >= l then None
      else if r.(i) = x then Some i
      else loop (i + 1)
    in loop 0

  (* let split_by = span *)

  (* let chunk = ntake *)

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  (* let partition_to_map f l = *)
  (*   foldr (fun x m -> Map.modify_opt (f x) (function *)
  (*     | None -> Some [x]  *)
  (*     | Some [] -> Some [x]  *)
  (*     | Some vl -> Some (x::vl)) m) Map.empty l;; *)

  (* let scanl = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let concat2 = append

  let flatmap (f : 'a -> 'b array) a =
    map f a |> enum |> L.of_enum |> concat

  let zipf = map2
  (* let zipfi = map2i *)

end

module A = JunkArray

module JunkString = struct
  include String

  let len = length

  let replace_chars = map
  let map = replace

  let maptol f s = L.map f (s2cl s)
  let maptoli f s = L.map f (s2cl s)

  let zipf f a b = L.zipf f (s2cl a) (s2cl b)
  let zipfi f a b = L.zipfi f (s2cl a) (s2cl b)

  let mkstr f sep ls =
    L.foldl (fun acc x -> acc ^ sep ^ (f x)) (f @@ L.hd ls) (List.tl ls)

end

module S = JunkString

let spsp s = S.split_on_char ' ' s

module JunkSortedSet = struct
  include Set

  module Make (Ord : Set.OrderedType) = struct
    include Set.Make(Ord)

    let nmem x st = not @@ mem x st

    let foldl f s z = fold (fun x a -> f a x) z s

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let foldl f s z = fold (fun x a -> f a x) z s

  let size = cardinal
end

module Ss = JunkSortedSet

module JunkSortedMap  = struct
  include Map

  module Make (Ord : Map.OrderedType) = struct
    include Map.Make(Ord)

    let nmem x st = not @@ mem x st

    let get = find
    let get_or x d m = find_default d x m

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let get = find
  let get_or x d m = find_default d x m

  let size = cardinal
end

module Ms = JunkSortedMap

let set_power ls =
  let rec loop ls pls =
    match ls with
    | [] -> pls
    | hd::tl -> loop tl (L.flatmap (fun p -> [p; hd::p]) pls)
  in loop ls [[]]

exception ArithmeticException of string

module JunkIntArithmetic = struct

  let rec power x e =
    if e = 0 then x
    else
      let rec loop r x2 e' =
        if e' = 0 then r
        else if e' land 1 = 0 then loop r (x2 * x2) (e' lsr 1)
        else loop (r * x2) (x2 * x2) (e' lsr 1)
      in loop 1 x e

  let rec powers_le_1000 x =
    if x > 32 then [x]
    else
      L.init 9 (fun e -> power x (e + 1))
      |> L.filter (fun y -> y < 1000)

  let primes_le_1000 = [2;3;5;7;11;13;17;19;23;29;31;37;41;
    43;47;53;59;61;67;71;73;79;83;89;97;101;
    103;107;109;113;127;131;137;139;149;151;157;163;167;
    173;179;181;191;193;197;199;211;223;227;229;233;239;
    241;251;257;263;269;271;277;281;283;293;307;311;313;
    317;331;337;347;349;353;359;367;373;379;383;389;397;
    401;409;419;421;431;433;439;443;449;457;461;463;467;
    479;487;491;499;503;509;521;523;541;547;557;563;569;
    571;577;587;593;599;601;607;613;617;619;631;641;643;
    647;653;659;661;673;677;683;691;701;709;719;727;733;
    739;743;751;757;761;769;773;787;797;809;811;821;823;
    827;829;839;853;857;859;863;877;881;883;887;907;911;
    919;929;937;941;947;953;967;971;977;983;991;997]

    let primes_and_powers_le_1000 =
      [2;3;4;5;7;8;9;11;13;16;17;19;23;25;27;29;31;32;37;41;
      43;47;49;53;59;61;64;67;71;73;79;81;83;89;97;
      101;103;107;109;113;121;125;127;128;131;137;139;149;151;
      157;163;167;169;173;179;181;191;193;197;199;211;223;227;
      229;233;239;241;243;251;256;257;263;269;271;277;281;283;
      289;293;307;311;313;317;331;337;343;347;349;353;359;361;
      367;373;379;383;389;397;401;409;419;421;431;433;439;443;
      449;457;461;463;467;479;487;491;499;503;509;512;521;523;
      529;541;547;557;563;569;571;577;587;593;599;601;607;613;
      617;619;625;631;641;643;647;653;659;661;673;677;683;691;
      701;709;719;727;729;733;739;743;751;757;761;769;773;787;
      797;809;811;821;823;827;829;839;841;853;857;859;863;877;
      881;883;887;907;911;919;929;937;941;947;953;961;967;971;
      977;983;991;997]

  let factorize_with ps n =
    let rec loop acc ps e n' =
      if n' <= 1 then ([], n')
      else
        match ps with
        | [] -> (acc, n')
        | p::t ->
          let r = n' mod p in
          if r = 0 then (
            if n' = p then ((p, e + 1) :: acc, 1)
            else loop acc ps (e + 1) (n' / p)
          ) else
            loop (if e = 0 then acc else (p, e) :: acc) t 0 n'
    in
    let (fs, r) = loop [] ps 0 n in
    (L.rev fs, r)

  let factorize_le_million n =
    factorize_with primes_le_1000 n

  let rec to_bits_le n =
    if n = 0 then []
    else (n mod 2) :: to_bits_le (n lsr 1)

  let rec gcd x y =
    match x mod y with
    | 0 -> y
    | z -> gcd y z

  let ext_euclid a b =
    let rec next (r0, s0, t0) (r1, s1, t1) =
      match r1 with
      | 0 -> (r0, s0, t0)
      | r2 ->
        let q = r0 / r1 in
        next (r1, s1, t1) (r0 - q * r1, s0 - q * s1, t0 - q * t1)
    in
    if a < b then
      let (g, y, x) = next (b, 1, 0) (a, 0, 1) in (g, x, y)
    else
      next (a, 1, 0) (b, 0, 1)

  let modinv x m =
    let (g, y, z) = ext_euclid x m in
    match g with
    | 1 -> y mod m
    | _ -> raise @@ ArithmeticException "Not relatively prime"

end

module N = JunkIntArithmetic

module JunkMatrix = struct

  type 'a t = { w : int; h : int; e : 'a array array }

  let make w h e0 =
    { w = w; h = h; e = A.make_matrix w h e0 }

  let from_columns w h e0 elems =
    let matr = make w h e0 in
    elems |> L.iteri (fun j col ->
      col |> L.iteri (fun i x -> matr.e.(i).(j) <- x));
    matr

  let blit (mats, rs, cs, w, h) (matd, rd, cd) =
    rep2 0 `Til w () 0 `Til h (fun i j ->
        matd.e.(rd + i).(cd + j) <- mats.e.(rs + i).(cs + j))

  let expand (w1, h1) (w2, h2) e0 mat =
    let matr = make w2 h2 e0 in
    blit (mat, 0, 0, w1, h1) (matr, 0, 0);
    matr

end

module M = JunkMatrix

module type FieldOps = sig
  type elt
  val zero : elt
  val one : elt
  val neg : elt -> elt
  val rcp : elt -> elt
  val add : elt -> elt -> elt
  val sub : elt -> elt -> elt
  val mul : elt -> elt -> elt
  val div : elt -> elt -> elt
end

module JunkLinearAlgebra (Fop : FieldOps) = struct

  type t = Fop.elt M.t

  let zero w h = M.make w h Fop.zero

  let prod (mat1 : t) (mat2 : t) =
    let matr = zero mat1.w mat2.h in
    rep2 0 `Til mat1.w () 0 `Til mat2.h (fun i j ->
        matr.e.(i).(j) <-
          mat1.e.(i) |> A.foldli (fun
            acc k x -> Fop.add acc (Fop.mul x mat2.e.(k).(i)))
            Fop.zero);
    matr

  exception NotZero of int
  let is_zero (mat : t) =
    try (
      rep 0 `Til mat.w (fun i ->
        if mat.e.(i) |> A.for_all (fun x -> x <> Fop.zero)
          then raise (NotZero 1)
      );
      true
    ) with _ -> false

  let col_addmul c1 (c2, a) (mat : t) =
    rep 0 `Til mat.h (fun i ->
      mat.e.(i).(c1) <- Fop.add mat.e.(i).(c1) (Fop.mul a mat.e.(i).(c2)))

  let col_inner_prod c1 c2 (mat : t) =
    let sum = ref Fop.zero in
    rep 0 `Til mat.h (fun i ->
      sum := Fop.add !sum @@ Fop.mul mat.e.(i).(c1) mat.e.(i).(c2));
    !sum

  (* let orth_extend k0 k1 mat = *)
  (*   let matx = extend (k0, h) ((k0 + k1), h) 0 mat in *)
  (*   rep k0 `Til (k0 + k1) (fun t -> *)
  (*     rep 0 `Til t (fun s ->  *)
  (*       let ip = col_inner_prod s t h matx in *)
  (*       col_addmul t (s, ip) h matx)); *)
  (*   submat (k0, 0) (k0 + k1 - 1, h - 1) matx *)

end

module type OrderedData = sig
  type t
  val compare : t -> t -> int
  val default : t
end

module JunkGraph = struct

  type 'a v_t = int * 'a
  type 'a t = { vs : 'a v_t array; nb : int Ss.t array }

  let empty nv vd =
    let vs0 = Array.make nv (0, vd) in
    for i = 0 to (nv - 1) do vs0.(i) <- (i, vd) done;
    {
      vs = vs0;
      nb = A.make nv Ss.empty
    }

  let add_edge (e : int * int) vd g =
    let (v1, v2) = e in
    g.vs.(v1 - 1) <- (v1, vd);
    g.vs.(v2 - 1) <- (v2, vd);
    g.nb.(v1 - 1) <- g.nb.(v1 - 1) |> Ss.add v2;
    g

  let add_uedge e vd g =
    add_edge e vd (add_edge (swap e) vd g)

  let from_edges nv vd es =
    es |> L.foldl (fun g e -> add_edge e vd g) (empty nv vd)

  let from_uedges nv vd es =
    es |> L.foldl (fun g e -> add_uedge e vd g) (empty nv vd)

end

module G = JunkGraph

module JunkGraphAlgorithms (Vdt : OrderedData) = struct

  type t = Vdt.t G.t

  module V = struct
    type t = int * Vdt.t
    let compare (vi1, vd1) (vi2, vd2) =
      let c1 = Vdt.compare vd1 vd2 in
      if c1 = 0 then compare vi1 vi2
      else c1

    let default i = (i, Vdt.default)
    let index (v : t) = fst v
  end

  module Vset = Ss.Make(V)

  let print_vertices label vs =
    printf "%s: " label;
    vs |> Vset.iter (fun (vi, _) -> printf "%d " vi);
    puts ""

  let nbiter (upd : V.t -> V.t -> t -> t * bool)
    (ui : int) (fr : Vset.t) (cls : int Ss.t) (g : t) =
    let nb = g.nb.(ui - 1) in
    let result = nb |> Ss.foldl (fun (ga, nxfr, nxcls) vi ->
    (* puts "nxcls: "; *)
      (* Ss.iter (fun x -> printf "%d " x) nxcls; puts ""; *)
      if ui = vi || Ss.mem vi nxcls then
        (ga, nxfr, nxcls)
      else
        let ue = g.vs.(ui - 1) and ve = g.vs.(vi - 1) in
        let (gu, close) = upd ue ve ga in
        (gu,
          nxfr |> Vset.add ve,
          if close then nxcls |> Ss.add vi else nxcls)
    ) (g, fr, cls)
    in (* puts "";  *)result

  let traverse (upd : V.t -> V.t -> t -> t * bool)
    (fr0 : Vset.t) (cls0 : int Ss.t) (g : t) =

    let rec progress fr cls g' =
      let (ve, fr') = Vset.pop_min fr in
      let (vi, _) = ve in
      let (gu, nxfr, nxcls) = nbiter upd vi fr' cls g' in
      if Vset.is_empty nxfr then (gu, nxcls)
      else progress nxfr nxcls gu
    in
    progress fr0 cls0 g

  let frontier (upd : V.t -> V.t -> t -> t * bool)
    (fr0 : Vset.t) (cls0 : int Ss.t) (g : t) =

    let rec progress fr cls g' =
      let (gu, nxfr, nxcls) =
        fr |> Vset.foldl (fun (ga, nxfra, nxclsa) ve ->
          let (vi, _) = ve in
          nbiter upd vi nxfra nxclsa ga
        ) (g', Vset.empty, cls)
      in
      if Vset.is_empty nxfr then (gu, nxcls)
      else progress nxfr nxcls gu
    in
    progress fr0 cls0 g

  let bfs (upd : V.t -> V.t -> t -> t) =
    frontier (fun fr cls g' -> (upd fr cls g', true))

end

let rds () = read_line ()

let rdi () = s2i @@ rds ()

let rdhs () = spsp @@ rds ()
let rdhi () = rdhs () |> L.map s2i

let rdhf () = rdhs () |> L.map s2f

let rdf2 () = match rdhf () with
| a::b::_ -> (a, b)
| _ -> (0., 0.)

let rdf3 () = match rdhf () with
| a::b::c::_ -> (a, b, c)
| _ -> (0., 0., 0.)

let rdf4 () = match rdhf () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0., 0., 0., 0.)

let rds2 () = match rdhs () with
  | a::b::_ -> (a, b)
  | _ -> ("", "")

let rdi2 () = match rdhi () with
  | a::b::_ -> (a, b)
  | _ -> (0, 0)

let rdi3 () = match rdhi () with
| a::b::c::_ -> (a, b, c)
| _ -> (0, 0, 0)

let rdi4 () = match rdhi () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0, 0, 0, 0)

let rdi5 () = match rdhi () with
| a::b::c::d::e::_ -> (a, b, c, d, e)
| _ -> (0, 0, 0, 0, 0)

let rdv n rf =
  let rec loop n =
    if n <= 0 then []
    else (
      let s = rf () in
      s::(loop (n - 1))
    )
  in loop n

let rdvi n = rdv n rdi
let rdvi2 n = rdv n rdi2
let rdvi3 n = rdv n rdi3
let rdvi4 n = rdv n rdi4

module Galg = JunkGraphAlgorithms (
  struct
    type t = int
    let compare = compare
    let default = 0
  end)

let print_list aa =
  printf "[ "; aa |> L.iter (fun a -> printf "%d " a); puts "]"

let print_array aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%d " a); puts "]"

let _ =
  let a = L.hd @@ s2cl @@ rds () in
  puts @@ if Char.is_lowercase a then "a" else "A";

();;


(*
ocamlfind ocamlopt -package batteries -linkpkg main.ml -o a.out
*)
open Batteries

let ch = Scanf.sscanf (read_line ()) "%c" ( fun ch -> ch)

let () =
        (
                if Char.is_lowercase ch then
                        'a'
                else
                        'A'
        ) |> Printf.printf "%c\n"


let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  let array = Array.init n @@ fun _ -> Scanf.scanf " %d" Fun.id in
  Array.sort compare array;
  let k_array = Array.sub array 0 k in
  Printf.printf "%d\n" @@ Array.fold_left ( + ) 0 k_array

Score : 200 points

Problem Statement

A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)

Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

Constraints

1 \leq K \leq N \leq 1000

1 \leq p_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 p_2 \ldots p_N

Output

Print an integer representing the minimum possible total price of fruits.

Sample Input 1

5 3
50 100 80 120 80

Sample Output 1

210

This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.

The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.

Sample Input 2

1 1
1000

Sample Output 2

1000


let () =
  let soc = fun n -> Char.escaped (char_of_int (97+n)) in
  let rec check n m l = if n <= m then (n-1, l-1) else check (n-m) (m*26) (l+1) in
  let rec make (n, k) =
    if k = 0 && n = 0 then soc n
    else if k = 0 then soc n
    else
      let y = int_of_float (26. ** (float_of_int k)) in
      let x, m = n / y, n mod y in soc x ^ make (m, (k-1)) in
  Scanf.scanf "%d\n" @@ fun n -> Printf.printf "%s\n" (make (check n 26 1))

Score : 300 points

Problem Statement

1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:

the dogs numbered 1,2,\cdots,26 were respectively given the names a, b, ..., z;

the dogs numbered 27,28,29,\cdots,701,702 were respectively given the names aa, ab, ac, ..., zy, zz;

the dogs numbered 703,704,705,\cdots,18277,18278 were respectively given the names aaa, aab, aac, ..., zzy, zzz;

the dogs numbered 18279,18280,18281,\cdots,475253,475254 were respectively given the names aaaa, aaab, aaac, ..., zzzy, zzzz;

the dogs numbered 475255,475256,\cdots were respectively given the names aaaaa, aaaab, ...;

and so on.

To sum it up, the dogs numbered 1, 2, \cdots were respectively given the following names:

a, b, ..., z, aa, ab, ..., az, ba, bb, ..., bz, ..., za, zb, ..., zz, aaa, aab, ..., aaz, aba, abb, ..., abz, ..., zzz, aaaa, ...

Now, Roger asks you:

"What is the name for the dog numbered N?"

Constraints

N is an integer.

1 \leq N \leq 1000000000000001

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer to Roger's question as a string consisting of lowercase English letters.

Sample Input 1

2

Sample Output 1

b

Sample Input 2

27

Sample Output 2

aa

Sample Input 3

123456789

Sample Output 3

jjddja


open Batteries
module EnumL = Enum.Labels
module ListL = List.Labels
module ArrayL = Array.Labels

let dbg0 x = Printf.eprintf "[debug]%s\n" @@ dump x
let dbg1 x = dbg0 x; x

let id = identity

let (++) n m = if n <= m then  List.range n `To m else []
let (++-) n m = if n >= m then List.range n `Downto m else []
let (++^) n m = if n < m then List.range n `To (pred m) else []

module ModOp = struct
  let prime = 1_000_000_007
  let (-) a b = (a + prime - b) mod prime
  let (+) a b = (a + b) mod prime
  let ( * ) a b = (a * b) mod prime

  let rec pow x n =
    if n = 0 then 1
    else if n mod 2 = 0 then pow (x*x) (n/2)
    else x * pow (x*x) (n/2)
end

let scan fmt = Scanf.sscanf (read_line ()) fmt

let scan_lines n fmt f =
  if n = 0 then []
  else List.map (fun _ -> scan fmt f) (1 ++ n)

let scan_list ?sep cnv =
  let line = read_line () in
  (match sep with
   | None -> List.map String.of_char @@ String.to_list line
   | Some sep -> String.split_on_char sep line)
  |> List.map cnv

let scan_array ?sep cnv = Array.of_list @@ scan_list ?sep cnv

let scan_matrix n m e ?sep conv =
  let arr = Array.make_matrix n m e in
  ListL.iter (0 ++^ n)
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list ?sep conv);
  arr

let atoi c = Char.code c - Char.code '0'
let itoa n = Char.chr (n + Char.code '0')

let rec powerset = function
  | [] -> [[]]
  | hd::tl ->
    let pws =  powerset tl in
    pws @ ListL.map pws ~f:(fun pw -> hd::pw)

let permutations l =
  let rec interleave x = function
    | [] -> [[x]]
    | (hd::tl) as l ->
      (x::l) :: (interleave x tl |> ListL.map ~f:(fun l -> hd::l)) in
  let rec aux = function
    | [] -> [[]]
    | a::rest ->
      aux rest |> ListL.map ~f:(interleave a) |> List.concat in
  aux l

let intersection l =
  EnumL.filter ~f:(fun x -> EnumL.exists ~f:((=) x) @@ Enum.clone l)

let zip l m =
  let n = min (List.length l) (List.length m) in
  List.combine (List.take n l) (List.take n m)

let lower_bound n f =
  let rec aux l u =
    if u - l > 1 then
      let m = (l + u) / 2 in
      if f m then aux l m
      else aux m u
    else u in aux (-1) n

let between n x m = n <= x && x < m

let n = scan "%Ld" id

let () =
  let s = "zabcdefghijklmnopqrstuvwxy" in
  let rec aux n acc =
    if Int64.equal n 0L then String.of_list acc
    else
      let i = Int64.to_int @@ Int64.modulo n 26L in
      if i = 0 then
        aux (Int64.pred (Int64.div n 26L))
          (String.get s i::acc)
      else
        aux (Int64.div n 26L)
          (String.get s i::acc)
  in
  Printf.printf "%s\n" @@ aux n []