using DataStructures
const double = Float64
const int = Int64

parseint(x) = parse(int, x)
readint() = map(parseint, split(readline()))

function main()
  N = readint()[1]

  if N < 600
    println(8)
  elseif N < 800
    println(7)
    elseif N < 1000
      println(6)
    elseif N < 1200
      println(5)
    elseif N < 1400
      println(4)
    elseif N < 1600
      println(3)
    elseif N < 1800
      println(2)
    elseif N < 2000
      println(1)
    end

end

main()

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.


N,K=parse.(Int,split(readline()))
A=parse.(Int,split(readline()))
function solve(n,k,A)
    for i=1:(n-k)
        if A[i]<A[i+k]
            println("Yes")
        else
            println("No")
        end
    end
end
solve(N,K,A)

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

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

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.


function main()
    N = pread(Int)
    a = readvec(Int, N)
    mv = zeros(Int, N)
    mv = search!(1,N,a,mv)
    kb = 0
    mon = 1000
    for i in 1:N
        mv[i] == 0 && continue
        if mv[i] == 1
            kb += mon ÷ a[i]
            mon -= kb * a[i]
        else
            mon += kb * a[i]
            kb = 0
        end
    end
    println(mon)
end

function search!(si,ei,a,mv)
    si >= ei && return mv
    sv = a[si]
    ev = a[ei]
    nsi = si
    nei = ei
    esa = 0
    emin = ev
    for i in 1:ei-si-1
        if a[si+i] < sv
            nsi = si + i
            sv = a[si+i]
        end
    end

    for i in 1:ei-si-1
        if nsi >= nei
            break
        end
        if a[ei-i] <= emin
            emin = a[ei-i]
        end
        if esa <= a[ei-i] - emin
            nei = ei - i
            ev = a[ei-i]
            esa = a[ei-i] - emin
        end
    end
    if sv > ev
        return mv
    end
    mv[nsi] = 1
    mv[nei] = -1
    search!(si,nsi-1,a,mv)
    search!(nsi+1,nei-1,a,mv)
    search!(nei+1,ei,a,mv)
    return mv
end

import Base.parse
import Base.StringVector

parse(::Type{String},  str::AbstractString) = str
isdelim(x::UInt8, xs::Set{UInt8}) = x in xs
const delimset = Set([0x0a, 0x20])

function myreaduntil(s::IO, delims::Set{UInt8})::Vector{UInt8}
    out = StringVector(0)
    c::UInt8 = 0x00
    while !eof(s)
        c = read(s, UInt8)
        !isdelim(c, delims) && break
    end
    push!(out, c)
    eof(s) && return out
    while !eof(s)
        c = read(s, UInt8)
        isdelim(c, delims) && break
        push!(out, c)
    end
    return out
end

function readword(io::IO = stdin, delims = delimset)::String
    word = myreaduntil(io, delims)
    i = length(word)
    if i == 0 || word[i] != 0x0a
        return String(word)
    elseif i < 2 || word[i-1] != 0x0d
        return String(resize!(word,i-1))
    else
        return String(resize!(word,i-2))
    end
end

pread(ty) = parse(ty, readword())

reads(tys...)::Tuple{tys...} = Tuple{tys...}(pread(ty) for ty in tys)

function readvec(tys::Tuple , len::Signed)::Tuple{map(x -> Vector{x},tys)...}
    rv = Tuple{map(x -> Vector{x},tys)...}(Vector{ty}(undef,len) for ty in tys)
    for i in 1:len
        for j in 1:length(tys)
            @inbounds rv[j][i] = pread(tys[j])
        end
    end
    rv
end

readvec(ty::Type, len::Signed)::Vector{ty} = @inbounds ty[pread(ty) for i in 1:len]

function readmat(ty::Type, s...)::Matrix{ty}
    v = Matrix{ty}(undef, s...)
    @inbounds for i in 1:s[1]
        v[i,:] = readvec(ty, s[2])
    end
    v
end

main()

Score: 400 points

Problem Statement

To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives.

He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the next N days will be as follows:

A_1 yen on the 1-st day, A_2 yen on the 2-nd day, ..., A_N yen on the N-th day.

In the i-th day, M-kun can make the following trade any number of times (possibly zero), within the amount of money and stocks that he has at the time.

Buy stock: Pay A_i yen and receive one stock.

Sell stock: Sell one stock for A_i yen.

What is the maximum possible amount of money that M-kun can have in the end by trading optimally?

Constraints

2 \leq N \leq 80

100 \leq A_i \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the maximum possible amount of money that M-kun can have in the end, as an integer.

Sample Input 1

7
100 130 130 130 115 115 150

Sample Output 1

1685

In this sample input, M-kun has seven days of trading. One way to have 1685 yen in the end is as follows:

Initially, he has 1000 yen and no stocks.

Day 1: Buy 10 stocks for 1000 yen. Now he has 0 yen.

Day 2: Sell 7 stocks for 910 yen. Now he has 910 yen.

Day 3: Sell 3 stocks for 390 yen. Now he has 1300 yen.

Day 4: Do nothing.

Day 5: Buy 1 stock for 115 yen. Now he has 1185 yen.

Day 6: Buy 10 stocks for 1150 yen. Now he has 35 yen.

Day 7: Sell 11 stocks for 1650 yen. Now he has 1685 yen.

There is no way to have 1686 yen or more in the end, so the answer is 1685.

Sample Input 2

6
200 180 160 140 120 100

Sample Output 2

1000

In this sample input, it is optimal to do nothing throughout the six days, after which we will have 1000 yen.

Sample Input 3

2
157 193

Sample Output 3

1216

In this sample input, it is optimal to buy 6 stocks in Day 1 and sell them in Day 2, after which we will have 1216 yen.


# %% library
# ----------

# %% library docs
# ---------------

"""
    @collect [cond] ex

Constructs [`Array`](@ref) from lastly evaluated values from a `for` loop block that appears
  first within given `ex` expression.
If the optional `cond` expression is given, iterations  where the `cond` is `false` are
  effectively filtered out.

```julia-repl
julia> @collect isodd(i) for i = 1:3
           println("i = ", i); i
       end
i = 1
i = 3
2-element Array{Int64,1}:
 1
 3
```

See also: [`@generator`](@ref)
"""
macro collect end

"""
    @generator [cond] ex

Constructs [`Base.Generator`](@ref) from lastly evaluated values from a `for` loop block
  that appears first within given `ex` expression.
If the optional `cond` expression is given, iterations where the `cond` is `false` are
  effectively filtered out.

```julia-repl
julia> @generator isodd(i) for i = 1:3
           println("i = ", i); i
       end |> sum
i = 1
i = 3
4
```

See also: [`@collect`](@ref)
"""
macro generator end

"""
    bruteforcesearch(n::Integer, b::Integer = 2)
    bruteforcesearch(f::Function, n::Integer, b::Integer = 2)

$(""#=TODO: add some equation here for the future reference=#)

!!! note
    By default (i.e. when `b == 2`), this function is equivalent to bit-brute-force search.

```julia-repl
julia> for gen in bruteforcesearch(3)
           @show collect(gen)
       end
collect(gen) = [2, 1, 1]
collect(gen) = [1, 2, 1]
collect(gen) = [2, 2, 1]
collect(gen) = [1, 1, 2]
collect(gen) = [2, 1, 2]
collect(gen) = [1, 2, 2]
collect(gen) = [2, 2, 2]
collect(gen) = [1, 1, 1]

julia> bruteforcesearch(2, 3) do gen
           @show collect(gen)
       end |> collect;
collect(gen) = [2, 1]
collect(gen) = [3, 1]
collect(gen) = [1, 2]
collect(gen) = [2, 2]
collect(gen) = [3, 2]
collect(gen) = [1, 3]
collect(gen) = [2, 3]
collect(gen) = [3, 3]
collect(gen) = [1, 1]
```
"""
function bruteforcesearch end

# %% library body
# ---------------

function decompose_forblk(forblk)
    @assert Meta.isexpr(forblk, :for) "for block expression should be given"
    itrspec, body = forblk.args
    @assert Meta.isexpr(itrspec, :(=)) "invalid for loop specification"
    v, itr = itrspec.args
    return body, v, itr
end

function recompose_to_comprehension(forblk, cond = nothing; gen = false)
    body, v, itr = decompose_forblk(forblk)
    return isnothing(cond) ?
        esc(gen ? :(($body for $v in $itr)) : :([$body for $v in $itr])) :
        esc(gen ? :(($body for $v in $itr if $cond)) : :([$body for $v in $itr if $cond]))
end

function walk_and_transform(x, cond = nothing; gen = false)
    Meta.isexpr(x, :for) && return recompose_to_comprehension(x, cond; gen = gen), true
    x isa Expr || return x, false
    for (i, ex) in enumerate(x.args)
        ex, transformed = walk_and_transform(ex, cond; gen = gen)
        x.args[i] = ex
        transformed && return x, true # already transformed
    end
    return x, false
end

macro collect(ex) first(walk_and_transform(ex)) end
macro collect(cond, ex) first(walk_and_transform(ex, cond)) end

macro generator(ex) first(walk_and_transform(ex; gen = true)) end
macro generator(cond, ex) first(walk_and_transform(ex, cond; gen = true)) end

@inbounds begin

function bruteforcesearch(n::Integer, b::Integer = 2)
    baselen = length(string(b, base = 10))
    return @generator for i = 1:b^n
        s = reverse(string(i, pad = n, base = b))[1:n] # cut off the overflowed char when `i == base^n`
        @generator for ns in partition(s, baselen)
            parse(Int, ns) + 1 # for 1-based indexing
        end
    end
end

function bruteforcesearch(f::Function, n::Integer, b::Integer = 2)
    baselen = length(string(b, base = 10))
    return @generator for i = 1:b^n
        s = reverse(string(i, pad = n, base = b))[1:n] # cut off the overflowed char when `i == base^n`
        gen = @generator for ns in partition(s, baselen)
            parse(Int, ns) + 1 # for 1-based indexing
        end
        f(gen)
    end
end

function partition(a, n)
    return if n == 1
        a
    else
        @collect for i in 1:(length(a)÷n)
            s = 1+n*(i-1)
            e = n*i
            a[s:e]
        end
    end
end

end # @inbounds

# %% constants
# ------------

# %% body
# -------

function main(io = stdin)
    readto(target = '\n') = readuntil(io, target)
    readnum(T::Type{<:Number} = Int; dlm = isspace, kwargs...) =
        parse.(T, split(readto(), dlm; kwargs...))

    # handle IO and stuff
    N, = readnum()
    XYPs = [readnum() for _ in 1:N]
    println.(solve(N, XYPs))
end

