# %% 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
    Xcaches = [Dict{UInt,Int}() for _ in XYPs]
    Ycaches = [Dict{UInt,Int}() for _ in XYPs]

    bruteforcesearch(N, 2) do roads
        Xs = Set(0)
        Ys = Set(0)
        for (road, XYP) in zip(roads, XYPs)
            if road == 1
                push!(Xs, XYP[1])
            else
                push!(Ys, XYP[2])
            end
        end

        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, XYP) in zip(roads, XYPs)
            if road == 1
                push!(Xs, XYP[1])
                1
            elseif road == 2
                push!(Ys, XYP[2])
                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 |> minimum

    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, Xs)
    end
end

function cache_distance!(cache, p, ps)
    k = hash(ps)
    haskey(cache, k) || (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

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

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.


using DataStructures
const double = Float64
const int = Int64

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

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

  X = Vector{int}(undef,N)
  Y = Vector{int}(undef,N)
  P = Vector{int}(undef,N)
  for i in 1:N
    X[i],Y[i],P[i] = readint()
  end

  kai = Vector{int}(undef,N+1)
  kai .= typemax(int)

  xmin = Vector{int}(undef,N)
  ymin = Vector{int}(undef,N)
  sasi = Vector{Bool}(undef,N)

  for i in 0:3^N-1
    a = i
    c = 0
    sum = 0
    sasi .= false
    for j in 1:N
      xmin[j] = abs(X[j])
      ymin[j] = abs(Y[j])
      if xmin[j] ==0 || ymin[j]==0
        sasi[j] = true
      end
    end

    for j in 1:N
      if a%3 == 1
        c += 1
        sasi[j]=true
        for k in 1:N
          sasi[k] && continue
          if X[k]==X[j]
            sasi[k] = true
            continue
          end
          xmin[k] = min(xmin[k],abs(X[k]-X[j]))
        end
      elseif a%3 == 2
        c += 1
        sasi[j]=true
        for k in 1:N
          sasi[k] && continue
          if Y[k]==Y[j]
            sasi[k] = true
            continue
          end
          ymin[k] = min(ymin[k],abs(Y[k]-Y[j]))
        end
      end
      a ÷= 3
    end

    sum = 0
    for j in 1:N
      sasi[j] && continue

      sum += min(xmin[j],ymin[j])*P[j]
    end
    kai[c+1] = min(kai[c+1],sum)
  end

  for i in 1:N+1
    println(kai[i])
  end

end

main()

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

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
  L,R,d = parseMap(split(readline()))
  count = 0
  for i in L:R
    if i%d ==0
      count+=1
    end
  end
  println("$count")
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


readints()=parse.(Int,split(readline()))
L,R,d=readints()

print(R÷d-(L-1)÷d)


function main()
    N = pread(Int)
    a = readvec(Int, N)
    c = 0
    for i in 1:2:N
        if isodd(a[i])
            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()

Score : 200 points

Problem Statement

We have N squares assigned the numbers 1,2,3,\ldots,N. Each square has an integer written on it, and the integer written on Square i is a_i.

How many squares i satisfy both of the following conditions?

The assigned number, i, is odd.

The written integer is odd.

Constraints

All values in input are integers.

1 \leq N, a_i \leq 100

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \cdots a_N

Output

Print the number of squares that satisfy both of the conditions.

Sample Input 1

5
1 3 4 5 7

Sample Output 1

2

Two squares, Square 1 and 5, satisfy both of the conditions.

For Square 2 and 4, the assigned numbers are not odd.

For Square 3, the written integer is not odd.

Sample Input 2

15
13 76 46 15 50 98 93 77 31 43 84 90 6 24 14

Sample Output 2

3


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
  N = parseInt(readline())
  a = parseMap(split(readline()))

  num = 0
  for i in 1:2:N
    if a[i] % 2 == 1
      num += 1
    end
    #println("$i")
  end

  println("$num")

#  if mod(a,1000) != 0
#    println(1000-mod(a,1000))
#  else
#    println(0)
#  end
end
main()


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

function main()
  n = readline() |> parseInt

  f = zeros(Int, 10000)

  for x in 1:100
    for y in 1:100
      for z in 1:100
        m = x*x + y*y + z*z + x*y + y*z + z*x
        m <= 10000 && (f[m] += 1)
      end
    end
  end
  println.(f[1:n])
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.


function main()
    n = parse(Int, readline())
    ans = Dict{Int, Int}()
    for x in 1:100
        for y in 1:100
            for z in 1:100
                ret = g(x,y,z)
                ret > n && break
                if haskey(ans, ret)
                    ans[ret] += 1
                else
                    ans[ret] = 1
                end
            end
        end
    end

    for i in 1:n
        if haskey(ans, i)
            println(ans[i])
        else
            println(0)
        end
    end
end

g(x,y,z) = x^2 + y^2 + z^2 + x*y + y*z + z*x

main()


readint()=parse.(Int,readline())
function check(n)
    Nmax=100
    ff=zeros(Int,n)
    for x in 1:Nmax,y in 1:Nmax,z in 1:Nmax
        s=x^2+y^2+z^2+x*y+y*z+z*x
        if s<=n
            ff[s]+=1
        end
    end
    for i in 1:n
        println(ff[i])
    end
end
check(readint())


function main()
    N = pread(Int)
    X = reverse(pread(String))
    pc = count(x -> x == '1', X)
    cp = parse(BigInt, reverse(X), base=2) % (pc + 1)

    ap = zeros(Int, N)
    am = zeros(Int, N)
    ap[1] = 1
    am[1] = 1

    for i in 2:N
        ap[i] = ap[i-1]<<1 % (pc+1)
    end
    cm = 0
    if (pc-1) != 0
        cm = parse(BigInt, reverse(X), base=2) % (pc - 1)
        for i in 2:N
            am[i] = am[i-1] << 1 % (pc-1)
        end
    end
    ans = zeros(Int,N)
    for i in 1:N
        c = (X[i]=='1' ? cm : cp)
        ppm = (pc + (X[i]=='1' ? -1 : 1))
        ppm == 0 && continue
        tmp = (ppm + c + (X[i]=='1' ? -am[i] : ap[i])) % ppm
        cc = 1
        while tmp != 0
            tmp = tmp % count_ones(tmp)
            cc += 1
        end
        ans[i] = cc
    end
    for i in N:-1:1
        println(ans[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()

Score : 400 points

Problem Statement

Let \mathrm{popcount}(n) be the number of 1s in the binary representation of n.
For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0.

Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n is divided by \mathrm{popcount}(n)." (It can be proved that, under the constraints of this problem, n always becomes 0 after a finite number of operations.)

For example, when n=7, it becomes 0 after two operations, as follows:

\mathrm{popcount}(7)=3, so we divide 7 by 3 and replace it with the remainder, 1.

\mathrm{popcount}(1)=1, so we divide 1 by 1 and replace it with the remainder, 0.

You are given an integer X with N digits in binary.
For each integer i such that 1 \leq i \leq N, let X_i be what X becomes when the i-th bit from the top is inverted.
Find f(X_1), f(X_2), \ldots, f(X_N).

Constraints

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

X is an integer with N digits in binary, possibly with leading zeros.

Input

Input is given from Standard Input in the following format:

N
X

Output

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

Sample Input 1

3
011

Sample Output 1

2
1
1

X_1 = 7, which will change as follows: 7 \rightarrow 1 \rightarrow 0. Thus, f(7) = 2.

X_2 = 1, which will change as follows: 1 \rightarrow 0. Thus, f(1) = 1.

X_3 = 2, which will change as follows: 2 \rightarrow 0. Thus, f(2) = 1.

Sample Input 2

23
00110111001011011001110

Sample Output 2

2
1
2
2
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
1
3


function main()
    N = pread(Int)
    X = reverse(pread(String))
    pc = count(x -> x == '1', X)
    cp = parse(Int, X[min(32,N):-1:1], base=2) % (pc + 1)
    for i in 33:32:N
        cp += parse(Int, X[min(i+31,N):-1:i], base=2) << 32 % (pc + 1)
        cp %= (pc + 1)
    end
    ap = zeros(Int, N)
    am = zeros(Int, N)
    ap[1] = 1
    am[1] = 1
    for i in 2:N
        ap[i] = ap[i-1]<<1 % (pc+1)
    end
    cm = 0
    if (pc-1) != 0
        cm = parse(Int, X[min(32,N):-1:1], base=2) % (pc - 1)
        for i in 33:32:N
            cm += parse(Int, X[min(i+31,N):-1:i], base=2) << 32 % (pc - 1)
            cm %= (pc - 1)
        end
        for i in 2:N
            am[i] = am[i-1]<<1 % (pc-1)
        end
    end
    ans = zeros(Int,N)
    for i in 1:N
        c = (X[i]=='1' ? cm : cp)
        ppm = (pc + (X[i]=='1' ? -1 : 1))
        if ppm == 0
            push!(ans, 0)
            continue
        end
        tmp = (ppm + c + (X[i]=='1' ? -am[i] : ap[i])) % ppm
        cc = 1
        while tmp != 0
            tmp = tmp % count_ones(tmp)
            cc += 1
        end
        ans[i] = cc
    end
    for i in N:-1:1
        println(ans[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()


readint()=parse.(Int,readline())
N=readint()
S=readline()
popcount(n)=sum(digits(n,base=2))
function f(n)
    s=0
    while n!=0
        n%=popcount(n)
        s+=1
    end
    s
end
function bitRev(X,N,i)
    if (X >> (N-i) & 1)==1
        X-=2^(N-i)
    else
        X+=2^(N-i)
    end
    X
end
#X=parse(Int,S,base=2)
Ss=split(S,"")
function bit2Int(N,Ss)
  X=0
	for i in 1:N
   		Ss[i]=="1" && (X+=big(2)^(N-i))
	end
  X
end
X=bit2Int(N,Ss)
for i in 1:N
    println(f(bitRev(X,N,i)))
end


function main()
    N = pread(Int)
    x = parse(Int, pread(String), base=2)
    for i in 1:N
        a = xor(x, 1<<(N-i))
        tmp = Int(a % count_ones(a))
        c = 1
        while tmp != 0
            tmp = tmp % count_ones(tmp)
            c += 1
        end
        println(c)
    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 = parse(Int, readline())

  dict = Dict("AC" => 0, "WA" => 0, "TLE" => 0, "RE" => 0)

  for i in 1:N
    S = chomp(readline())
    dict[S] = get(dict, S, 0) + 1
  end

  for i in ["AC", "WA", "TLE", "RE"]
    println(i, " x ", dict[i])
  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


function main()
    n = parse(Int, readline())
    ans = zeros(Int, 4)
    for i in 1:n
        s = readline()
        s == "AC" && (ans[1] += 1)
        s == "WA" && (ans[2] += 1)
        s == "TLE" && (ans[3] += 1)
        s == "RE" && (ans[4] += 1)
    end

    println("AC x ", ans[1])
    println("WA x ", ans[2])
    println("TLE x ", ans[3])
    println("RE x ", ans[4])

end

main()


using DataStructures
const double = Float64
const int = Int64

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

function main()
  N = readint()[1]
  S = ["AC", "WA", "TLE", "RE"]
  d = Dict{String,int}()
  for moji in S
    get!(d,moji,0)
  end
  for _ in 1:N
    s = readline()
    #get!(d,s,0)
    d[s]+=1
  end

  for moji in S
    println(moji," x ",d[moji])
  end

end

main()


function main()
  h, w, k = parse.(Int, split(readline()))

  c = String[]
  for i in 1:h
    push!(c, readline())
  end

  ans = 0
  for i in 0:2^(h+w)-1
    cnt = 0
    for x in 1:h
      for y in 1:w
#        println(i >> (x-1), i >> (y+h-1))
        if (i >> (x-1) ) % 2 == 0 || (i >> (y+h-1)) % 2 == 0
          continue
        elseif c[x][y] == '#'
          cnt += 1
        end
      end
    end

    if k == cnt
      ans += 1
    end
  end

  println(ans)
end

main()

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


using DataStructures

function main()
    n = parse(Int, readline())
    a = parse.(Int, split(readline()))
    p = sortperm(a, rev=true)

    ans = 0
    arrived = [p[1]]
    pq = PriorityQueue{Tuple{Int, Int}, Int}(Base.Order.Reverse)
    pq[(1, 1)] = a[p[1]]

    for i in 2:length(p)
        ans += peek(pq)[2]
        loc = peek(pq)[1]
        ll = minimum(loc)
        gl = maximum(loc)
        insert!(arrived, gl, p[i])

        nl = gl
        gl += 1
        dequeue!(pq)
        pq[(ll, nl)] = min(a[arrived[ll]], a[arrived[nl]])
        pq[(nl, gl)] = min(a[arrived[nl]], a[arrived[gl]])
    end
    println(ans)
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


if isfile("mystdin.txt");mystdin=open("mystdin.txt","r");redirect_stdin(mystdin);end
pI(x)=parse(Int,x)
pM(x::Array{SubString{String},1})=map(pI,x)
function main()
  n=pI(readline())
  a=pM(split(readline()))
  println(sum(a)-minimum(a))
end
main()
if isdefined(Base, :mystdin);close(mystdin);end


using DataStructures
const double = Float64
const int = Int64

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

const MOD = 10^9+7
function main()
  N,K = readint()
  A = readint()
  sort!(A)

  # 負, 0, 正の区間
  # searchsorted が基本ですね
  L0 = searchsorted(A,0)
  Lm = 1:(L0.start-1)
  Lp = (L0.stop + 1):N

  # 負、0, 正の数
  Nm = length(Lm)
  N0 = length(L0)
  Np = length(Lp)

  if N0 > N-K
    println(0)
    return
  end

  if K == N
    s = 1
    for a in A
      s *= a
      s %= MOD
    end
    if s < 0
      s += MOD
    end
    println(s)
    return
  end

  if L0.stop == N
    s = 1
    if K%2 == 1
      for i in N:-1:N-K+1
        s *= A[i]
        s %= MOD

      end
      if s < 0
        s += MOD
      end
    else
      for i in 1:K
        s *= A[i]
        s %= MOD
      end
    end

  else
    s = 1
    if K%2 == 1
      s *= A[end]
    end
    B = Vector{int}(undef,N)
    B .= 0

    Nm = L0.stop
    NPm = Nm÷2
    for i in 1:NPm
      B[i] = A[2i-1]*A[2i]
    end

    p = NPm + 1
    if K%2==1
      for i in N-1:-2:Nm+2
        B[p] = A[i]*A[i-1]
        p += 1
      end
    else
      for i in N:-2:Nm+2
        B[p] = A[i]*A[i-1]
        p += 1
      end
    end

    sort!(B,rev=true)
    #println(B)
    for i in 1:K÷2
      s *= B[i]%MOD
      s %= MOD
    end

  end
  println(s)

end

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


using DataStructures
const double = Float64
const int = Int64

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

const MOD = 10^9+7
function main()
  N,K = readint()
  A = readint()
  sort!(A)
  lr0 = searchsorted(A,0)

  if length(lr0) > N-K
    println(0)
    return
  end

  if N == K
    s = 1
    for a in A
      s *= a
      s %= MOD
    end
    if s < 0
      s += MOD
    end
    println(s)
    return
  end

  s = 1
  if lr0.stop == N
    if K%2 == 1
      for i in N:-1:N-K+1
        s *= A[i]
        s %= MOD

      end
      s += MOD
    else
      for i in 1:K
        s *= A[i]
        s %= MOD
      end
    end

  else
    if K%2 == 1
      s *= A[end]
    end
    B = Vector{int}(undef,2N)

    Nm = lr0.stop
    NPm = Nm÷2
    for i in 1:NPm
      B[i] = A[2i-1]*A[2i]
    end

    p = NPm + 1
    if K%2==1
      for i in N-1:-2:Nm+1
        B[p] = A[i]*A[i-1]
        p += 1
      end
    else
      for i in N:-2:Nm+1
        B[p] = A[i]*A[i-1]
        p += 1
      end
    end

    sort!(B,rev=true)
    #println(B)
    for i in 1:K÷2
      s *= B[i]%MOD
      s %= MOD
    end

  end
  println(s)

end

main()


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

function main()
	d = readline() |> parseInt
	for i in 1:d
		println(1)
	end
end

main()

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

Beginner's Guide

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

Problem Statement

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

Input

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

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

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

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

Output

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

v_1
v_2
\vdots
v_D

Sample Input 1

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

Sample Output 1

18398
35037
51140
65837
79325

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

Next Step

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

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


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

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

main()

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


s=parse(Int,readline())
function solve(s)
print(s+s^2+s^3)
end
solve(s)


function main()
    S = readline()
    T = readline()
    min = 0
    for i in 1:length(S)
         if S[i] != T[i]
             min +=1
         end
    end
    println(min)
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.


a = readline()[1]

if a >= 'a' && a <= 'z'
  print('a')
else
  print('A')
end

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.


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

sort!(a)
c = 0
for i in 1:k
  global c
  c = c + a[i]
end
print(c)

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


function main()
  n=parse(Int,readline())
  ans=""
  while n!=0
    n-=1
    n,r=divrem(n,26)
    ans*='a'+r
  end
  println(ans[end:-1:1])
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


using DataStructures
parseline(str) = parse.(Int, split(str))
function Replacing()
    data = readlines()
    N = parse(Int, data[1])
    A = parseline(data[2])
    nums = zeros(Int, 10^5)
    for a in A
        nums[a] += 1
    end
    Q = parse(Int, data[3])
    BC = parseline.(data[4:end])
    ans = sum(A)
    ansStr = ""
    for bc in BC
        nums[bc[1]] == 0 && continue
        ans += (bc[2] - bc[1]) * nums[bc[1]]
        nums[bc[2]] += nums[bc[1]]
        nums[bc[1]] = 0
        ansStr *= "$ans\n"
    end
    println(ansStr)
end
Replacing()

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


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

function main()
N = readline()
A = parseMap(split(readline()))
Q = parseInt(readline())

D = Dict{Int, Int}()

before_sum = sum(A)
for a in A
    if a in keys(D)
        D[a] += 1
    else
        D[a] = 1
    end
end

for _ in 1:Q
    B, C = parseMap(split(readline()))
    if B in keys(D)
        before_sum += D[B] * (C - B)
    else
        println(before_sum)
        continue
    end
    if C in keys(D)
        D[C] += D[B]
    else
        D[C] = D[B]
    end
    D[B] = 0
    println(before_sum)
end
end

main()


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

Axor=xor(A...)
for i in 1:N
    Aixor=xor(Axor,A[i])
    print(Aixor)
    print(" ")
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.


const double = Float64
const int = Int64

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

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

  b = Array{int,2}(undef,32,N)
  oe = Vector{int}(undef,32)
  oe .= 0
  for i in 1:N
    for j in 1:32
      k = A[i]
      b[j,i] = k >> (j-1) &1
      if i > 2
        oe[j] += b[j,i]
      end
    end
  end

  r = Array{int,2}(undef,32,N)
  r .= 0

  for i in 1:32
    # odd or even
    oe[i] = oe[i] %2

    if b[i,1]%2 == 0
      if b[i,2]%2 == 0
        if oe[i] == 1
          r[i,1] = 1
          r[i,2] = 1
        else
          r[i,1] = 0
          r[i,2] = 0
        end
      else
        if oe[i] == 1
          r[i,1] = 0
          r[i,2] = 1
        else
          r[i,1] = 1
          r[i,2] = 0
        end
      end
    else
      if b[i,2]%2 == 0
        if oe[i] == 1
          r[i,1] = 1
          r[i,2] = 0
        else
          r[i,1] = 0
          r[i,2] = 1
        end
      else
        if oe[i] == 1
          r[i,1] = 0
          r[i,2] = 0
        else
          r[i,1] = 1
          r[i,2] = 1
        end
      end
    end
  end

    for i in 2:N-1
      for j in 1:32
        if b[j,i] == b[j,i+1]
          r[j,i+1] = r[j,i]
        else
          if r[j,i]==0
            r[j,i+1] = 1
          else
            r[j,i+1] = 0
          end
        end
      end
    end

    for i in 1:N
      s = 0
      for j in 1:32
        s += r[j,i]*(2^(j-1))
      end
      println(s)
    end

  end

main()


using DataStructures
const double = Float64
const int = Int64

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

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

  s = 0
  c = 0
  while true
    c += 1
    s += N
    s %= 360
    if s == 0
      println(c)
      break
    end
  end

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


using DataStructures
const double = Float64
const int = Int64

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

MOD = 998244353
function main()
  A,B,C,D = readint()

  s0 = Array{int,2}(undef,C,D)
  s1 = Array{int,2}(undef,C,D)

  s0[A,B] = 1
  s1[A,B] = 0

  for i in A+1:C
    s0[i,B] = (s0[i-1,B]+s1[i-1,B])* B%MOD
    s1[i,B] = 0
  end

  for i in B+1:D
    s0[A,i] = 0
    s1[A,i] = (s0[A,i-1] + s1[A,i-1])*A%MOD
  end

  for j in B+1:D,i in A+1:C
    s0[i,j] = (s0[i-1,j]+s1[i-1,j])*j%MOD
    s1[i,j] = (s0[i,j-1]+s1[i,j-1]*i)%MOD

  end

  println((s0[C,D]+s1[C,D])%MOD)

end

main()

Score : 600 points

Problem Statement

We have a grid with A horizontal rows and B vertical columns, with the squares painted white. On this grid, we will repeatedly apply the following operation:

Assume that the grid currently has a horizontal rows and b vertical columns. Choose "vertical" or "horizontal".

If we choose "vertical", insert one row at the top of the grid, resulting in an (a+1) \times b grid.

If we choose "horizontal", insert one column at the right end of the grid, resulting in an a \times (b+1) grid.

Then, paint one of the added squares black, and the other squares white.

Assume the grid eventually has C horizontal rows and D vertical columns. Find the number of ways in which the squares can be painted in the end, modulo 998244353.

Constraints

1 \leq A \leq C \leq 3000

1 \leq B \leq D \leq 3000

A, B, C, and D are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of ways in which the squares can be painted in the end, modulo 998244353.

Sample Input 1

1 1 2 2

Sample Output 1

3

Any two of the three squares other than the bottom-left square can be painted black.

Sample Input 2

2 1 3 4

Sample Output 2

65

Sample Input 3

31 41 59 265

Sample Output 3

387222020


# SPDX-License-Identifier: X11
# 2020-08-29
# Five Variables (100pt)

println(findfirst(x -> x == 0, parse.(Int, split(readline(), " "))))

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


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 X == 0 && Y == 0
      println("Yes")
      exit()
  end
  if Y < 2*X || Y > 4*X
      println("No")
      exit()
  end
  if Y % 2 != 0
      println("No")
      exit()
  end
  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")
      elseif y0==0 && x0 > 0
        println("Yes")

      else
        println("No")
      end
    end
  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.


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

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

  z = (4x-y)÷2
  w = (4x-y)%2
  if w==0 && z>=0 && z<=x
    println("Yes")
  else
    println("No")
  end
end

main()


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

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

  if (4x-y)%2==0
    println("Yes")
  else
    println("No")
  end
end

main()


function main()
	X,N=map(x->parse(Int,x),split(readline()))
	A=map(x->parse(Int,x),split(readline()))
	function f(T)
		for i=1:N
			if A[i]==T
				return true
			end
		end
		return false
	end
	for k=0:114514
		if !f(X-k)
			println(X-k)
			exit()
		elseif !f(X+k)
			println(X+k)
			exit()
		end
	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.


readstr() = split(readline())
readnum(T::Type{<:Number} = Int) = parse.(T, split(readline()))
let
  X, N = readnum()
  p = readnum()
  X ∉ p && (println(X); exit())
  tmp = 0
  for ans = 0:101
    ans ∈ p && continue
    if X - ans > 0
      tmp = X - ans
    else
      if ans - X < tmp
        println(ans)
        break
      else
        println(X - tmp)
        break
      end
    end
  end
end


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

function main()

X, N = parseMap(split(readline()))

if N != 0
    P = parseMap(split(readline()))
    for e in 0:100
        x = X - e
        if !(x in P)
            println(x)
            break
        end
        x2 = X + e
    if !(x2 in P)
        println(x2)
        break
    end
    end
else
    println(X)
end

end

main()


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 && (D_d % D_v)==0
    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


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

function solve(N, K, A)
    for _ in 1:K
        tmp = zeros(Int64, N)

        for i in 1:N
            to = maximum([1, i - A[i]])
            en = minimum([N, i + A[i]])
            tmp[to:en] .+= 1
        end
    if A == tmp
        return A
    else
        A = tmp
    end
    end
    return A
end

function print_ans(A)
    for a in A
        print(a, " ")
    end
    println()
end

function main()

N, K = parseMap(split(readline()))

A = parseMap(split(readline()))

if N * K < 10 ^ 6
    print_ans(solve(N, K ,A))
elseif K >= N
    print_ans(fill(N, N))
else
    print_ans(solve(N, 200, A))
end

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


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

function bsearch(a::Array{Tuple{Int,Int},1},x)
	l,r = 0, length(a)+1
	while r-l>1
		m = (l+r)>>1
		if a[m][1]<=x
			l = m
		else
			r = m
		end
	end
	return(l)
end

function main()
	n = readline() |> parseInt
	a = Tuple{Int,Int}[(0,0) for i in 1:n]
	for i in 1:n
		v,w = readline() |> split |> parseMap
		a[i] = (v,w)
	end
	dps = [Dict{Int,Int}() for i in 1:n>>1]
	dps[1][0]=0
	dps[1][a[1][2]]=a[1][1]
	for iter in 2:n>>1
		v = iter
		dp = copy(dps[v>>1])
		(p,q)=a[v]
		for j in keys(dps[v>>1])
			if haskey(dp,j+q)
				dp[j+q]=max(dp[v>>1][j+q],dps[v>>1][j]+p)
			else
				dp[j+q]=dps[v>>1][j]+p
			end
		end
		dps[v] = copy(dp)
	end
	dpt = [Tuple{Int,Int}[] for i in 1:n>>1]
	for i in 1:n>>1
		y = Tuple{Int,Int}[(j,dps[i][j]) for j in keys(dps[i])]
		y = sort(y,by=x->x[1])
		z = Tuple{Int,Int}[]
		push!(z,y[1])
		for j in 2:length(y)
			push!(z,(y[j][1],max(y[j][2],z[j-1][2])))
		end
		dpt[i]=copy(z)
	end
	q = readline() |> parseInt
	for iter in 1:q
		v,l = readline() |> split |> parseMap
		dp = Dict{Int,Int}()
		dp[0]=0
		while v>n>>1
			(p,q) = a[v]
			tmp = copy(dp)
			tmp[0]=0
			for j in keys(dp)
				if j+q<=l
					if haskey(dp,j+q)
						tmp[j+q]=max(dp[j+q],dp[j]+p)
					else
						tmp[j+q]=dp[j]+p
					end
				end
			end
			dp = copy(tmp)
			v>>=1
		end
		mx = 0
		for j in keys(dp)
			k = bsearch(dpt[v],l-j)
			if k>0
				mx = max(mx,dp[j]+dpt[v][k][2])
			else
				mx = max(mx,dp[j])
			end
		end
		println(mx)
	end
end

main()

Score : 700 points

Problem Statement

We have a rooted binary tree with N vertices, where the vertices are numbered 1 to N.
Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex \left[ \frac{i}{2} \right].

Each vertex has one item in it. The item in Vertex i has a value of V_i and a weight of W_i.
Now, process the following query Q times:

Given are a vertex v of the tree and a positive integer L.
Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L.
Find the maximum possible total value of the chosen items.

Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k (k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i.

Constraints

All values in input are integers.

1 \leq N < 2^{18}

1 \leq Q \leq 10^5

1 \leq V_i \leq 10^5

1 \leq W_i \leq 10^5

For the values v and L given in each query, 1 \leq v \leq N and 1 \leq L \leq 10^5.

Input

Let v_i and L_i be the values v and L given in the i-th query.
Then, Input is given from Standard Input in the following format:

N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q

Output

For each integer i from 1 through Q,
the i-th line should contain the response to the i-th query.

Sample Input 1

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

Sample Output 1

0
3
3

In the first query, we are given only one choice: the item with (V, W)=(1,2). Since L = 1, we cannot actually choose it, so our response should be 0.

In the second query, we are given two choices: the items with (V, W)=(1,2) and (V, W)=(2,3). Since L = 5, we can choose both of them, so our response should be 3.

Sample Input 2

15
123 119
129 120
132 112
126 109
118 103
115 109
102 100
130 120
105 105
132 115
104 102
107 107
127 116
121 104
121 115
8
8 234
9 244
10 226
11 227
12 240
13 237
14 206
15 227

Sample Output 2

256
255
250
247
255
259
223
253


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

function main()
	n = readline() |> parseInt
	a = Tuple{Int,Int}[(0,0) for i in 1:n]
	for i in 1:n
		v,w = readline() |> split |> parseMap
		a[i] = (v,w)
	end
	q = readline() |> parseInt
	for iter in 1:q
		v,l = readline() |> split |> parseMap
		dp = Dict{Int,Int}()
		dp[0]=0
		while v>0
			(p,q) = a[v]
			tmp = copy(dp)
			tmp[0]=0
			for j in keys(dp)
				if j+q<=l
					if haskey(dp,j+q)
						tmp[j+q]=max(dp[j+q],dp[j]+p)
					else
						tmp[j+q]=dp[j]+p
					end
				end
			end
			dp = copy(tmp)
			v>>=1
		end
		println(maximum(values(dp)))
	end
end

main()


function solve()
  n=parse(Int,readline())
  as=map(x->parse(Int,x),split(readline()))
  s=readline()
  t=Int[]
  ok=false
  for i=n:-1:1
    a=as[i]
    for b=t
      a=min(a,xor(a,b))
    end
    if a!=0
      if s[i]=='1'
        ok=true
      else
        push!(t,a)
      end
    end
  end
  println(ok ? 1 : 0)
end
t=parse(Int,readline())
for _=1:t
  solve()
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(Int64,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 = Int64(0)
        while j<=length(S)
            jun = parse(Int64,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(Int64,tmp)
        tmp=readline()
        A=parse.(Int64,split(tmp))
        tmp=readline()
        S=tmp
        #println("Input: $N, $A ,$S")
        #println(length(S))
        if S[N]=="1"
            println(1)
            continue
        end
        ans=calc(A,S)
        ans2=1#calc2(A,S)
        if ans==0 || ans2==0
            println(0)
        else
            println(1)
        end
        i += 1
    end
end


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

A, B = parseMap(split(readline()))

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


if isfile("mystdin.txt");mystdin=open("mystdin.txt","r");redirect_stdin(mystdin);end
pI(x)=parse(Int,x)
pM(x::Array{SubString{String},1})=map(pI,x)
function main()
  a,b=pM(split(readline()))
  print(*(a,b))
end
main()
if isdefined(Base, :mystdin);close(mystdin);end


import Base.parse
import Base.StringVector

parse(::Type{String},  str::AbstractString) = str

isdelim(x::UInt8, xs::Set{UInt8}) = x in xs

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

delimset = Set([0x0a, 0x20])

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)

readvec(tys::Tuple , len::Signed)::Vector{Tuple{tys...}} = @inbounds Tuple{tys...}[reads(tys...) for i in 1:len]

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 = 1:s[1]
        v[i,:] = readvec(ty, s[2])
    end
    v
end

function main()
    a,b = reads(Int,Int)
    println(a*b)
end

main()


using Primes: factor
using DataStructures: SortedDict
function main()
    n = parse(Int,readline())
    sa = factor(SortedDict, n)
    ret = 0
    for p in sa
        ni = p |> last
        for del in 1:10
            if ni >= del
                ni -= del
                ret += 1
            end
        end
    end
    println(ret)
end
main()

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


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)
using Primes

function main()
    n::Int=parseInt(readline())
    sq::Int=trunc(Int,sqrt(n))
    arr::Vector{Int}=Vector{Int}()
    sosu::Vector{Bool}=[true for i in 1:10^6]
    sosu[1]=false
    for i in 3:10^6
        res=true
        for j in 2:trunc(Int,sqrt(i))+1
            if i%j==0
                res=false
                break
            end
        end
        sosu[i]=res
    end
    ans::Int=0
    for i in 2:10^6
        if !sosu[i]
            continue
        end
        res::Int128=i
        while n%res==0
            ans+=1
            n÷=res
            res*=i
        end
    end
    flag::Bool=true
    for i in 2:10^6
        if n%i==0
            flag=false
        end
    end
    if flag && n>1
        ans+=1
    end
    println(ans)
end
main()


import Base.parse
import Base.StringVector
using Primes
using DataStructures

parse(::Type{String},  str::AbstractString) = str

isdelim(x::UInt8, xs::Set{UInt8}) = x in xs

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

delimset = Set([0x0a, 0x20])

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)

readvec(tys::Tuple , len::Signed)::Vector{Tuple{tys...}} = @inbounds Tuple{tys...}[reads(tys...) for i in 1:len]

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 = 1:s[1]
        v[i,:] = readvec(ty, s[2])
    end
    v
end

function main()
    N = pread(Int)
    fs = factor(DataStructures.SortedDict, N)
    ans = 0
    for f in fs
        c = f[2]
        ans += (-1+sqrt(1+8c))÷2
    end
    println(Int(ans))
end

main()


function main()
	N=parse(Int,readline())
	A=Int[]
	B=Int[]
	for _=1:N
		a,b=map(x->parse(Int,x),split(readline()))
		push!(A,a)
		push!(B,b)
	end
	sort!(A)
	sort!(B)
	if N%2==1
		println(B[div(N+1,2)]-A[div(N+1,2)]+1)
	else
		println(B[div(N,2)]+B[div(N,2)+1]-A[div(N,2)]-A[div(N,2)+1]+1)
	end
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


const double = Float64
const int = Int128

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

function main(a::Int128)
  a = a*a

  N = readint()[1]
  A = readint()

  if A[0] && N==0
    println(-1)
    return
  end
  if A[1] == 1
    if N==0
      println(1)
      return
    else
      println(-1)
      return
    end
  end

  sum = 1
  parent = 1

  pmaxs = Vector{int}(undef,N+1)
  pmaxs[1] = 1

  for i in 2:N+1
    nmax = parent * 2
    if A[i] > nmax
      #println(pmaxs)
      println(-1)
      return
    end
    parent = min(nmax - A[i],a)
    pmaxs[i] = parent
  end

  #sum = 1
  sum = 1+ A[N+1]
  ch = A[N+1]
  for i in N:-1:2
    sum += A[i] + min(pmaxs[i],ch)
    ch = A[i] + min(pmaxs[i],ch)
  end

  println(sum)

end

a = Vector{Int128}(undef,1)
a[1] = 2^62
main(a[1])

Score : 600 points

Problem Statement

Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1.

Notes

A binary tree is a rooted tree such that each vertex has at most two direct children.

A leaf in a binary tree is a vertex with zero children.

The depth of a vertex v in a binary tree is the distance from the tree's root to v. (The root has the depth of 0.)

The depth of a binary tree is the maximum depth of a vertex in the tree.

Constraints

0 \leq N \leq 10^5

0 \leq A_i \leq 10^{8} (0 \leq i \leq N)

A_N \geq 1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0 A_1 A_2 \cdots A_N

Output

Print the answer as an integer.

Sample Input 1

3
0 1 1 2

Sample Output 1

7

Below is the tree with the maximum possible number of vertices. It has seven vertices, so we should print 7.

Sample Input 2

4
0 0 1 0 2

Sample Output 2

10

Sample Input 3

2
0 3 1

Sample Output 3

-1

Sample Input 4

1
1 1

Sample Output 4

-1

Sample Input 5

10
0 0 1 1 2 3 5 8 13 21 34

Sample Output 5

264


const double = Float64
const int = Int64

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

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

  if A[1] == 1
    if N==0
      println(1)
      return
    else
      println(-1)
      return
    end
  end

  sum = 1
  parent = 1

  pmaxs = Vector{int}(undef,N+1)
  pmaxs[1] = 1

  for i in 2:N+1
    nmax = parent * 2
    if A[i] > nmax
      #println(pmaxs)
      println(-1)
      return
    end
    parent = min(nmax - A[i], 10^17)
    pmaxs[i] = parent
  end

  #sum = 1
  sum = 1+ A[N+1]
  ch = A[N+1]
  for i in N:-1:2
    sum += A[i] + min(pmaxs[i],ch)
    ch = A[i] + min(pmaxs[i],ch)
  end

  println(sum)

end

main()


function solve()
    n = readline()
    if n[end] in ['2', '4', '5', '7', '9']
        "hon"
    elseif n[end] in ['0', '1', '6', '8']
        "pon"
    else
        "bon"
    end
end

println(solve())

Score: 100 points

Problem Statement

The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese.

When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "N 本" for a positive integer N not exceeding 999 is as follows:

hon when the digit in the one's place of N is 2, 4, 5, 7, or 9;

pon when the digit in the one's place of N is 0, 1, 6 or 8;

bon when the digit in the one's place of N is 3.

Given N, print the pronunciation of "本" in the phrase "N 本".

Constraints

N is a positive integer not exceeding 999.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

16

Sample Output 1

pon

The digit in the one's place of 16 is 6, so the "本" in "16 本" is pronounced pon.

Sample Input 2

2

Sample Output 2

hon

Sample Input 3

183

Sample Output 3

bon


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

N = parseInt(readline())

h = [2, 4, 5, 7, 9]
p = [0, 1, 6, 8]
b = [3]

n = N % 10

if n in h
    println("hon")
elseif n in p
    println("pon")
else
    println("bon")
end


K = parse(Int64, readline())
S = readline()

if K >= length(S)
    println(S)
else
    println(S[1:K] * "...")
end

Score: 200 points

Problem Statement

We have a string S consisting of lowercase English letters.

If the length of S is at most K, print S without change.

If the length of S exceeds K, extract the first K characters in S, append ... to the end of them, and print the result.

Constraints

K is an integer between 1 and 100 (inclusive).

S is a string consisting of lowercase English letters.

The length of S is between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

K
S

Output

Print a string as stated in Problem Statement.

Sample Input 1

7
nikoandsolstice

Sample Output 1

nikoand...

nikoandsolstice has a length of 15, which exceeds K=7.

We should extract the first 7 characters in this string, append ... to the end of them, and print the result nikoand....

Sample Input 2

40
ferelibenterhominesidquodvoluntcredunt

Sample Output 2

ferelibenterhominesidquodvoluntcredunt

The famous quote from Gaius Julius Caesar.


Score: 300 points

Problem Statement

Consider an analog clock whose hour and minute hands are A and B centimeters long, respectively.

An endpoint of the hour hand and an endpoint of the minute hand are fixed at the same point, around which each hand rotates clockwise at constant angular velocity. It takes the hour and minute hands 12 hours and 1 hour to make one full rotation, respectively.

At 0 o'clock, the two hands overlap each other. H hours and M minutes later, what is the distance in centimeters between the unfixed endpoints of the hands?

Constraints

All values in input are integers.

1 \leq A, B \leq 1000

0 \leq H \leq 11

0 \leq M \leq 59

Input

Input is given from Standard Input in the following format:

A B H M

Output

Print the answer without units. Your output will be accepted when its absolute or relative error from the correct value is at most 10^{-9}.

Sample Input 1

3 4 9 0

Sample Output 1

5.00000000000000000000

The two hands will be in the positions shown in the figure below, so the answer is 5 centimeters.

Sample Input 2

3 4 10 40

Sample Output 2

4.56425719433005567605

The two hands will be in the positions shown in the figure below. Note that each hand always rotates at constant angular velocity.


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

function main()
	a,b,h,m = readline() |> split |> parseMap
	hs = h/6+m/360
	ms = m/30
	println(sqrt((a*cos(hs*pi)-b*cos(ms*pi))^2+(a*sin(hs*pi)-b*sin(ms*pi))^2))
end

main()


function main()
    a, b, h, m = parse.(Int, split(readline()))

    t = 60*60*h + 60*m
    ta = t*2*pi/43200
    tb = m*2*pi/60
    theta = abs(ta-tb)
    ans = a^2 + b^2 - 2*a*b*cos(theta)
    ans = sqrt(ans)
    println(ans)
end

main()


parseline(str) = parse.(Int, split(str))
function DoubleDots()
    N, M = parseline(readline())
    graph = [Int[] for _ in 1:M]
    for ab in parseline.(readlines())
        isempty(ab) && continue
        a, b = ab
        push!(graph[a], b)
        push!(graph[b], a)
    end
    torch = zeros(Int, N)
    torch[1] = 1
    que = [1]
    while !isempty(que)
        b = popfirst!(que)
        for a in graph[b]
            torch[a]==0 && (push!(que, a); torch[a] = b)
        end
    end
    println("Yes")
    for t in torch[2:end]
        println(t)
    end
end
DoubleDots()

Score: 400 points

Problem Statement

There is a cave.

The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.

It is dark in the cave, so we have decided to place a signpost in each room except Room 1. The signpost in each room will point to one of the rooms directly connected to that room with a passage.

Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room 1.

If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room 1 after traversing the minimum number of passages possible.

Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

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

1 \leq A_i, B_i \leq N\ (1 \leq i \leq M)

A_i \neq B_i\ (1 \leq i \leq M)

One can travel between any two rooms by traversing passages.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If there is no way to place signposts satisfying the objective, print No.

Otherwise, print N lines. The first line should contain Yes, and the i-th line (2 \leq i \leq N) should contain the integer representing the room indicated by the signpost in Room i.

Sample Input 1

4 4
1 2
2 3
3 4
4 2

Sample Output 1

Yes
1
2
2

If we place the signposts as described in the sample output, the following happens:

Starting in Room 2, you will reach Room 1 after traversing one passage: (2) \to 1. This is the minimum number of passages possible.

Starting in Room 3, you will reach Room 1 after traversing two passages: (3) \to 2 \to 1. This is the minimum number of passages possible.

Starting in Room 4, you will reach Room 1 after traversing two passages: (4) \to 2 \to 1. This is the minimum number of passages possible.

Thus, the objective is satisfied.

Sample Input 2

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

Sample Output 2

Yes
6
5
5
1
1

If there are multiple solutions, any of them will be accepted.


if isfile("mystdin.txt");mystdin=open("mystdin.txt","r");redirect_stdin(mystdin);end
pI(x)=parse(Int,x)
pM(x::Array{SubString{String},1})=map(pI,x)
function main()
  n,m=pM(split(readline()))
  graph=[Int[] for i=1:n]
  for i=1:m;
    a,b=pM(split(readline()))
    push!(graph[a],b)
    push!(graph[b],a)
  end
  que=Int[1]
  mezirusi=zeros(Int,n)
  mezirusi[1]=1
  while !isempty(que)
    look=popfirst!(que)
    for next=graph[look]
      if mezirusi[next]!=0;continue;end
      mezirusi[next]=look+1
      push!(que,next)
    end
  end
  println("Yes")
  for i=mezirusi[2:end];println(i-1);end
end
main()
if isdefined(Base, :mystdin);close(mystdin);end


parseInt(x)=parse(Int, x)
parseMap(x::Array{SubString{String},1})=map(parseInt, x)
const p = 10^9+7

function main()
	n = readline() |> parseInt
	a = Tuple{Int,Int}[(0,0) for i in 1:n]
	for i in 1:n
		s,t = readline() |> split |> parseMap
		a[i] = (s,t)
	end
	d = Dict{Tuple{Int,Int},Int}()
	ct = zeros(Int,n)
	for i in 1:n
		v = (0,0)
		if a[i][1]!=0||a[i][2]!=0
			g = gcd(a[i][1],a[i][2])
			m = div(a[i][1]*a[i][2],abs(a[i][1]*a[i][2]))
			v = (m*div(abs(a[i][1]),g),div(abs(a[i][2]),g))
		end
		if haskey(d,(-m*abs(v[1]),abs(v[2])))
			ct[i]=d[(-m*abs(v[1]),abs(v[2]))]
		end
		if haskey(d,v)
			d[v]+=1
		else
			d[v]=1
		end
	end
	bx = ones(Int,n+1)
	for i in 2:n+1
		bx[i]=bx[i-1]*2%p
	end
	ans = 1
	for i in keys(d)
		if i==(0,0)
			ans = ans*(d[i]+1)%p
		else
			m = div(abs(i[1]),i[1])
			if haskey(d,(-m*abs(i[2]),abs(i[1])))
				if i[1]>0
					x = d[i]
					y = d[(-m*abs(i[2]),abs(i[1]))]
					ans = ans*mod(bx[x+y+1]-(bx[x+1]-1)*(bx[y+1]-1)%p,p)%p
				end
			else
				ans = ans*bx[d[i]+1]%p
			end
		end
	end
	println(mod(ans-1,p))
end

main()

Score: 500 points

Problem Statement

We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively.

We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time.

The i-th and j-th sardines (i \neq j) are on bad terms if and only if A_i \cdot A_j + B_i \cdot B_j = 0.

In how many ways can we choose the set of sardines to put into the cooler? Since the count can be enormous, print it modulo 1000000007.

Constraints

All values in input are integers.

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

-10^{18} \leq A_i, B_i \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the count modulo 1000000007.

Sample Input 1

3
1 2
-1 1
2 -1

Sample Output 1

5

There are five ways to choose the set of sardines, as follows:

The 1-st

The 1-st and 2-nd

The 2-nd

The 2-nd and 3-rd

The 3-rd

Sample Input 2

10
3 2
3 2
-1 1
2 -1
-3 -9
-8 12
7 7
8 1
8 2
8 4

Sample Output 2

479


function main()
  s = readline()
  t = readline()

  char_s = Vector{Char}(s)
  char_t = Vector{Char}(t)

  println(char_t[1:length(t)-1] == char_s ? "Yes" : "No")
end

main()

Score : 100 points

Problem Statement

Takahashi wants to be a member of some web service.

He tried to register himself with the ID S, which turned out to be already used by another user.

Thus, he decides to register using a string obtained by appending one character at the end of S as his ID.

He is now trying to register with the ID T. Determine whether this string satisfies the property above.

Constraints

S and T are strings consisting of lowercase English letters.

1 \leq |S| \leq 10

|T| = |S| + 1

Input

Input is given from Standard Input in the following format:

S
T

Output

If T satisfies the property in Problem Statement, print Yes; otherwise, print No.

Sample Input 1

chokudai
chokudaiz

Sample Output 1

Yes

chokudaiz can be obtained by appending z at the end of chokudai.

Sample Input 2

snuke
snekee

Sample Output 2

No

snekee cannot be obtained by appending one character at the end of snuke.

Sample Input 3

a
aa

Sample Output 3

Yes


S=chomp(readline())
T=chomp(readline())
anser = (S==T[1:(end-1)] ? "Yes" : "No")
print(anser)


function solve()
    a, b, c, k = [parse(Int, x) for x in split(readline())]
    if k <= a
        k
    elseif k <= a+b
        a
    else
        a - (k-a-b)
    end
end

println(solve())

Score : 200 points

Problem Statement

We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.

We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?

Constraints

All values in input are integers.

0 \leq A, B, C

1 \leq K \leq A + B + C \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the maximum possible sum of the numbers written on the cards chosen.

Sample Input 1

2 1 1 3

Sample Output 1

2

Consider picking up two cards with 1s and one card with a 0.
In this case, the sum of the numbers written on the cards is 2, which is the maximum possible value.

Sample Input 2

1 2 3 4

Sample Output 2

0

Sample Input 3

2000000000 0 0 2000000000

Sample Output 3

2000000000


function f()
    a,b,c,k=map(x->parse(Int,x),split(readline()))
    ans=0
    for i=1:k
        if a != 0
            ans += 1
            a -= 1
        elseif b != 0
            b -= 1
        elseif c != 0
            ans -= 1
            c -= 1
        end
    end
    println(ans)
end
f()


function main()
    n, m, x = parse.(Int, split(readline()))
    c = zeros(Int, n);
    a = zeros(Int, n, m);
    for i in 1:n
        xx = parse.(Int, split(readline()))
        c[i] = xx[1]
        a[i, :] = xx[2:end]
    end
    L = n
    comb = Vector{Int}[]
    for i = 0:2^L-1
        cc = Int[]
        str = bitstring(i)
        str[length(str)-L+1:length(str)]
        for j in length(str)-L+1:length(str)
            push!(cc, Int(str[j] - '0'))
        end
        push!(comb, cc)
    end

    money = Int[]
    ok = false
    idxs = []
    for i in eachindex(comb)
        aa = zeros(Int, m)
        mm = 0
        for j in eachindex(comb[i])
            if comb[i][j] == 1
                for k in 1:m
                    aa[k] += a[j, k]
                end
                mm += c[j]
            end
        end
        if all(aa .>= x)
            push!(money, mm)
            push!(idxs, i)
            ok = true
        end
    end

    if ok == false
        println(-1)
    else
        println(minimum(money))
    end
end

main()

Score : 300 points

Problem

Takahashi, who is a novice in competitive programming, wants to learn M algorithms.
Initially, his understanding level of each of the M algorithms is 0.

Takahashi is visiting a bookstore, where he finds N books on algorithms.
The i-th book (1\leq i\leq N) is sold for C_i yen (the currency of Japan). If he buys and reads it, his understanding level of the j-th algorithm will increase by A_{i,j} for each j (1\leq j\leq M).
There is no other way to increase the understanding levels of the algorithms.

Takahashi's objective is to make his understanding levels of all the M algorithms X or higher. Determine whether this objective is achievable. If it is achievable, find the minimum amount of money needed to achieve it.

Constraints

All values in input are integers.

1\leq N, M\leq 12

1\leq X\leq 10^5

1\leq C_i \leq 10^5

0\leq A_{i, j} \leq 10^5

Input

Input is given from Standard Input in the following format:

N M X
C_1 A_{1,1} A_{1,2} \cdots A_{1,M}
C_2 A_{2,1} A_{2,2} \cdots A_{2,M}
\vdots
C_N A_{N,1} A_{N,2} \cdots A_{N,M}

Output

If the objective is not achievable, print -1; otherwise, print the minimum amount of money needed to achieve it.

Sample Input 1

3 3 10
60 2 2 4
70 8 7 9
50 2 3 9

Sample Output 1

120

Buying the second and third books makes his understanding levels of all the algorithms 10 or higher, at the minimum cost possible.

Sample Input 2

3 3 10
100 3 1 4
100 1 5 9
100 2 6 5

Sample Output 2

-1

Buying all the books is still not enough to make his understanding levels of all the algorithms 10 or higher.

Sample Input 3

8 5 22
100 3 7 5 3 1
164 4 5 2 7 8
334 7 2 7 2 9
234 4 7 2 8 2
541 5 4 3 3 6
235 4 8 6 9 7
394 3 6 1 6 2
872 8 4 3 7 2

Sample Output 3

1067