@inbounds function solve(N, XYPs)
    # TODO: precomputation
    Xcaches = [Dict{UInt,Int}() for _ in 1:N]
    Ycaches = [Dict{UInt,Int}() for _ in 1:N]

    for roads in bruteforcesearch(N, 2)
        Xs = Set(X for (road, (X, _)) in zip(roads, XYPs) if road == 1)
        Ys = Set(Y for (road, (_, Y, _)) in zip(roads, XYPs) if road == 1)
        push!(Xs, 0); push!(Ys, 0)
        cache_distances!(XYPs, Xs, Ys, Xcaches, Ycaches)
    end

    ret = [typemax(Int) for n in 0:N]

    # calculate shortest distances for all the candidates
    for roads in bruteforcesearch(N, 3)
        Xs = Set(0)
        Ys = Set(0)
        cnt = @generator for (road, (X, Y, _)) in zip(roads, XYPs)
            if road == 1
                push!(Xs, X)
                1
            elseif road == 2
                push!(Ys, Y)
                1
            else # no road here, no count
                0
            end
        end |> sum
        ret[cnt + 1] = min(ret[cnt + 1], sumup_distances(XYPs, Xs, Ys, Xcaches, Ycaches))
    end

    return ret
end

function cache_distances!(XYPs, Xs, Ys, Xcaches, Ycaches)
    for ((X, Y, _), Xcache, Ycache) in zip(XYPs, Xcaches, Ycaches)
        cache_distance!(Xcache, X, Xs)
        cache_distance!(Ycache, Y, Ys)
    end
end

function cache_distance!(cache, p, ps)
    k = hash(ps)
    haskey(cache, k) && return
    cache[k] = shortest_distance(p, ps)
end

shortest_distance(p, ps) = minimum(abs(p - x) for x in ps)

@inbounds function sumup_distances(XYPs, Xs, Ys, Xcaches, Ycaches)
    xk = hash(Xs)
    yk = hash(Ys)
    @generator for ((_, _, P), Xcache, Ycache) in zip(XYPs, Xcaches, Ycaches)
        min(Xcache[xk], Ycache[yk]) * P
    end |> sum
end

@static if @isdefined(Juno)
    using BenchmarkTools

    main(open(replace(@__FILE__, r"(.+)\.jl" => s"\1.in")))
    @btime main(open(replace(@__FILE__, r"(.+)\.jl" => s"\1.in")))
else
    main()
end

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.


# %% library
# ----------

# %% library docs
# ---------------

"""
    @collect [cond] ex

Constructs [`Array`](@ref) from lastly evaluated values from a `for` loop block that appears
  first within given `ex` expression.
If the optional `cond` expression is given, iterations  where the `cond` is `false` are
  effectively filtered out.

```julia-repl
julia> @collect isodd(i) for i = 1:3
           println("i = ", i); i
       end
i = 1
i = 3
2-element Array{Int64,1}:
 1
 3
```

See also: [`@generator`](@ref)
"""
macro collect end

"""
    @generator [cond] ex

Constructs [`Base.Generator`](@ref) from lastly evaluated values from a `for` loop block
  that appears first within given `ex` expression.
If the optional `cond` expression is given, iterations where the `cond` is `false` are
  effectively filtered out.

```julia-repl
julia> @generator isodd(i) for i = 1:3
           println("i = ", i); i
       end |> sum
i = 1
i = 3
4
```

See also: [`@collect`](@ref)
"""
macro generator end

"""
    bruteforcesearch(f::Function, n::Integer, b::Integer = 2)

Applies `f` for all the ...
$(""#=TODO: add some equation here for the future reference=#)

!!! note
    By default (i.e. when `b == 2`), this function is equivalent to bit-brute-force search.

```julia-repl
julia> bruteforcesearch(3) do comb
           @show collect(comb)
       end;
collect(mask) = [2, 1, 1]
collect(mask) = [1, 2, 1]
collect(mask) = [2, 2, 1]
collect(mask) = [1, 1, 2]
collect(mask) = [2, 1, 2]
collect(mask) = [1, 2, 2]
collect(mask) = [2, 2, 2]
collect(mask) = [1, 1, 1]

julia> bruteforcesearch(2, 3) do comb
           @show collect(comb)
       end;
collect(mask) = [2, 1]
collect(mask) = [3, 1]
collect(mask) = [1, 2]
collect(mask) = [2, 2]
collect(mask) = [3, 2]
collect(mask) = [1, 3]
collect(mask) = [2, 3]
collect(mask) = [3, 3]
collect(mask) = [1, 1]
```
"""
function bruteforcesearch end

# %% library body
# ---------------

function decompose_forblk(forblk)
    @assert Meta.isexpr(forblk, :for) "for block expression should be given"
    itrspec, body = forblk.args
    @assert Meta.isexpr(itrspec, :(=)) "invalid for loop specification"
    v, itr = itrspec.args
    return body, v, itr
end

function recompose_to_comprehension(forblk, cond = nothing; gen = false)
    body, v, itr = decompose_forblk(forblk)
    return isnothing(cond) ?
        esc(gen ? :(($body for $v in $itr)) : :([$body for $v in $itr])) :
        esc(gen ? :(($body for $v in $itr if $cond)) : :([$body for $v in $itr if $cond]))
end

function walk_and_transform(x, cond = nothing; gen = false)
    Meta.isexpr(x, :for) && return recompose_to_comprehension(x, cond; gen = gen), true
    x isa Expr || return x, false
    for (i, ex) in enumerate(x.args)
        ex, transformed = walk_and_transform(ex, cond; gen = gen)
        x.args[i] = ex
        transformed && return x, true # already transformed
    end
    return x, false
end

macro collect(ex) first(walk_and_transform(ex)) end
macro collect(cond, ex) first(walk_and_transform(ex, cond)) end

macro generator(ex) first(walk_and_transform(ex; gen = true)) end
macro generator(cond, ex) first(walk_and_transform(ex, cond; gen = true)) end

@inbounds function bruteforcesearch(f::Function, n::Integer, b::Integer = 2)
    baselen = length(string(b, base = 10))
    @collect for i = 1:b^n
        s = reverse(string(i, pad = n, base = b))[1:n] # cut off the overflowed char when `i == base^n`
        comb = @generator for ns in partition(s, baselen)
            parse(Int, ns) + 1 # for 1-based indexing
        end
        f(comb)
    end
end

partition(a, n) = @generator for i in 1:(length(a)÷n)
    s = 1+n*(i-1)
    e = n*i
    a[s:e]
end

# %% constants
# ------------

# %% body
# -------

function main(io = stdin)
    readto(target = '\n') = readuntil(io, target)
    readnum(T::Type{<:Number} = Int; dlm = isspace, kwargs...) =
        parse.(T, split(readto(), dlm; kwargs...))

    # handle IO and stuff
    N, = readnum()
    XYPs = [readnum() for _ in 1:N]
    println.(solve(N, XYPs))
end

function solve(N, XYPs)
    # TODO: precomputation
    ret = [typemax(Int) for n in 0:N]

    # calculate shortest distances for all the candidates
    bruteforcesearch(N, 3) do roads
        Ys = [0]
        Xs = [0]
        cnt = @collect for (road, (X, Y, _)) in zip(roads, XYPs)
            if road == 1
                push!(Xs, X)
                1
            elseif road == 2
                push!(Ys, Y)
                1
            else road == 3
                0 # no road here, no count
            end
        end |> sum
        ret[cnt + 1] = min(ret[cnt + 1], sumup_distances(XYPs, Xs, Ys))
    end

    return ret
end

sumup_distances(XYPs, Xs, Ys) = @generator for (X, Y, P) in XYPs
    shortest_distance(X, Y, Xs, Ys) * P
end |> sum

function shortest_distance(X, Y, Xs, Ys)
    xdist = minimum(abs(x - X) for x in Xs)
    ydist = minimum(abs(y - Y) for y in Ys)
    return min(xdist, ydist)
end

@static if @isdefined(Juno)
    main(open(normpath(@__DIR__, "E.in")))
else
    main()
end


# %% library
# ----------

# %% library docs
# ---------------

"""
    @collect [cond] ex

Constructs [`Array`](@ref) from lastly evaluated values from a `for` loop block that appears
  first within given `ex` expression.
If the optional `cond` expression is given, iterations  where the `cond` is `false` are
  effectively filtered out.

```julia-repl
julia> @collect isodd(i) for i = 1:3
           println("i = ", i); i
       end
i = 1
i = 3
2-element Array{Int64,1}:
 1
 3
```

See also: [`@generator`](@ref)
"""
macro collect end

"""
    @generator [cond] ex

Constructs [`Base.Generator`](@ref) from lastly evaluated values from a `for` loop block
  that appears first within given `ex` expression.
If the optional `cond` expression is given, iterations where the `cond` is `false` are
  effectively filtered out.

```julia-repl
julia> @generator isodd(i) for i = 1:3
           println("i = ", i); i
       end |> sum
i = 1
i = 3
4
```

See also: [`@collect`](@ref)
"""
macro generator end

"""
    bruteforcesearch(f::Function, n::Integer, b::Integer = 2)

Applies `f` for all the ...
$(""#=TODO: add some equation here for the future reference=#)

!!! note
    By default (i.e. when `b == 2`), this function is equivalent to bit-brute-force search.

```julia-repl
julia> bruteforcesearch(3) do comb
           @show collect(comb)
       end;
collect(mask) = [2, 1, 1]
collect(mask) = [1, 2, 1]
collect(mask) = [2, 2, 1]
collect(mask) = [1, 1, 2]
collect(mask) = [2, 1, 2]
collect(mask) = [1, 2, 2]
collect(mask) = [2, 2, 2]
collect(mask) = [1, 1, 1]

julia> bruteforcesearch(2, 3) do comb
           @show collect(comb)
       end;
collect(mask) = [2, 1]
collect(mask) = [3, 1]
collect(mask) = [1, 2]
collect(mask) = [2, 2]
collect(mask) = [3, 2]
collect(mask) = [1, 3]
collect(mask) = [2, 3]
collect(mask) = [3, 3]
collect(mask) = [1, 1]
```
"""
function bruteforcesearch end

# %% library body
# ---------------

function decompose_forblk(forblk)
    @assert Meta.isexpr(forblk, :for) "for block expression should be given"
    itrspec, body = forblk.args
    @assert Meta.isexpr(itrspec, :(=)) "invalid for loop specification"
    v, itr = itrspec.args
    return body, v, itr
end

function recompose_to_comprehension(forblk, cond = nothing; gen = false)
    body, v, itr = decompose_forblk(forblk)
    return isnothing(cond) ?
        esc(gen ? :(($body for $v in $itr)) : :([$body for $v in $itr])) :
        esc(gen ? :(($body for $v in $itr if $cond)) : :([$body for $v in $itr if $cond]))
end

function walk_and_transform(x, cond = nothing; gen = false)
    Meta.isexpr(x, :for) && return recompose_to_comprehension(x, cond; gen = gen), true
    x isa Expr || return x, false
    for (i, ex) in enumerate(x.args)
        ex, transformed = walk_and_transform(ex, cond; gen = gen)
        x.args[i] = ex
        transformed && return x, true # already transformed
    end
    return x, false
end

macro collect(ex) first(walk_and_transform(ex)) end
macro collect(cond, ex) first(walk_and_transform(ex, cond)) end

macro generator(ex) first(walk_and_transform(ex; gen = true)) end
macro generator(cond, ex) first(walk_and_transform(ex, cond; gen = true)) end

@inbounds function bruteforcesearch(f::Function, n::Integer, b::Integer = 2)
    baselen = length(string(b, base = 10))
    @collect for i = 1:b^n
        s = reverse(string(i, pad = n, base = b))[1:n] # cut off the overflowed char when `i == base^n`
        comb = @generator for ns in partition(s, baselen)
            parse(Int, ns) + 1 # for 1-based indexing
        end
        f(comb)
    end
end

partition(a, n) = @generator for i in 1:(length(a)÷n)
    s = 1+n*(i-1)
    e = n*i
    a[s:e]
end

# %% constants
# ------------

# %% body
# -------

function main(io = stdin)
    readto(target = '\n') = readuntil(io, target)
    readnum(T::Type{<:Number} = Int; dlm = isspace, kwargs...) =
        parse.(T, split(readto(), dlm; kwargs...))

    # handle IO and stuff
    N, = readnum()
    XYPs = [readnum() for _ in 1:N]
    # println.(solve(N, XYPs))
    solve(N, XYPs)
end

@inbounds function solve(N, XYPs)
    # TODO: precomputation
    Xcaches = [Dict{UInt,Int}() for _ in 1:N]
    Ycaches = [Dict{UInt,Int}() for _ in 1:N]

    bruteforcesearch(N, 2) do roads
        Xs = Set(X for (road, (X, _)) in zip(roads, XYPs) if road == 1)
        Ys = Set(Y for (road, (_, Y, _)) in zip(roads, XYPs) if road == 1)
        push!(Xs, 0); push!(Ys, 0)
        cache_distances!(XYPs, Xs, Ys, Xcaches, Ycaches)
    end

    ret = [typemax(Int) for n in 0:N]

    # calculate shortest distances for all the candidates
    bruteforcesearch(N, 3) do roads
        Xs = Set(0)
        Ys = Set(0)
        cnt = @collect for (road, (X, Y, _)) in zip(roads, XYPs)
            if road == 1
                push!(Xs, X)
                1
            elseif road == 2
                push!(Ys, Y)
                1
            else # no road here, no count
                0
            end
        end |> sum
        ret[cnt + 1] = min(ret[cnt + 1], sumup_distances(XYPs, Xs, Ys, Xcaches, Ycaches))
    end

    return ret
end

function cache_distances!(XYPs, Xs, Ys, Xcaches, Ycaches)
    for ((X, Y, _), Xcache, Ycache) in zip(XYPs, Xcaches, Ycaches)
        cache_distance!(Xcache, X, Xs)
        cache_distance!(Ycache, Y, Ys)
    end
end

function cache_distance!(cache, p, ps)
    k = hash(ps)
    haskey(cache, k) && return
    cache[k] = shortest_distance(p, ps)
end

shortest_distance(p, ps) = minimum(abs(p - x) for x in ps)

function sumup_distances(XYPs, Xs, Ys, Xcaches, Ycaches)
    xk = hash(Xs)
    yk = hash(Ys)
    @generator for ((_, _, P), Xcache, Ycache) in zip(XYPs, Xcaches, Ycaches)
        get_distance(xk, yk, Xcache, Ycache) * P
    end |> sum
end

@inbounds get_distance(xk, yk, Xcache, Ycache) = min(Xcache[xk], Ycache[yk])

@static if @isdefined(Juno)
    main(open(replace(@__FILE__, r"(.+)\.jl" => s"\1.in")))
else
    main()
end


# %% library
# ----------

# %% library docs
# ---------------

"""
    @collect [cond] ex

Constructs [`Array`](@ref) from lastly evaluated values from a `for` loop block that appears
  first within given `ex` expression.
If the optional `cond` expression is given, iterations  where the `cond` is `false` are
  effectively filtered out.

```julia-repl
julia> @collect isodd(i) for i = 1:3
           println("i = ", i); i
       end
i = 1
i = 3
2-element Array{Int64,1}:
 1
 3
```

See also: [`@generator`](@ref)
"""
macro collect end

"""
    @generator [cond] ex

Constructs [`Base.Generator`](@ref) from lastly evaluated values from a `for` loop block
  that appears first within given `ex` expression.
If the optional `cond` expression is given, iterations where the `cond` is `false` are
  effectively filtered out.

```julia-repl
julia> @generator isodd(i) for i = 1:3
           println("i = ", i); i
       end |> sum
i = 1
i = 3
4
```

See also: [`@collect`](@ref)
"""
macro generator end

"""
    bruteforcesearch(f::Function, n::Integer, b::Integer = 2)

Applies `f` for all the ...
$(""#=TODO: add some equation here for the future reference=#)

!!! note
    By default (i.e. when `b == 2`), this function is equivalent to bit-brute-force search.

```julia-repl
julia> bruteforcesearch(3) do comb
           @show collect(comb)
       end;
collect(mask) = [2, 1, 1]
collect(mask) = [1, 2, 1]
collect(mask) = [2, 2, 1]
collect(mask) = [1, 1, 2]
collect(mask) = [2, 1, 2]
collect(mask) = [1, 2, 2]
collect(mask) = [2, 2, 2]
collect(mask) = [1, 1, 1]

julia> bruteforcesearch(2, 3) do comb
           @show collect(comb)
       end;
collect(mask) = [2, 1]
collect(mask) = [3, 1]
collect(mask) = [1, 2]
collect(mask) = [2, 2]
collect(mask) = [3, 2]
collect(mask) = [1, 3]
collect(mask) = [2, 3]
collect(mask) = [3, 3]
collect(mask) = [1, 1]
```
"""
function bruteforcesearch end

# %% library body
# ---------------

function decompose_forblk(forblk)
    @assert Meta.isexpr(forblk, :for) "for block expression should be given"
    itrspec, body = forblk.args
    @assert Meta.isexpr(itrspec, :(=)) "invalid for loop specification"
    v, itr = itrspec.args
    return body, v, itr
end

function recompose_to_comprehension(forblk, cond = nothing; gen = false)
    body, v, itr = decompose_forblk(forblk)
    return isnothing(cond) ?
        esc(gen ? :(($body for $v in $itr)) : :([$body for $v in $itr])) :
        esc(gen ? :(($body for $v in $itr if $cond)) : :([$body for $v in $itr if $cond]))
end

function walk_and_transform(x, cond = nothing; gen = false)
    Meta.isexpr(x, :for) && return recompose_to_comprehension(x, cond; gen = gen), true
    x isa Expr || return x, false
    for (i, ex) in enumerate(x.args)
        ex, transformed = walk_and_transform(ex, cond; gen = gen)
        x.args[i] = ex
        transformed && return x, true # already transformed
    end
    return x, false
end

macro collect(ex) first(walk_and_transform(ex)) end
macro collect(cond, ex) first(walk_and_transform(ex, cond)) end

macro generator(ex) first(walk_and_transform(ex; gen = true)) end
macro generator(cond, ex) first(walk_and_transform(ex, cond; gen = true)) end

@inbounds function bruteforcesearch(f::Function, n::Integer, b::Integer = 2)
    baselen = length(string(b, base = 10))
    @collect for i = 1:b^n
        s = reverse(string(i, pad = n, base = b))[1:n] # cut off the overflowed char when `i == base^n`
        comb = @generator for ns in partition(s, baselen)
            parse(Int, ns) + 1 # for 1-based indexing
        end
        f(comb)
    end
end

partition(a, n) = @generator for i in 1:(length(a)÷n)
    s = 1+n*(i-1)
    e = n*i
    a[s:e]
end

# %% constants
# ------------

# %% body
# -------

function main(io = stdin)
    readto(target = '\n') = readuntil(io, target)
    readnum(T::Type{<:Number} = Int; dlm = isspace, kwargs...) =
        parse.(T, split(readto(), dlm; kwargs...))

    # handle IO and stuff
    N, = readnum()
    XYPs = [readnum() for _ in 1:N]
    println.(solve(N, XYPs))
end

@inbounds function solve(N, XYPs)
    # TODO: precomputation
    Xcaches = [Dict{UInt,Int}() for _ in 1:N]
    Ycaches = [Dict{UInt,Int}() for _ in 1:N]

    bruteforcesearch(N, 2) do roads
        Xs = Set(X for (road, (X, _)) in zip(roads, XYPs) if road == 1)
        Ys = Set(Y for (road, (_, Y, _)) in zip(roads, XYPs) if road == 2)
        push!(Xs, 0)
        push!(Ys, 0)
        cache_distances!(XYPs, Xs, Ys, Xcaches, Ycaches)
    end

    ret = [typemax(Int) for n in 0:N]

    # calculate shortest distances for all the candidates
    bruteforcesearch(N, 3) do roads
        Xs = Set(0)
        Ys = Set(0)

        cnt = @collect for (road, (X, Y, _)) in zip(roads, XYPs)
            if road == 1
                push!(Xs, X)
                1
            elseif road == 2
                push!(Ys, Y)
                1
            else road == 3
                0 # no road here, no count
            end
        end |> sum
        ret[cnt + 1] = min(ret[cnt + 1], sumup_distances(XYPs, Xs, Ys, Xcaches, Ycaches))
    end

    return ret
end

function cache_distances!(XYPs, Xs, Ys, Xcaches, Ycaches)
    for ((X, Y, _), Xcache, Ycache) in zip(XYPs, Xcaches, Ycaches)
        cache_distance!(Xcache, X, Xs)
        cache_distance!(Ycache, Y, Ys)
    end
end

function cache_distance!(cache, p, ps)
    k = hash(ps)
    haskey(cache, k) && return
    cache[k] = shortest_distance(p, ps)
end

shortest_distance(p, ps) = minimum(abs(p - x) for x in ps)

function sumup_distances(XYPs, Xs, Ys, Xcaches, Ycaches)
    @generator for ((_, _, P), Xcache, Ycache) in zip(XYPs, Xcaches, Ycaches)
        get_distance(Xs, Ys, Xcache, Ycache) * P
    end |> sum
end

@inbounds get_distance(Xs, Ys, Xcache, Ycache) = min(Xcache[hash(Xs)], Ycache[hash(Ys)])

@static if @isdefined(Juno)
    main(open(replace(@__FILE__, r"(.+)\.jl" => s"\1.in")))
else
    main()
end


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    L, R, d = parseMap(split(readline()))
    ans = 0
    for i in L:R
        if i % d == 0
            ans += 1
        end
    end
    println(ans)
end

main()

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


function main()
    Int L, R, d, ans, i
    L, R, d = split(readline())
    ans = 0
    for i in L:R
        if i % d == 0
            ans += 1
        end
    end
    println(ans)
end

main()


parseInt(x)=parse(Int, x)
parseMap(x::Array{SubString{String},1})=map(parseInt, x)

function main()
	l,r,d = readline() |> split |> parseMap
	x = 0
	k = 0
	while x<=r
		if l<=x<=r
			k += 1
		end
		x+=d
	end
	println(k)
end

main()


function main()
    L,R,d = reads(Int,Int,Int)
    c = 0
    for i in L:R
        if i % d == 0
            c += 1
        end
    end
    println(c)
end

import Base.parse
import Base.StringVector

parse(::Type{String},  str::AbstractString) = str
isdelim(x::UInt8, xs::Set{UInt8}) = x in xs
const delimset = Set([0x0a, 0x20])

function myreaduntil(s::IO, delims::Set{UInt8})::Vector{UInt8}
    out = StringVector(0)
    c::UInt8 = 0x00
    while !eof(s)
        c = read(s, UInt8)
        !isdelim(c, delims) && break
    end
    push!(out, c)
    eof(s) && return out
    while !eof(s)
        c = read(s, UInt8)
        isdelim(c, delims) && break
        push!(out, c)
    end
    return out
end

function readword(io::IO = stdin, delims = delimset)::String
    word = myreaduntil(io, delims)
    i = length(word)
    if i == 0 || word[i] != 0x0a
        return String(word)
    elseif i < 2 || word[i-1] != 0x0d
        return String(resize!(word,i-1))
    else
        return String(resize!(word,i-2))
    end
end

pread(ty) = parse(ty, readword())

reads(tys...)::Tuple{tys...} = Tuple{tys...}(pread(ty) for ty in tys)

function readvec(tys::Tuple , len::Signed)::Tuple{map(x -> Vector{x},tys)...}
    rv = Tuple{map(x -> Vector{x},tys)...}(Vector{ty}(undef,len) for ty in tys)
    for i in 1:len
        for j in 1:length(tys)
            @inbounds rv[j][i] = pread(tys[j])
        end
    end
    rv
end

readvec(ty::Type, len::Signed)::Vector{ty} = @inbounds ty[pread(ty) for i in 1:len]

function readmat(ty::Type, s...)::Matrix{ty}
    v = Matrix{ty}(undef, s...)
    @inbounds for i in 1:s[1]
        v[i,:] = readvec(ty, s[2])
    end
    v
end

main()


function main()
    L, R, d = parse.(Int, split(readline()))
    ans = 0
    for i in L:R
        if i % d == 0
            ans += 1
        end
    end

    println(ans)
end

main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
    n::Int=parseInt(readline())
    ans::Vector{Int}=[0 for i in 1:n]
    for x in 1:100
        for y in 1:100
            for z in 1:100
                tmp::Int=x^2+y^2+z^2+x*y+y*z+z*x
                if tmp<=n
                    ans[tmp]+=1
                end
            end
        end
    end
    for i in ans
        println(i)
    end
end
main()

Score : 300 points

Problem Statement

Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:

1 \leq x,y,z

x^2 + y^2 + z^2 + xy + yz + zx = n

Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).

Constraints

All values in input are integers.

1 \leq N \leq 10^4

Input

Input is given from Standard Input in the following format:

N

Output

Print N lines. The i-th line should contain the value f(i).

Sample Input 1

20

Sample Output 1

0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
0
0

For n=6, only (1,1,1) satisfies both of the conditions. Thus, f(6) = 1.

For n=11, three triples, (1,1,2), (1,2,1), and (2,1,1), satisfy both of the conditions. Thus, f(6) = 3.

For n=17, three triples, (1,2,2), (2,1,2), and (2,2,1), satisfy both of the conditions. Thus, f(17) = 3.

For n=18, three triples, (1,1,3), (1,3,1), and (3,1,1), satisfy both of the conditions. Thus, f(18) = 3.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
  N = parseInt(readline())
  S = String["" for i in 1:N]
  for i in 1:N
    S[i]=chomp(readline())
  end
  ac=count(S.=="AC")
  wa=count(S.=="WA")
  tle=count(S.=="TLE")
  re=count(S.=="RE")
  #N,K = parseMap(split(readline()))
  #p = parseMap(split(readline()))
#  println("$N,$S")
  println("AC x $ac")
  println("WA x $wa")
  println("TLE x $tle")
  println("RE x $re")
  #println("$p")
#  if mod(a,1000) != 0
#    println(1000-mod(a,1000))
#  else
#    println(0)
#  end
end
main()

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


using LinearAlgebra

function solve()
    H, W, K = parse.(Int, split(readline()))

    c = zeros(Int, H, W)

    for i = 1:H
        s = readline()
        for j = 1:W
            c[i,j] = Int(s[j] == '.' ? 0 : 1)
        end
    end

    sumrow = [sum(view(c, i, 1:W)) for i = 1:H]
    sumcol = [sum(view(c, 1:H, j)) for j = 1:W]

    stack = [[0],[1]]

    cnt = 0

    for i = 0:2^(H+W)
        x = i
        bits = []
        for j = 1:(H+W)
            push!(bits, x&1)
            x ÷= 2
        end

        P = Diagonal(bits[1:H])
        Q = Diagonal(bits[(H+1):(H+W)])
        if sum(P*c*Q) == K cnt += 1 end

    end

    println(cnt)
end

solve()

Score : 300 points

Problem Statement

We have a grid of H rows and W columns of squares. The color of the square at the i-th row from the top and the j-th column from the left (1 \leq i \leq H, 1 \leq j \leq W) is given to you as a character c_{i,j}: the square is white if c_{i,j} is ., and black if c_{i,j} is #.

Consider doing the following operation:

Choose some number of rows (possibly zero), and some number of columns (possibly zero). Then, paint red all squares in the chosen rows and all squares in the chosen columns.

You are given a positive integer K. How many choices of rows and columns result in exactly K black squares remaining after the operation? Here, we consider two choices different when there is a row or column chosen in only one of those choices.

Constraints

1 \leq H, W \leq 6

1 \leq K \leq HW

c_{i,j} is . or #.

Input

Input is given from Standard Input in the following format:

H W K
c_{1,1}c_{1,2}...c_{1,W}
c_{2,1}c_{2,2}...c_{2,W}
:
c_{H,1}c_{H,2}...c_{H,W}

Output

Print an integer representing the number of choices of rows and columns satisfying the condition.

Sample Input 1

2 3 2
..#
###

Sample Output 1

5

Five choices below satisfy the condition.

The 1-st row and 1-st column

The 1-st row and 2-nd column

The 1-st row and 3-rd column

The 1-st and 2-nd column

The 3-rd column

Sample Input 2

2 3 4
..#
###

Sample Output 2

1

One choice, which is choosing nothing, satisfies the condition.

Sample Input 3

2 2 3
##
##

Sample Output 3

0

Sample Input 4

6 6 8
..##..
.#..#.
#....#
######
#....#
#....#

Sample Output 4

208


parseInt(x)=parse(Int, x)
parseMap(x::Array{SubString{String},1})=map(parseInt, x)

function main()
	n = readline() |> parseInt
	a = readline() |> split |> parseMap |> sort
	v = 0
	for i in n:-1:2
		v += a[i]
	end
	println(v)
end

main()

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


function main()
  n=parse(Int,readline())
  a=sort(parse.(Int,split(readline())),rev=true)
  ans=0
  for i=1:n-1; ans+=a[1+fld(i,2)]; end
  println(ans)
end
main()


readints()=parse.(Int,split(readline()))
readint()=parse.(Int,readline())

N=readint()
A=readints()
B=sort(A)
print(sum(B[2:end]))


parseInt(x) = parse(Int128, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
  N = parseInt(readline())
  A = parseMap(split(readline()))
  A = sort(A,rev=true)
  #println(A)
  if N%2==0
    imax=div(N,2)
  else
    imax=div(N,2)+1
  end
  sum = 0
  for i in 1:imax
      if i == 1
        sum += A[i]
      else
        if N%2==0
          sum += 2*A[i]
        else
          if i != imax
            sum += 2*A[i]
          else
            sum += A[i]
          end
        end
      end
  end
  println("$sum")
end
main()


# SPDX-License-Identifier: X11
# 2020-08-30
# Multiplication 4 (500pt)

const M = 1000000007

function main()
  N, K = parse.(Int, split(readline(), " "))
  A = parse.(Int, split(readline(), " "))
  T = 1

  if N == K
    for i ∈ A
      T *= i ⨳ M
      T = T ⨳ M
    end
    println(T)
    return
  end

  sort!(A; lt = test, rev = true)

  B = A[1:K]
  if oddneg(B)
    R = A[K + 1:end]
    fp = firstpos(R) === nothing ? -1 : firstpos(R)
    fpv = fp == -1 ? fp : R[fp]
    fn = firstneg(R) === nothing ? -1 : firstneg(R)
    fnv = fn == -1 ? fn : abs(R[fn])

    if fpv > fnv || fpv < fnv && lastpos(B) === nothing && fpv > -1
      B[lastneg(B)] = R[fp]
    elseif fpv < fnv && !(lastpos(B) === nothing)
      B[lastpos(B)] = R[fn]
    elseif fpv == fnv
      B[K] = B[K] < 0 ? R[fp] : R[fn]
    else
      if A[N] == 0
        println(0)
        return
      else
        B = A[end + 1 - K:end]
      end
    end
  end

  for i ∈ B
    T *= i ⨳ M
    T = T ⨳ M
  end

  println(T)
end

function test(x::Int, y::Int)
  return abs(x) == abs(y) ? x < y : abs(x) < abs(y);
end

⨳(x, y) = mod(x, y)
oddneg(A) = count(x -> x < 0, A) & 1 == 1
firstneg(A) = findfirst(x -> x < 0, A)
firstpos(A) = findfirst(x -> x > 0, A)
lastneg(A) = findlast(x -> x < 0, A)
lastpos(A) = findlast(x -> x > 0, A)

main()

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


const MOD = 1000000007
function main()
    n, k = parse.(Int, split(readline()))
    a = parse.(Int, split(readline()))
    s = filter(x->x>=0, a)
    t = filter(x->x<0, a)
    sort!(s)
    sort!(t, rev=true)
    S = length(s)
    T = length(t)

    ok = false
    if S > 0
        if n == k
            ok = (T % 2 == 0)
        else
            ok = true
        end
    else
        ok = (k % 2 == 0)
    end

    ans = 1
    if !ok
        sort(a, by=abs)
        for i in 1:k
            ans *= a[i]
            ans = mod(ans, MOD)
        end
    else
        if k%2 == 1
            ans *= pop!(s)
        end
        p = Int[]
        while length(s) >= 2
            x = pop!(s)
            x *= pop!(s)
            push!(p, x)
        end
        while length(t) >= 2
            x = pop!(t)
            x *= pop!(t)
            push!(p, x)
        end
        sort!(p, rev=true)
        for i in 1:k÷2
            ans *= mod(p[i], MOD)
            ans = mod(ans, MOD)
        end
    end
    println(ans)
end

main()


a = parse(Int, readline())
println(a+a^2+a^3)

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


num = parse(Int,readline())
print(num + num^2 + num^3)


function main()
    a = parse(Int,readline())

    println(a + a^2 + a^3)
end
main()


lines = readline(stdin)
num = parse(Int,lines);
println(num + num^2 + num^3);


rl() = [parse(Int64, x) for x in split(readline())]

a, = rl()

println("$(a+a*a+a*a*a)")


using DataStructures
const double = Float64
const int = Int64

parseint(x) = parse(int, x)
readint() = map(parseint, split(readline()))

function main()
  S = readline()
  T = readline()

  cout = 0
  for i in 1:length(S)
    if S[i] != T[i]
      cout += 1
    end
  end
  println(cout)
end

main()

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.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
    count = 0
    S = chomp(readline())
    T = chomp(readline())
    for i in 1:length(S)
        if S[i] != T[i]
            count += 1
        end
    end

    println(count)
end

main()


const double = Float64
const int = Int64

parseint(x) = parse(int, x)
readint() = map(parseint, split(readline()))

function main()
  a = readline()

  b = lowercase(a)
  if a != b
    println("A")
  else
    println("a")
  end

end

main()

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.


function  parse_int(x)
    parse(Int, x)
end
function  MAP()
    map(parse_int, split(readline(), " "))
end

function solve()
    N, K = MAP()
    p = MAP()
    sort!(p)
    ans = 0
    for i = 1 : K
        ans += p[i]
    end
    ans
end

ans = solve()
println("$(ans)")

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


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
    n,k=parseMap(split(readline()))
    p=parseMap(split(readline()))
    sort!(p)
    println(sum(p[1:k]))
end
main()


function main()
    n, k = parse.(Int , split(readline()))
    p = parse.(Int, split(readline()))
    sort!(p)
    println(sum(p[1:k]))
end

main()


function main()
    n = parse(Int, readline())
    println(f(n))
end

function f(n)
    n == 0 && return ""
    n -= 1
    return f(n÷26) *  ('a'+n%26)
end

main()

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


function main()
  n=parse(Int,readline())
  bucket=[0 for i=1:10^5]
  sum=0
  for i=parse.(Int,split(readline())); sum+=i; bucket[i]+=1;end
  q=parse(Int,readline())
  for i=1:q
    b,c=parse.(Int,split(readline()))
    sum+=bucket[b]*(c-b)
    bucket[c]+=bucket[b]
    bucket[b]=0
    println(sum);end
end
main()

Score : 400 points

Problem Statement

You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.

You will now successively do the following Q operations:

In the i-th operation, you replace every element whose value is B_{i} with C_{i}.

For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

Constraints

All values in input are integers.

1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}

B_{i} \neq C_{i}

Input

Input is given from Standard Input in the following format:

N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

Output

Print Q integers S_{i} to Standard Output in the following format:

S_{1}
S_{2}
\vdots
S_{Q}

Note that S_{i} may not fit into a 32-bit integer.

Sample Input 1

4
1 2 3 4
3
1 2
3 4
2 4

Sample Output 1

11
12
16

Initially, the sequence A is 1,2,3,4.

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

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

Sample Output 2

8
4
4

Note that the sequence A may not contain an element whose value is B_{i}.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000


N=parse(Int,readline())
A=parse.(Int,split(readline()))
Axor=xor(A...)
for i in A
    print(xor(Axor,i)," ")
end

Score : 500 points

Problem Statement

There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.

Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.

Recently, they learned the operation called xor (exclusive OR).

What is xor?

For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is defined as follows:

When x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.

For example, 3~\textrm{xor}~5 = 6.

They wanted to use this operation quickly, so each of them calculated the xor of the integers written on their scarfs except his scarf.

We know that the xor calculated by Snuke Cat i, that is, the xor of the integers written on the scarfs except the scarf of Snuke Cat i is a_i.
Using this information, restore the integer written on the scarf of each Snuke Cat.

Constraints

All values in input are integers.

2 \leq N \leq 200000

N is even.

0 \leq a_i \leq 10^9

There exists a combination of integers on the scarfs that is consistent with the given information.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print a line containing N integers separated with space.

The i-th of the integers from the left should represent the integer written on the scarf of Snuke Cat i.

If there are multiple possible solutions, you may print any of them.

Sample Input 1

4
20 11 9 24

Sample Output 1

26 5 7 22

5~\textrm{xor}~7~\textrm{xor}~22 = 20

26~\textrm{xor}~7~\textrm{xor}~22 = 11

26~\textrm{xor}~5~\textrm{xor}~22 = 9

26~\textrm{xor}~5~\textrm{xor}~7 = 24

Thus, this output is consistent with the given information.


parseInt(x)=parse(Int, x)
parseMap(x::Array{SubString{String},1})=map(parseInt, x)

function main()
	x = readline() |> parseInt
	k = 1
	while (k*x)%360!=0
		k += 1
	end
	println(k)
end

main()

Score : 200 points

Problem Statement

Takahashi is standing on a two-dimensional plane, facing north. Find the minimum positive integer K such that Takahashi will be at the starting position again after he does the following action K times:

Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise.

Constraints

1 \leq X \leq 179

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of times Takahashi will do the action before he is at the starting position again.

Sample Input 1

90

Sample Output 1

4

Takahashi's path is a square.

Sample Input 2

1

Sample Output 2

360


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
    x=parseMap(split(readline()))
    for i in 1:5
        if x[i]==0
            println(i)
            break
        end
    end
end
main()

Score : 100 points

Problem Statement

We have five variables x_1, x_2, x_3, x_4, and x_5.

The variable x_i was initially assigned a value of i.

Snuke chose one of these variables and assigned it 0.

You are given the values of the five variables after this assignment.

Find out which variable Snuke assigned 0.

Constraints

The values of x_1, x_2, x_3, x_4, and x_5 given as input are a possible outcome of the assignment by Snuke.

Input

Input is given from Standard Input in the following format:

x_1 x_2 x_3 x_4 x_5

Output

If the variable Snuke assigned 0 was x_i, print the integer i.

Sample Input 1

0 2 3 4 5

Sample Output 1

1

In this case, Snuke assigned 0 to x_1, so we should print 1.

Sample Input 2

1 2 0 4 5

Sample Output 2

3


function main()

  xs = map(x -> parse(Int, x), split(readline()))

  for i in 1:5

    if xs[i] == 0
      println(i)
      break
    end

  end

end

main()


function main()

  X, Y = map(x -> parse(Int, x), split(readline()))

  ans = false

  if 2X == Y || 4X == Y
    ans = true
  end

  for i in 0:X
    for j in i+1:X

      if 2i + 4j == Y
        ans = true
      end

    end
  end

  if ans
    println("Yes")
  else
    println("No")
  end

end

main()

Score : 200 points

Problem Statement

There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.

Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.

Constraints

1 \leq X \leq 100

1 \leq Y \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If there is a combination of numbers of cranes and turtles in which the statement is correct, print Yes; otherwise, print No.

Sample Input 1

3 8

Sample Output 1

Yes

The statement "there are 3 animals in total in the garden, and they have 8 legs in total" is correct if there are two cranes and one turtle. Thus, there is a combination of numbers of cranes and turtles in which the statement is correct.

Sample Input 2

2 100

Sample Output 2

No

There is no combination of numbers of cranes and turtles in which this statement is correct.

Sample Input 3

1 2

Sample Output 3

Yes

We also consider the case in which there are only cranes or only turtles.


function main()

  X, Y = map(x -> parse(Int, x), split(readline()))

  ans = false

  for i in 1:X
    for j in i+1:X

      if 2i + 4j = Y
        ans = true
      end

    end
  end

  if ans
    println("Yes")
  else
    println("No")
  end

end

main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
#１行に数値一つならparseInt(readline())
#１行に数値複数ならparseMap(split(readline()))を行数分。
# 例：n,k = readline() |> split |> parseMap
#      a = readline() |> split |> parseMap
function main()
  #a = parseInt(readline())
  X,Y = parseMap(split(readline()))
  #println("$X,$Y")

  if (Y-2*X) % 2 == 0 && (4*X-Y) % 2 == 0
    y0 = (Y-2*X)/2
    x0 = (4*X-Y)/2
    if x0 > 0 && y0 > 0
      println("Yes")
    else
      if x0==0 || y0==0
        println("Yes")
      else
        println("No")
      end
    end
  end
end
main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
#１行に数値一つならparseInt(readline())
#１行に数値複数ならparseMap(split(readline()))を行数分。
# 例：n,k = readline() |> split |> parseMap
#      a = readline() |> split |> parseMap
function main()
  #a = parseInt(readline())
  X,N = parseMap(split(readline()))
  p = parseMap(split(readline()))
  #println("$X,$N,$p")
  All = [i for i in -100:1:200]
  for i in 1:N
    #println(findall(isequal(p[i],All)))
    #println(findall(All .== p[i])[1])
    splice!(All,findall(All .== p[i])[1])
  end
  #println("$All")
  q = All .- X
  q = abs.(q)
  #println("$q")
  #println("AnsLoc:",findall(isequal(minimum(q)),q))
  #println("Ans:",All[findall(isequal(minimum(q)),q)])
  #println(size(All[findall(isequal(minimum(q)),q)]))
  if size(All[findall(isequal(minimum(q)),q)])[1] > 1
    println(minimum(All[findall(isequal(minimum(q)),q)]))
  else
    println(All[findall(isequal(minimum(q)),q)][1])
  end
  #=
      if x0==0 && y0 > 0
        println("Yes")
      elseif y0==0 && x0 > 0
        println("Yes")

      else
        println("No")
      end
  =#
end
main()

Score : 300 points

Problem Statement

Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N.

Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, report the smallest such integer.

Constraints

1 \leq X \leq 100

0 \leq N \leq 100

1 \leq p_i \leq 100

p_1, \ldots, p_N are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X N
p_1 ... p_N

Output

Print the answer.

Sample Input 1

6 5
4 7 10 6 5

Sample Output 1

8

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the one nearest to 6 is 8.

Sample Input 2

10 5
4 7 10 6 5

Sample Output 2

9

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the ones nearest to 10 are 9 and 11. We should print the smaller one, 9.

Sample Input 3

100 0

Sample Output 3

100

When N = 0, the second line in the input will be empty. Also, as seen here, X itself can be the answer.


parseInt(x) = parse(Int, x)
parseArray(x::Array{SubString{String}, 1}) = map(parseInt, x)

function main()
  x, n = readline() |> split |> parseArray
  p = readline() |> split |> parseArray

  a = collect(1:100)
  for pp in p
    a[pp] = -1
  end
  ans = 0
  for i in 0:100
    j = max(x-i, 0)
    if (j != 0 && a[j] != -1) || j == 0
      ans = j
      break
    end
    j = min(x+i, 101)
    if j != 101 && a[j] != -1
      ans = j
      break
    end
  end
  println(ans)
end

main()


readints()=parse.(Int,split(readline()))
X,N=readints()
p=readints()

F=ones(Bool,100)
for i in p
    F[i]=false
end
ans0=0
for i in 0:100
    s=X-i > 0 ? X-i : X
    if F[s]
        global ans0=s
        break
    end
    s=X+i <= 100 ? X+i : X
    if F[s]
        ans0=s
        break
    end
end
print(ans0)


parseInt(x) = parse(Int, x)
parseArray(x::Array{SubString{String}, 1}) = map(parseInt, x)

function main()
  x, n = readline() |> split |> parseArray
  p = readline() |> split |> parseArray

  a = collect(1:100)
  for pp in p
    a[pp] = -1
  end
  ans = 0
  for i in 0:100
    j = max(x-i, 1)
    if a[j] != -1
      ans = j
      break
    end
    j = min(x+i, n)
    if a[j] != -1
      ans = j
      break
    end
  end
  println(ans)
end

main()


function main()
	H,W,K=map(x->parse(Int,x),split(readline()))
	sx,sy,gx,gy=map(x->parse(Int,x),split(readline()))
	S=readlines()
	D=ones(Int,H,W)*10^9
	D[sx,sy]=1
	Q=[sx=>sy]
	while !isempty(Q)
		x,y=popfirst!(Q)
		for (dx,dy)=(0=>1,0=>-1,1=>0,-1=>0)
			tx,ty=x,y
			E=D[x,y]+1
			for _=1:K
				tx+=dx
				ty+=dy
				if 1<=tx<=H&&1<=ty<=W&&S[tx][ty]=='.'
					if D[tx,ty]>E
						D[tx,ty]=E
						push!(Q,tx=>ty)
					elseif D[tx,ty]<E
						break
					end
				else
					break
				end
			end
		end
	end
	println(D[gx,gy]%10^9-1)
end
main()

Score : 600 points

Problem Statement

Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.

Some of the squares have a lotus leaf on it and cannot be entered.
The square (i,j) has a lotus leaf on it if c_{ij} is @, and it does not if c_{ij} is ..

In one stroke, Snuke can move between 1 and K squares (inclusive) toward one of the four directions: north, east, south, and west.
The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden.

Find the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2).
If the travel from (x_1,y_1) to (x_2,y_2) is impossible, point out that fact.

Constraints

1 \leq H,W,K \leq 10^6

H \times W \leq 10^6

1 \leq x_1,x_2 \leq H

1 \leq y_1,y_2 \leq W

x_1 \neq x_2 or y_1 \neq y_2.

c_{i,j} is . or @.

c_{x_1,y_1} = .

c_{x_2,y_2} = .

All numbers in input are integers.

Input

Input is given from Standard Input in the following format:

H W K
x_1 y_1 x_2 y_2
c_{1,1}c_{1,2} .. c_{1,W}
c_{2,1}c_{2,2} .. c_{2,W}
:
c_{H,1}c_{H,2} .. c_{H,W}

Output

Print the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2), or print -1 if the travel is impossible.

Sample Input 1

3 5 2
3 2 3 4
.....
.@..@
..@..

Sample Output 1

5

Initially, Snuke is at the square (3,2).
He can reach the square (3, 4) by making five strokes as follows:

From (3, 2), go west one square to (3, 1).

From (3, 1), go north two squares to (1, 1).

From (1, 1), go east two squares to (1, 3).

From (1, 3), go east one square to (1, 4).

From (1, 4), go south two squares to (3, 4).

Sample Input 2

1 6 4
1 1 1 6
......

Sample Output 2

2

Sample Input 3

3 3 1
2 1 2 3
.@.
.@.
.@.

Sample Output 3

-1


function main()

  S = chomp(readline())

  println(S[1:3])

end

main()

Score : 100 points

Problem Statement

When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters.
You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him.

Constraints

3 \leq |S| \leq 20

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print your answer.

Sample Input 1

takahashi

Sample Output 1

tak

Sample Input 2

naohiro

Sample Output 2

nao


readints()=parse.(Int,split(readline()))
readint()=parse.(Int,readline())

A,V=readints()
B,W=readints()
T=readint()

D_d=abs(A-B)
D_v=(V-W)

if D_d <= D_v*T
    print("YES")
else
    print("NO")
end

Score : 200 points

Problem Statement

Two children are playing tag on a number line. (In the game of tag, the child called "it" tries to catch the other child.) The child who is "it" is now at coordinate A, and he can travel the distance of V per second.
The other child is now at coordinate B, and she can travel the distance of W per second.

He can catch her when his coordinate is the same as hers.
Determine whether he can catch her within T seconds (including exactly T seconds later).
We assume that both children move optimally.

Constraints

-10^9 \leq A,B \leq 10^9

1 \leq V,W \leq 10^9

1 \leq T \leq 10^9

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A V
B W
T

Output

If "it" can catch the other child, print YES; otherwise, print NO.

Sample Input 1

1 2
3 1
3

Sample Output 1

YES

Sample Input 2

1 2
3 2
3

Sample Output 2

NO

Sample Input 3

1 2
3 3
3

Sample Output 3

NO


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

A, V = parseMap(split(readline()))
B, W = parseMap(split(readline()))
T = parseInt(readline())

d = abs(A - B)

if A != B
    if V - W != 0
        t  = d / (V - W)
    else
        t = 10 ^ 10
    end
else
    t = 0
end

if t > 0
    if  T >= t
        println("YES")
    else
        println("NO")
    end
elseif t == 0
    println("Yes")
else
    println("NO")
end


parseInt(x) = parse(Int, x)
parseArray(x::Array{SubString{String}, 1}) = map(parseInt, x)

function main()
  a, v = readline() |> split |> parseArray
  b, w = readline() |> split |> parseArray
  t = readline() |> parseInt

  ans="NO"
  if v > w && abs(a-b)/(v-w)<=t
    ans="YES"
  end

  println(ans)
end

main()


parseInt(x) = parse(Int, x)
parseArray(x::Array{SubString{String}, 1}) = map(parseInt, x)

function main()
  n,k = readline() |> split |> parseArray
  a = zeros(Int, n)
  a = readline() |> split |> parseArray

  for _ in 1:min(k, ceil(Int, 50))
    imos = zeros(Int, n+1)
    for i in 1:n
      d = a[i]
      imos[max(i-d, 1)] += 1
      imos[min(i+d+1, n+1)] += -1
    end
    a = zeros(Int, n)
    c = 0
    for i in 1:n
      c = c+imos[i]
      a[i] = c
    end
  end
  println.(a)
end

main()

Score : 500 points

Problem Statement

We have N bulbs arranged on a number line, numbered 1 to N from left to right.
Bulb i is at coordinate i.

Each bulb has a non-negative integer parameter called intensity.
When there is a bulb of intensity d at coordinate x, the bulb illuminates the segment from coordinate x-d-0.5 to x+d+0.5.
Initially, the intensity of Bulb i is A_i. We will now do the following operation K times in a row:

For each integer i between 1 and N (inclusive), let B_i be the number of bulbs illuminating coordinate i. Then, change the intensity of each bulb i to B_i.

Find the intensity of each bulb after the K operations.

Constraints

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

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

0 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \ldots A_N

Output

Print the intensity A{'}_i of each bulb i after the K operations to Standard Output in the following format:

A{'}_1 A{'}_2 \ldots A{'}_N

Sample Input 1

5 1
1 0 0 1 0

Sample Output 1

1 2 2 1 2

Initially, only Bulb 1 illuminates coordinate 1, so the intensity of Bulb 1 becomes 1 after the operation.
Similarly, the bulbs initially illuminating coordinate 2 are Bulb 1 and 2, so the intensity of Bulb 2 becomes 2.

Sample Input 2

5 2
1 0 0 1 0

Sample Output 2

3 3 4 4 3


function main()
    N,K = reads(Int,Int)
    a = readvec(Int,N)
    for i in 1:K
        next = zeros(Int, N)
        for j in 1:N
            next[max(1,j-a[j]):min(N,j+a[j])] .+= 1
        end
        a == next && break
        a = next
    end
    for i in 1:N
        if i == N
            println(a[i])
            return
        end
        print(a[i]," ")
    end
end

import Base.parse
import Base.StringVector

parse(::Type{String},  str::AbstractString) = str
isdelim(x::UInt8, xs::Set{UInt8}) = x in xs
const delimset = Set([0x0a, 0x20])

function myreaduntil(s::IO, delims::Set{UInt8})::Vector{UInt8}
    out = StringVector(0)
    c::UInt8 = 0x00
    while !eof(s)
        c = read(s, UInt8)
        !isdelim(c, delims) && break
    end
    push!(out, c)
    eof(s) && return out
    while !eof(s)
        c = read(s, UInt8)
        isdelim(c, delims) && break
        push!(out, c)
    end
    return out
end

function readword(io::IO = stdin, delims = delimset)::String
    word = myreaduntil(io, delims)
    i = length(word)
    if i == 0 || word[i] != 0x0a
        return String(word)
    elseif i < 2 || word[i-1] != 0x0d
        return String(resize!(word,i-1))
    else
        return String(resize!(word,i-2))
    end
end

pread(ty) = parse(ty, readword())

reads(tys...)::Tuple{tys...} = Tuple{tys...}(pread(ty) for ty in tys)

function readvec(tys::Tuple , len::Signed)::Tuple{map(x -> Vector{x},tys)...}
    rv = Tuple{map(x -> Vector{x},tys)...}(Vector{ty}(undef,len) for ty in tys)
    for i in 1:len
        for j in 1:length(tys)
            @inbounds rv[j][i] = pread(tys[j])
        end
    end
    rv
end

readvec(ty::Type, len::Signed)::Vector{ty} = @inbounds ty[pread(ty) for i in 1:len]

function readmat(ty::Type, s...)::Matrix{ty}
    v = Matrix{ty}(undef, s...)
    @inbounds for i in 1:s[1]
        v[i,:] = readvec(ty, s[2])
    end
    v
end

main()


function main()
    n, k = parse.(Int, split(readline()))
    a = parse.(Int, split(readline()))

    for i in 1:min(k, 41)
        b = zeros(Int, n)
        for j in 1:n
            l = max(1, j-a[j])
            r = min(j+a[j], n)
            b[l] += 1
            r + 1 <= n && (b[r+1] -= 1)
        end
        for j in 2:n
            b[j] += b[j-1]
        end
        a = b
    end

    for i in a
        print(i," ")
    end
    println()

end

function getrange(i, x, m)
    l = max(1, i-x)
    r = min(i+x, m)

end

main()


const double = Float64
const int = Int64

parseint(x) = parse(int, x)
readint() = map(parseint, split(readline()))

function main()
  N, K = readint()
  A = readint()

  B = zeros(int,N)
  Nmax = 0
  for i in 1:K
    B = zeros(int,N)
    for j in 1:N
      l=max(1,j-A[j])
      r=min(N,j+A[j])
      B[l] += 1
      r+1 <= N && (B[r+1] -=1)
    end
    for j in 2:N
      B[j] += B[j-1]
    end
    s = 0
    for j in 1:N
      if B[j] == N
        s+=1
      end
    end
    if s == N
      for j = 1:N
        print(N," ")
      end
      println()
      return
    end
    A = B
  end
  for i in 1:N
    print(A[i]," ")
  end
  println()

end

main()


function main()
    n, k = parse.(Int, split(readline()))
    a = parse.(Int, split(readline()))

    h = Int(ceil(log2(n)))+1
    t = Vector{Vector{Int}}(undef, h)
    t[end] = a;
    for i in h-1:-1:1
        t[i] = zeros(Int, Int(ceil(length(t[i+1])/2)))
    end

    for i in 1:k
        p = zeros(Int, length(a))
        for j in 1:n
            p[getrange(j, a[j], n)] .+= 1
        end
        a = p
    end

    for i in a
        print(i," ")
    end
    println()

end

function getrange(i, x, m)
    l = max(1, i-x)
    r = min(i+x, m)
    l:r
end

main()


function calc(A)
    B=zeros(Int32,N)
    let i=1
        while i<=N
            #xmin=ceil(Int64, i-A[i]-0.5)
            #xmax=floor(Int64, i+A[i]+0.5)
            xmin=i-A[i]
            xmax=i+A[i]+0.5
            if xmin >= 1
                j=xmin
            else
                j=1
            end
            if xmax > N
                xmax = N
            end

            while j<=xmax
                B[j] += 1
                j += 1
            end
            i += 1
        end
        #println(B)
        B
    end
end

tmp=readline()
N,K=parse.(Int32,split(tmp))
tmp=readline()
#A=zeros(Int32,(N,K))
#A[1:end,1]=parse.(Int32,split(tmp))
#println("$N,$K,$A")
A=parse.(Int32,split(tmp))
let kl=1
    while kl<=K
        B=calc(A)
        let i=1
            while i<=N
                A[i]=B[i]
                if kl==K
                    print(A[i]," ")
                end
                i += 1
            end
        end
        kl+=1
    end
end


function getB(A)
    B=A*0
    for i in 1:(length(A))
        n_start=i-A[i]
        n_start<1 && (n_start=1)
        n_end=i+A[i]
        n_end>length(A) && (n_end=length(A))
        B[n_start:n_end].+=1
    end
    B
end

function main()
    readints()=parse.(Int,split(readline()))
    N,K=readints()
    A=readints()

    for i in 1:K
        A=getB(A)
    end

    for i in A
        print(i," ")
    end
end
main()


tmp=readline()
N,K=parse.(Int32,split(tmp))
tmp=readline()
A=parse.(Int32,split(tmp))
#println("$N,$K,$A")
let kl=1
    while kl<=K
        B=zeros(Int32,N)
        #println("$B")
        let i=1
            while i<=N
                xmin=ceil(Int64, i-A[i]-0.5)
                xmax=floor(Int64, i+A[i]+0.5)
                if xmin >= 1
                    j=xmin
                else
                    j=1
                end
                if xmax > N
                    xmax = N
                end

                while j<=xmax
                    B[j] += 1
                    j += 1
                end
                i += 1
            end
        end
        #A = B
        let i=1
            while i<=N
                A[i]=B[i]
                if kl=K
                    print(A[i]," ")
                end
                i += 1
            end
        end
        kl += 1
    end
    #for i in 1:N
    #    print(A[i]," ")
    #end
end


tmp=readline()
N,K=parse.(Int64,split(tmp))
tmp=readline()
A=parse.(Int64,split(tmp))
#println("$N,$K,$A")
let kl=1
    while kl<=K
        B=zeros(Int64,N)
        #println("$B")
        let i=1
            while i<=N
                xmin=ceil(Int64, i-A[i]-0.5)
                xmax=floor(Int64, i+A[i]+0.5)
                if xmin >= 1
                    j=xmin
                else
                    j=1
                end
                if xmax > N
                    xmax = N
                end

                while j<=xmax
                    B[j] += 1
                    j += 1
                end
                i += 1
            end
        end
        #A = B
        let i=1
            while i<=N
                A[i]=B[i]
                i += 1
            end
        end

        kl += 1
    end
    for i in 1:N
        print(A[i]," ")
    end
end


#N,K=5,2
#A=[1,0,0,1,0]
function getB(A)
    B=A*0
    for i in 1:(length(A))
        for j in 1:(length(A))
            if abs(i-j)<=A[j]
                B[i]+=1
            end
        end
    end
    B
end

function main()
  readints()=parse.(Int,split(readline()))
N,K=readints()
A=readints()

for i in 1:K
    A=getB(A)
end
s=""
for i in A
    s*=string(i)*" "
end
print(s[1:(end-1)])
end
main()


parseInt(x)=parse(Int, x)
parseMap(x::Array{SubString{String},1})=map(parseInt, x)

function main()
	n,k = readline() |> split |> parseMap
	a = readline() |> split |> parseMap
	l = zeros(Int,n)
	r = zeros(Int,n)
	for i in 1:n
		l[i]=max(1,i-a[i])
		r[i]=min(n,i+a[i])
	end
	for i in 1:k
		b = zeros(Int,n)
		for j in 1:n
			b[l[j]]+=1
			if r[j]<n
				b[r[j]+1]-=1
			end
		end
		for j in 2:n
			b[j]+=b[j-1]
		end
		a = copy(b)
		if sum(b)==n*n
			break
		end
		for j in 1:n
			l[j]=max(1,j-a[j])
			r[j]=min(n,j+a[j])
		end
	end
	for i in 1:n-1
		print(a[i]," ")
	end
	println(a[n])
end

main()


# Q.1
function A01(x,y)
    if count_zeros(y) > count_zeros(x)
        x = y
    elseif count_zeros(y) == count_zeros(x)
        xor(x,A[])
    end
    x
end

function A02(x,y)
    if count_zeros(y) > count_zeros(x)
        x = y
    elseif count_zeros(y) == count_zeros(x)
        x = y
    end
    x
end

function A11(x,y)
    if count_zeros(y) < count_zeros(x)
        x = y
    elseif count_zeros(y) == count_zeros(x)
        x = x
    end
    x
end

function A12(x,y)
    if count_zeros(y) < count_zeros(x)
        x = y
    elseif count_zeros(y) == count_zeros(x)
        x = y
    end
    x
end

function calc(A,S)
    let j=1
        x = Int128(0)
        while j<=length(S)
            jun = parse(Int128,S[j])
            #println(jun)
            y = xor(x,A[j])
            #println(count_zeros(y)," vs ",count_zeros(x))
            if jun==0
                if count_zeros(y) > count_zeros(x)
                    x = y
                elseif count_zeros(y) == count_zeros(x)
                    if j!=length(S) && count_zeros(xor(x,A[j+1])) < count_zeros(xor(y,A[j+1]))
                        x = y
                    end
                end
#                x1 = A01(x,y)
#                x2 = A02(x,y)
            else
                if count_zeros(y) < count_zeros(x)
                    x = y
                elseif count_zeros(y) == count_zeros(x)
                    if j!=length(S) && count_zeros(xor(x,A[j+1])) > count_zeros(xor(y,A[j+1]))
                        x = y
                    end
                end
#                x1 = A11(x,y)
#                x2 = A12(x,y)
            end

            #println("j = $j, turn: $jun, Aâ±¼ = $(A[j]), x = $x")
            j += 1
        end
        #println("xans = ",x)
        if x==0
            #println(0)
            ans=0
        else
            #println(1)
            ans=1
        end
        ans
    end
end

function calc2(A,S)
    let j=1
        x = Int128(0)
        while j<=length(S)
            jun = parse(Int128,S[j])
            #println(jun)
            y = xor(x,A[j])
            #println(count_zeros(y)," vs ",count_zeros(x))
            if jun==0
                if count_zeros(y) >= count_zeros(x)
                    x = y
                end
            else
                if count_zeros(y) <= count_zeros(x)
                    x = y
                end
            end
            #println("j = $j, turn: $jun, Aâ±¼ = $(A[j]), x = $x")
            j += 1
        end
        #println("xans = ",x)
        if x==0
            #println(0)
            ans=0
        else
            #println(1)
            ans=1
        end
        ans
    end
end

tmp=readline()
#println("Input: ",split(tmp))
T=parse(Int128,tmp)
let i=1
    while i<=T
        tmp=readline()
        N=parse(Int128,tmp)
        tmp=readline()
        A=parse.(Int128,split(tmp))
        tmp=readline()
        S=tmp
        #println("Input: $N, $A ,$S")
        #println(length(S))
        ans=calc(A,S)
        ans2=1#calc2(A,S)
        if ans==0 || ans2==0
            println(0)
        else
            println(1)
        end
        i += 1
    end
end

Score : 400 points

Problem Statement

There are two persons, numbered 0 and 1, and a variable x whose initial value is 0.
The two persons now play a game.
The game is played in N rounds. The following should be done in the i-th round (1 \leq i \leq N):

Person S_i does one of the following:

Replace x with x \oplus A_i, where \oplus represents bitwise XOR.

Do nothing.

Person 0 aims to have x=0 at the end of the game, while Person 1 aims to have x \neq 0 at the end of the game.

Determine whether x becomes 0 at the end of the game when the two persons play optimally.

Solve T test cases for each input file.

Constraints

1 \leq T \leq 100

1 \leq N \leq 200

1 \leq A_i \leq 10^{18}

S is a string of length N consisting of 0 and 1.

All numbers in input are integers.

Input

Input is given from Standard Input in the following format.
The first line is as follows:

T

Then, T test cases follow.
Each test case is given in the following format:

N
A_1 A_2 \cdots A_N
S

Output

For each test case, print a line containing 0 if x becomes 0 at the end of the game, and 1 otherwise.

Sample Input 1

3
2
1 2
10
2
1 1
10
6
2 3 4 5 6 7
111000

Sample Output 1

1
0
0

In the first test case, if Person 1 replaces x with 0 \oplus 1=1, we surely have x \neq 0 at the end of the game, regardless of the choice of Person 0.

In the second test case, regardless of the choice of Person 1, Person 0 can make x=0 with a suitable choice.


# Q.1
function A01(x,y)
    if count_zeros(y) > count_zeros(x)
        x = y
    elseif count_zeros(y) == count_zeros(x)
        xor(x,A[])
    end
    x
end

function A02(x,y)
    if count_zeros(y) > count_zeros(x)
        x = y
    elseif count_zeros(y) == count_zeros(x)
        x = y
    end
    x
end

function A11(x,y)
    if count_zeros(y) < count_zeros(x)
        x = y
    elseif count_zeros(y) == count_zeros(x)
        x = x
    end
    x
end

function A12(x,y)
    if count_zeros(y) < count_zeros(x)
        x = y
    elseif count_zeros(y) == count_zeros(x)
        x = y
    end
    x
end

function calc(A,S)
    let j=1
        x = Int128(0)
        while j<=length(S)
            jun = parse(Int128,S[j])
            #println(jun)
            y = xor(x,A[j])
            #println(count_zeros(y)," vs ",count_zeros(x))
            if jun==0
                if count_zeros(y) > count_zeros(x)
                    x = y
                elseif count_zeros(y) == count_zeros(x)
                    if count_zeros(xor(x,A[j+1])) < count_zeros(xor(y,A[j+1]))
                        x = y
                    end
                end
#                x1 = A01(x,y)
#                x2 = A02(x,y)
            else
                if count_zeros(y) < count_zeros(x)
                    x = y
                elseif count_zeros(y) == count_zeros(x)
                    if count_zeros(xor(x,A[j+1])) > count_zeros(xor(y,A[j+1]))
                        x = y
                    end
                end
#                x1 = A11(x,y)
#                x2 = A12(x,y)
            end

            #println("j = $j, turn: $jun, Aâ±¼ = $(A[j]), x = $x")
            j += 1
        end
        #println("xans = ",x)
        if x==0
            #println(0)
            ans=0
        else
            #println(1)
            ans=1
        end
        ans
    end
end

function calc2(A,S)
    let j=1
        x = Int128(0)
        while j<=length(S)
            jun = parse(Int128,S[j])
            #println(jun)
            y = xor(x,A[j])
            #println(count_zeros(y)," vs ",count_zeros(x))
            if jun==0
                if count_zeros(y) >= count_zeros(x)
                    x = y
                end
            else
                if count_zeros(y) <= count_zeros(x)
                    x = y
                end
            end
            #println("j = $j, turn: $jun, Aâ±¼ = $(A[j]), x = $x")
            j += 1
        end
        #println("xans = ",x)
        if x==0
            #println(0)
            ans=0
        else
            #println(1)
            ans=1
        end
        ans
    end
end

tmp=readline()
#println("Input: ",split(tmp))
T=parse(Int128,tmp)
let i=1
    while i<=T
        tmp=readline()
        N=parse(Int128,tmp)
        tmp=readline()
        A=parse.(Int128,split(tmp))
        tmp=readline()
        S=tmp
        #println("Input: $N, $A ,$S")
        #println(length(S))
        ans=calc(A,S)
        ans2=1#calc2(A,S)
        if ans==0 || ans2==0
            println(0)
        else
            println(1)
        end
        i += 1
    end
end


#=
NOMURA atcoder 20200530 as an exercise.
=#

# Q.2
tmp=readline()
#println("Input: ",split(tmp))
T=parse(Int128,tmp)
let i=1
    while i<=T
        tmp=readline()
        N=parse(Int128,tmp)
        tmp=readline()
        A=parse.(Int128,split(tmp))
        tmp=readline()
        S=tmp
        #println("Input: $N, $A ,$S")
        #println(length(S))
        let j=1
            x = Int128(0)
            while j<=length(S)
                jun = parse(Int128,S[j])
                #println(jun)
                y = xor(x,A[j])
                if jun==0
                    if count_zeros(y) > count_zeros(x)
                        x = y
                    end
                else
                    if count_zeros(y) < count_zeros(x)
                        x = y
                    end
                end
                #println("j = $j, turn: $jun, x = $x")
                #println(count_zeros(y)," vs ",count_zeros(x))
                j += 1
            end
            #println("xans = ",x)
            if x==0
                println(0)
            else
                println(1)
            end
        end
        i += 1
    end
end
exit()


a, b = parse.(Int, split(readline()))

print(a * b)

Score : 100 points

Problem Statement

Compute A \times B.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the value A \times B as an integer.

Sample Input 1

2 5

Sample Output 1

10

We have 2 \times 5 = 10.

Sample Input 2

100 100

Sample Output 2

10000


using Primes
function divide(n)
    ans = 0
    temp = n
    for m in 1:n
        temp -= m
        temp < 0 && break
        ans += 1
    end
    return ans
end
function DivGame()
    N = parse(Int, readline())
    data = [c.second for c in collect(factor(N))]
    return println(sum(divide.(data)))
end
DivGame()

Score : 400 points

Problem Statement

Given is a positive integer N. Consider repeatedly applying the operation below on N:

First, choose a positive integer z satisfying all of the conditions below:

z can be represented as z=p^e, where p is a prime number and e is a positive integer;

z divides N;

z is different from all integers chosen in previous operations.

Then, replace N with N/z.

Find the maximum number of times the operation can be applied.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum number of times the operation can be applied.

Sample Input 1

24

Sample Output 1

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=12.)

Choose z=3 (=3^1). (Now we have N=4.)

Choose z=4 (=2^2). (Now we have N=1.)

Sample Input 2

1

Sample Output 2

0

We cannot apply the operation at all.

Sample Input 3

64

Sample Output 3

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=32.)

Choose z=4 (=2^2). (Now we have N=8.)

Choose z=8 (=2^3). (Now we have N=1.)

Sample Input 4

1000000007

Sample Output 4

1

We can apply the operation once by, for example, making the following choice:

z=1000000007 (=1000000007^1). (Now we have N=1.)

Sample Input 5

997764507000

Sample Output 5

7


MAXP = 10^6
f = [i for i in 1:MAXP]
p = []
for i in 2:MAXP
  MAXP < i^2 && break
  if f[i] == i
    push!(p, i)
    j = 2i
    while j <= MAXP
      f[j] == j && (f[j] = i)
      j += i
    end
  end
end

function factor(n)
  fs = Dict{Int64, Int}()
  for pi in p
    n <= MAXP && break
    while n % pi == 0
      !haskey(fs, pi) && (fs[pi] = 0)
      fs[pi] += 1
      n ÷= pi
    end
  end
  MAXP < n && (fs[n] = 1; n = 1)
  while 1 < n
    !haskey(fs, f[n]) && (fs[f[n]] = 0)
    fs[f[n]] += 1
    n ÷= f[n]
  end
  return fs
end

function s(n)
  s = 0
  for v in values(factor(n))
    i = 1
    k = 0
    while k + i <= v
      s += 1
      k += i
      i += 1
    end
  end
  return s
end

n = parse(Int64, readline())
println(s(n))


const double = Float64
const int = Int64

parseint(x) = parse(int, x)
readint() = map(parseint, split(readline()))

function main()
  n = readint()[1]
  A = Vector{int}(undef,n)
  B = Vector{int}(undef,n)

  for i in 1:n
    A[i], B[i] = readint()
  end

  sort!(A)
  sort!(B)

  if n%2 == 1
    println(B[n÷2 + 1] - A[n÷2 + 1] + 1)
  else
    println(B[n÷2] + B[n÷2 + 1] - A[n÷2] - A[n÷2 + 1]+1)
  end
  #println()
end

main()

Score : 500 points

Problem Statement

There are N integers X_1, X_2, \cdots, X_N, and we know that A_i \leq X_i \leq B_i.
Find the number of different values that the median of X_1, X_2, \cdots, X_N can take.

Notes

The median of X_1, X_2, \cdots, X_N is defined as follows. Let x_1, x_2, \cdots, x_N be the result of sorting X_1, X_2, \cdots, X_N in ascending order.

If N is odd, the median is x_{(N+1)/2};

if N is even, the median is (x_{N/2} + x_{N/2+1}) / 2.

Constraints

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

1 \leq A_i \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the answer.

Sample Input 1

2
1 2
2 3

Sample Output 1

3

If X_1 = 1 and X_2 = 2, the median is \frac{3}{2};

if X_1 = 1 and X_2 = 3, the median is 2;

if X_1 = 2 and X_2 = 2, the median is 2;

if X_1 = 2 and X_2 = 3, the median is \frac{5}{2}.

Thus, the median can take three values: \frac{3}{2}, 2, and \frac{5}{2}.

Sample Input 2

3
100 100
10 10000
1 1000000000

Sample Output 2

9991


function main()
    h1, m1, h2, m2, k = parse.(Int, split(readline()))

    t1 = h1 * 60 + m1
    t2 = h2 * 60 + m2
    tot = t2 - t1 - k
    println(Int(tot))

end

main()

Score : 100 points

Problem Statement

In this problem, we use the 24-hour clock.

Takahashi gets up exactly at the time H_1 : M_1 and goes to bed exactly at the time H_2 : M_2. (See Sample Inputs below for clarity.)
He has decided to study for K consecutive minutes while he is up.
What is the length of the period in which he can start studying?

Constraints

0 \le H_1, H_2 \le 23

0 \le M_1, M_2 \le 59

The time H_1 : M_1 comes before the time H_2 : M_2.

K \ge 1

Takahashi is up for at least K minutes.

All values in input are integers (without leading zeros).

Input

Input is given from Standard Input in the following format:

H_1 M_1 H_2 M_2 K

Output

Print the length of the period in which he can start studying, as an integer.

Sample Input 1

10 0 15 0 30

Sample Output 1

270

Takahashi gets up at exactly ten in the morning and goes to bed at exactly three in the afternoon.
It takes 30 minutes to do the study, so he can start it in the period between ten o'clock and half-past two. The length of this period is 270 minutes, so we should print 270.

Sample Input 2

10 0 12 0 120

Sample Output 2

0

Takahashi gets up at exactly ten in the morning and goes to bed at exactly noon. It takes 120 minutes to do the study, so he has to start it at exactly ten o'clock. Thus, we should print 0.


function main()
    h1, m1, h2, m2, k = parse.(Int, split(readline()))

    tot = 0
    if h1 == h2
        tot += (m2 - m1)
    else
        if m1 != 0
            tot += 60 - m1
        end
        tot += (h2 - h1) * 60
        tot += m2
    end

    tot -= k
    if tot < 0
        tot = 0
    end

    println(Int(tot))

end

main()


parseInt(x) = parse(Int, x)
parseBigInt(x) = parse(BigInt, x)
parseFloat(x) = parse(Float64, x)
parseBigFloat(x) = parse(BigFloat, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
    h1,m1,h2,m2,k=parseMap(split(readline()))
    start=h1*60+m1
    e=h2*60+m2
    if e-start>=k
        print(e-start-k)
    else
        print(0)
    end
end
main()