#!/usr/bin/env -S JULIA_VERSION=1.4.0 julia
# contest: abc167, problem: abc167_c, alphabet: C

function solve(N::Int, M::Int, X::Int, C::Vector{Int}, A::Matrix{Int})
  min_cost = 2^60
  for i in 0:2^N-1
    s = string(i, base=2, pad=N)
    @assert length(s) == N
    study = zeros(Int, M)
    cost = 0
    for (j, js) in enumerate(s)
      js == '0' && continue
      cost += C[j]
      for k in 1:M
        study[k] += A[j, k]
      end
    end
    if all(study .>= X)
      min_cost = min(min_cost, cost)
    end
  end
  if min_cost < 2^60
    println(min_cost)
  else
    println(-1)
  end
end

function main()
  # Failed to predict input format
  tokens = Channel{String}(32)
  Task() do
    for line in eachline(@static VERSION < v"0.6" ? STDIN : stdin)
      startswith(line, '\0') && break
      for token in split(chomp(line))
        put!(tokens, token)
      end
    end
    close(tokens)
  end |> schedule
  N = parse(Int, take!(tokens))
  M = parse(Int, take!(tokens))
  X = parse(Int, take!(tokens))
  C = zeros(Int, N)
  A = zeros(Int, N, M)
  for i in 1:N
    C[i] = parse(Int, take!(tokens))
    for j in 1:M
      A[i, j] = parse(Int, take!(tokens))
    end
  end
  solve(N, M, X, C, A)
end

if isempty(get(ENV, "ATCODER_LOCAL", ""))
  isempty(ARGS) && main()
else
  @eval begin
    const samples = [("3 3 10\n60 2 2 4\n70 8 7 9\n50 2 3 9", "120"), ("3 3 10\n100 3 1 4\n100 1 5 9\n100 2 6 5", "-1"), ("8 5 22\n100 3 7 5 3 1\n164 4 5 2 7 8\n334 7 2 7 2 9\n234 4 7 2 8 2\n541 5 4 3 3 6\n235 4 8 6 9 7\n394 3 6 1 6 2\n872 8 4 3 7 2", "1067")]
    function test(sampleids...)
      isempty(sampleids) && return test(collect(1:length(samples))...)
      ostdin, ostdout = @static VERSION < v"0.6" ? (STDIN, STDOUT) : (stdin, stdout)
      rd, wr = first(redirect_stdout()), last(redirect_stdin())
      try
        map(sampleids) do sampleid
          input, output = samples[sampleid]
          print(ostdout, "Testing sample #$(sampleid)..."); flush(ostdout)
          println(wr, input)
          println(wr, "\0")
          t = @elapsed main()
          println()
          result = strip(String(readavailable(rd)))
          if result == output
            println(ostdout, "OK ($t sec).")
            true
          else
            println(ostdout, "ERROR ($t sec)")
            println(ostdout, "== expected ==\n$output")
            println(ostdout, "== actual ==\n$result\n")
            false
          end
        end |> all
      finally
        redirect_stdin(ostdin)
        redirect_stdout(ostdout)
      end
    end
    submit() = test() && (prog = @__FILE__; run(`atcoder-submit $prog`))
    !isinteractive() && submit()
  end
end


parseInt(x)=parse(Int, x)
parseMap(x::Array{SubString{String},1})=map(parseInt, x)
function eval(a::Tuple{Int,Int},b::Tuple{Int,Int})
	if a[1]-a[2]>b[1]-b[2]
		1
	elseif a[1]-a[2]==b[1]-b[2]
		0
	else
		-1
	end
end

function hpush(h::Array{Tuple{Int,Int},1},x::Tuple{Int,Int})
	push!(h,x)
	if length(h) > 1
		l = length(h)
		k = l>>1
		while eval(x,h[k])==1&&k>=1
			tmp = h[k]
			h[k] = x
			h[l] = tmp
			k = max(k>>1,1)
			l = l>>1
		end
	end
end

function hpop(h::Array{Tuple{Int,Int},1})
	x = h[1]
	z = pop!(h)
	if !isempty(h)
		h[1] = z
		k = 1
		l = length(h)
		while k <= l
			if 2*k>l
				break
			elseif 2*k+1>l
				if eval(z,h[2*k])>=0
					break
				else
					tmp = h[2*k]
					h[2*k] = z
					h[k] = tmp
					k = 2*k
				end
			else
				if eval(z,h[2*k])>=0&&eval(z,h[2*k+1])>=0
					break
				else
					t = eval(h[2*k],h[2*k+1])>=0 ? 2*k : 2*k+1
					tmp = h[t]
					h[t] = z
					h[k] = tmp
					k = t
				end
			end
		end
	end
	x
end

function main()
	n = readline() |> parseInt
	a = Tuple{Int,Int}[]
	b = Tuple{Int,Int}[]
	f = 0
	lx = 0
	rx = 0
	for i in 1:n
		s = readline() |> chomp
		l = 0
		r = 0
		for j in 1:length(s)
			if s[j]=='('
				l += 1
			else
				if l==0
					r+=1
				else
					l-=1
				end
			end
		end
		if l>r
			push!(a,(l,r))
		else
			push!(b,(l,r))
		end
		lx+=l
		rx+=r
	end
	f = 0
	if lx!=rx
		f = 1
	end
	lc = 0
	a = sort(a,by=x->x[2])
	for i in 1:length(a)
		if lc-a[i][2]<0
			f = 1
		end
		lc+=a[i][1]-a[i][2]
	end
	b = sort(b,by=x->x[1],rev=true)
	for i in 1:length(b)
		if lc-b[i][2]<0
			f = 1
		end
		lc += b[i][1]-b[i][2]
	end
	println(f==0 ? "Yes" : "No")
end

main()

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

Score : 600 points

Problem Statement

A bracket sequence is a string that is one of the following:

An empty string;

The concatenation of (, A, and ) in this order, for some bracket sequence A ;

The concatenation of A and B in this order, for some non-empty bracket sequences A and B /

Given are N strings S_i. Can a bracket sequence be formed by concatenating all the N strings in some order?

Constraints

1 \leq N \leq 10^6

The total length of the strings S_i is at most 10^6.

S_i is a non-empty string consisting of ( and ).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

If a bracket sequence can be formed by concatenating all the N strings in some order, print Yes; otherwise, print No.

Sample Input 1

2
)
(()

Sample Output 1

Yes

Concatenating (() and ) in this order forms a bracket sequence.

Sample Input 2

2
)(
()

Sample Output 2

No

Sample Input 3

4
((()))
((((((
))))))
()()()

Sample Output 3

Yes

Sample Input 4

3
(((
)
)

Sample Output 4

No

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 eval(a::Tuple{Int,Int},b::Tuple{Int,Int})
	if a[1]-a[2]>b[1]-b[2]
		1
	elseif a[2]==b[2]
		0
	else
		-1
	end
end

function hpush(h::Array{Tuple{Int,Int},1},x::Tuple{Int,Int})
	push!(h,x)
	if length(h) > 1
		l = length(h)
		k = l>>1
		while eval(x,h[k])==1&&k>=1
			tmp = h[k]
			h[k] = x
			h[l] = tmp
			k = max(k>>1,1)
			l = l>>1
		end
	end
end

function hpop(h::Array{Tuple{Int,Int},1})
	x = h[1]
	z = pop!(h)
	if !isempty(h)
		h[1] = z
		k = 1
		l = length(h)
		while k <= l
			if 2*k>l
				break
			elseif 2*k+1>l
				if eval(z,h[2*k])>=0
					break
				else
					tmp = h[2*k]
					h[2*k] = z
					h[k] = tmp
					k = 2*k
				end
			else
				if eval(z,h[2*k])>=0&&eval(z,h[2*k+1])>=0
					break
				else
					t = eval(h[2*k],h[2*k+1])>=0 ? 2*k : 2*k+1
					tmp = h[t]
					h[t] = z
					h[k] = tmp
					k = t
				end
			end
		end
	end
	x
end

function main()
	n = readline() |> parseInt
	a = Tuple{Int,Int}[]
	b = Tuple{Int,Int}[]
	f = 0
	lx = 0
	rx = 0
	for i in 1:n
		s = readline() |> chomp
		l = 0
		r = 0
		for j in 1:length(s)
			if s[j]=='('
				l += 1
			else
				if l==0
					r+=1
				else
					l-=1
				end
			end
		end
		if l>r
			push!(a,(l,r))
		else
			push!(b,(l,r))
		end
		lx+=l
		rx+=r
	end
	f = 0
	if lx!=rx
		f = 1
	end
	lc = 0
	a = sort(a,by=x->(x[2],x[2]-x[1]))
	if !isempty(a)
		if a[1][2]>0
			f = 1
		end
		lc+=a[1][1]
		popfirst!(a)
	end
	h = Tuple{Int,Int}[]
	l = length(a)
	for i in 1:l
		if !isempty(a)
			while lc>=a[1][2]
				hpush(h,popfirst!(a))
			end
			if isempty(a)
				break
			end
		end
		if isempty(h)
			f = 1
		end
		now=hpop(h)
		lc+=now[1]-now[2]
	end
	b = sort(b,by=x->x[2],rev=true)
	for i in 1:length(b)
		if lc<b[i][2]
			f=1
		end
		lc+=b[i][1]-b[i][2]
	end
	println(f==1 ? "No" : "Yes")
end

main()


parseInt(x)=parse(Int, x)
parseMap(x::Array{SubString{String},1})=map(parseInt, x)
function eval(a::Tuple{Int,Int},b::Tuple{Int,Int})
	if a[2]<b[2]||(a[2]==b[2]&&a[1]-a[2]>b[1]-b[2])
		1
	elseif a[1]-a[2]==b[1]-b[2]
		0
	else
		-1
	end
end

function hpush(h::Array{Tuple{Int,Int},1},x::Tuple{Int,Int})
	push!(h,x)
	if length(h) > 1
		l = length(h)
		k = l>>1
		while eval(x,h[k])==1&&k>=1
			tmp = h[k]
			h[k] = x
			h[l] = tmp
			k = max(k>>1,1)
			l = l>>1
		end
	end
end

function hpop(h::Array{Tuple{Int,Int},1})
	x = h[1]
	z = pop!(h)
	if !isempty(h)
		h[1] = z
		k = 1
		l = length(h)
		while k <= l
			if 2*k>l
				break
			elseif 2*k+1>l
				if eval(z,h[2*k])>=0
					break
				else
					tmp = h[2*k]
					h[2*k] = z
					h[k] = tmp
					k = 2*k
				end
			else
				if eval(z,h[2*k])>=0&&eval(z,h[2*k+1])>=0
					break
				else
					t = eval(h[2*k],h[2*k+1])>=0 ? 2*k : 2*k+1
					tmp = h[t]
					h[t] = z
					h[k] = tmp
					k = t
				end
			end
		end
	end
	x
end

function main()
	n = readline() |> parseInt
	a = Tuple{Int,Int}[(0,0) for i in 1:n]
	f = 0
	for i in 1:n
		s = readline() |> chomp
		l = 0
		r = 0
		for j in 1:length(s)
			if s[j]=='('
				l += 1
			else
				if l==0
					r+=1
				else
					l-=1
				end
			end
		end
		a[i]=(l,r)
	end
	ls = 0
	rs = 0
	for i in 1:n
		ls+=a[i][1]
		rs+=a[i][2]
	end
	if ls!=rs
		println("No")
	else
		a = sort(a,by=x->(x[2],x[1]-x[2]))
		h = Tuple{Int,Int}[]
		f = 0
		lc = 0
		ct = 1
		if a[1][2]==0
			f = 1
			lc+=a[1][1]
			popfirst!(a)
		end
		if f == 0
			println("No")
		else
			for i in 1:n-1
				if !isempty(a)
					while a[1][2]<=lc
						now = popfirst!(a)
						hpush(h,now)
						if isempty(a)
							break
						end
					end
				end
				if isempty(h)
					f = 0
				else
					now = hpop(h)
					lc+=now[1]-now[2]
				end
			end
			if f==0
				println("No")
			else
				println("Yes")
			end
		end
	end
end

main()


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

function main()
	s = readline() |> chomp
	println(s=="ABC" ? "ARC" : "ABC")
end

main()

Score : 100 points

Problem Statement

AtCoder Inc. holds a contest every Saturday.

There are two types of contests called ABC and ARC, and just one of them is held at a time.

The company holds these two types of contests alternately: an ARC follows an ABC and vice versa.

Given a string S representing the type of the contest held last week, print the string representing the type of the contest held this week.

Constraints

S is ABC or ARC.

Input

Input is given from Standard Input in the following format:

S

Output

Print the string representing the type of the contest held this week.

Sample Input 1

ABC

Sample Output 1

ARC

They held an ABC last week, so they will hold an ARC this week.


function main()
  N,K=map(x->parse(Int,x),split(readline()))
  vis=[false for _=1:N]
  for _=1:N
    readline()
    for a=map(x->parse(Int,x),split(readline()))
      if !vis[a]
        vis[a]=true
        N-=1
      end
    end
  end
  println(N)
end
main()

Score : 200 points

Problem Statement

N Snukes called Snuke 1, Snuke 2, ..., Snuke N live in a town.

There are K kinds of snacks sold in this town, called Snack 1, Snack 2, ..., Snack K. The following d_i Snukes have Snack i: Snuke A_{i, 1}, A_{i, 2}, \cdots, A_{i, {d_i}}.

Takahashi will walk around this town and make mischief on the Snukes who have no snacks. How many Snukes will fall victim to Takahashi's mischief?

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 100

1 \leq d_i \leq N

1 \leq A_{i, 1} < \cdots < A_{i, d_i} \leq N

Input

Input is given from Standard Input in the following format:

N K
d_1
A_{1, 1} \cdots A_{1, d_1}
\vdots
d_K
A_{K, 1} \cdots A_{K, d_K}

Output

Print the answer.

Sample Input 1

3 2
2
1 3
1
3

Sample Output 1

1

Snuke 1 has Snack 1.

Snuke 2 has no snacks.

Snuke 3 has Snack 1 and 2.

Thus, there will be one victim: Snuke 2.

Sample Input 2

3 3
1
3
1
3
1
3

Sample Output 2

2


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

function main()
    n,k=parseMap(split(readline()))
    cnt=[0 for i in 1:n]
    for i in 1:k
        d=parseInt(readline())
        a=parseMap(split(readline()))
        for j in a
            cnt[j]+=1
        end
    end
    println(count(x->x==0,cnt))
end
main()


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

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

snuke_list = zeros(N)
for i in 1:K
    d = parseInt(readline())
    A = parseMap(split(readline()))
    for a in A
        snuke_list[a] = 1
    end
end
ans = 0
for s in snuke_list
    if s == 0
        ans += 1
    end
end
println(ans)
end

main()


function solve()
    n, m = [parse(Int, x) for x in split(readline())]
    h = [parse(Int, x) for x in split(readline())]

    good = ones(Bool, n)
    for _ in 1:m
        a, b = [parse(Int, x) for x in split(readline())]
        if h[a] < h[b]
            good[a] = false
        elseif h[b] < h[a]
            good[b] = false
        else
            good[a] = good[b] = false
        end
    end
    sum(good)
end

println(solve())

Score : 300 points

Problem Statement

There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i.
There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j.

Obs. i is said to be good when its elevation is higher than those of all observatories that can be reached from Obs. i using just one road.
Note that Obs. i is also good when no observatory can be reached from Obs. i using just one road.

How many good observatories are there?

Constraints

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq H_i \leq 10^9

1 \leq A_i,B_i \leq N

A_i \neq B_i

Multiple roads may connect the same pair of observatories.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
H_1 H_2 ... H_N
A_1 B_1
A_2 B_2
:
A_M B_M

Output

Print the number of good observatories.

Sample Input 1

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

Sample Output 1

2

From Obs. 1, you can reach Obs. 3 using just one road. The elevation of Obs. 1 is not higher than that of Obs. 3, so Obs. 1 is not good.

From Obs. 2, you can reach Obs. 3 and 4 using just one road. The elevation of Obs. 2 is not higher than that of Obs. 3, so Obs. 2 is not good.

From Obs. 3, you can reach Obs. 1 and 2 using just one road. The elevation of Obs. 3 is higher than those of Obs. 1 and 2, so Obs. 3 is good.

From Obs. 4, you can reach Obs. 2 using just one road. The elevation of Obs. 4 is higher than that of Obs. 2, so Obs. 4 is good.

Thus, the good observatories are Obs. 3 and 4, so there are two good observatories.

Sample Input 2

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

Sample Output 2

3


function main()

  (N, M) = map(x -> parse(Int, x), split(readline()))
  H = map(x -> parse(Int, x), split(readline()))

  check = zeros(Int, N)
  for i in 1:M
    (A, B) = map(x -> parse(Int, x), split(readline()))
    check[A] = max(check[A], H[B])
    check[B] = max(check[B], H[A])
  end

  ans = 0

  for i in 1:N
    if H[i] > check[i]
      ans += 1
    end
  end

  println(ans)

end

main()


function f()
    n,m=map(x->parse(Int,x),split(readline()))
    ni=map(x->parse(Int,x),split(readline()))
    a=zeros(Int,m)
    b=zeros(Int,m)
    for i=1:m
        ai,bi=map(x->parse(Int,x),split(readline()))
        a[i]=ai
        b[i]=bi
    end
    sum=0
    route=0
    flag=0
    for i=1:n
        flag=0
        route=0
        for j=1:m
            if a[j]==i
                route=1
                if ni[a[j]]<=ni[b[j]]
                    flag=1
                end
            end
            if b[j]==i
                route=1
                if ni[b[j]]<=ni[a[j]]
                    flag=1
                end
            end
        end
        if flag==0 || route==0
            sum += 1
        end
    end
    print(sum)
end

f()


function main()
  n,m=parse.(Int,split(readline()))
  h=parse.(Int,split(readline()))
  ans=[1 for i=1:n]
  for i=1:m
    a,b=parse.(Int,split(readline()))
    if h[a]==h[b]
      ans[a]=0
      ans[b]=0
    elseif h[a]<h[b]
      ans[a]=0
    else
      ans[b]=0
    end
  end
  print(sum(ans))
end
main()


function f()
    x=parse(Int,readline())
    x1=0
    for a=0:floor(x^(1/5))
        for b=-floor(x^(1/5)):0
            if x%(a-b) == 0
                print(1)
                x1 = x/(a-b)
                if x1 == a^4+a*b^3+a^2*b^2+a*b^3+b^4
                    print("$a $b")
                    exit()
                end
            end
        end
    end
end
f()

Score : 400 points

Problem Statement

Give a pair of integers (A, B) such that A^5-B^5 = X.
It is guaranteed that there exists such a pair for the given integer X.

Constraints

1 \leq X \leq 10^9

X is an integer.

There exists a pair of integers (A, B) satisfying the condition in Problem Statement.

Input

Input is given from Standard Input in the following format:

X

Output

Print A and B, with space in between.
If there are multiple pairs of integers (A, B) satisfying the condition, you may print any of them.

A B

Sample Input 1

33

Sample Output 1

2 -1

For A=2 and B=-1, A^5-B^5 = 33.

Sample Input 2

1

Sample Output 2

0 -1


parseInt() = parse(Int,readline())
function f(n,a,b)
    if b>n
        return 0
    end
    ans=0
    for i=b+1:n
        if abs(b-i) == a[b]+a[i]
            ans += 1
        end
    end
    ans += f(n,a,b+1)
    return ans
end
n=parseInt()
a=map(x->parse(Int,x),split(readline()))
print(f(n,a,1))

Score: 500 points

Problem Statement

You are the top spy of AtCoder Kingdom. To prevent the stolen secret from being handed to AlDebaran Kingdom, you have sneaked into the party where the transaction happens.

There are N attendees in the party, and they are given attendee numbers from 1 through N. The height of Attendee i is A_i.

According to an examination beforehand, you know that a pair of attendees satisfying the condition below will make the transaction.

The absolute difference of their attendee numbers is equal to the sum of their heights.

There are \frac{N(N-1)}{2} ways to choose two from the N attendees and make a pair. Among them, how many satisfy the condition above?

P.S.: We cannot let you know the secret.

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^9\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the number of pairs satisfying the condition.

Sample Input 1

6
2 3 3 1 3 1

Sample Output 1

3

A_1 + A_4 = 3, so the pair of Attendee 1 and 4 satisfy the condition.

A_2 + A_6 = 4, so the pair of Attendee 2 and 6 satisfy the condition.

A_4 + A_6 = 2, so the pair of Attendee 4 and 6 satisfy the condition.

No other pair satisfies the condition, so you should print 3.

Sample Input 2

6
5 2 4 2 8 8

Sample Output 2

0

No pair satisfies the condition, so you should print 0.

Sample Input 3

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

Sample Output 3

22


function main()
    n = parse(Int, readline())
    As = map(x -> parse(Int, x), split(readline()))
    ans = 0
    for (i, ai) in zip(1:n, As)
        for j = (i+ai):n
            if j - i == ai + As[j]
                ans += 1
            end
        end
    end
    println(ans)
end

main()


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

function main()
	n,a,b,c = readline() |> split |> parseMap
	s = zeros(Int,n)
	for i in 1:n
		str = readline() |> chomp
		if str=="AB"
			s[i]=1
		elseif str=="AC"
			s[i]=2
		else
			s[i]=3
		end
	end
	if a>=1&&b>=1&&c>=1
		println("Yes")
		for i in 1:n
			if s[i]==1
				if a>=b
					println("B")
					a-=1
					b+=1
				else
					println("A")
					a+=1
					b-=1
				end
			elseif s[i]==2
				if a>=c
					println("C")
					a-=1
					c+=1
				else
					println("A")
					a+=1
					c-=1
				end
			else
				if c>=b
					println("B")
					c-=1
					b+=1
				else
					println("C")
					c+=1
					b-=1
				end
			end
		end
	else
		f = 0
		ans = String["" for i in 1:n]
		nx = zeros(Int,n)
		ab = n+1
		ac = n+1
		bc = n+1
		for i in n:-1:1
			if s[i]==1
				nx[i] = bc<ac ? 3 : 2
				ab = i
			elseif s[i]==2
				nx[i] = ab < bc ? 1 : 3
				bc = i
			else
				nx[i] = ab < ac ? 1 : 2
				ac = i
			end
		end
		for i in 1:n
				if s[i]==1
					if a>b
						ans[i]="B"
						a-=1
						b+=1
					elseif b>a
						ans[i]="A"
						a+=1
						b-=1
					elseif a==0
						f = 1
					else
						if nx[i]==2
							ans[i]="A"
							a+=1
							b-=1
						else
							ans[i]="B"
							a-=1
							b+=1
						end
					end
				elseif s[i]==2
					if a>c
						ans[i]="C"
						a-=1
						c+=1
					elseif c>a
						ans[i]="A"
						a+=1
						c-=1
					elseif a==0
						f = 1
					else
						if nx[i]==3
							ans[i]="C"
							c+=1
							a-=1
						else
							ans[i]="A"
							a+=1
							c-=1
						end
					end
				else
					if c>b
						ans[i]="B"
						c-=1
						b+=1
					elseif b>c
						ans[i]="C"
						c+=1
						b-=1
					elseif b==0
						f = 1
					else
						if nx[i]==1
							ans[i]="B"
							b+=1
							a-=1
						else
							ans[i]="C"
							c+=1
							b-=1
						end
					end
				end
		end
		if f==1
			println("No")
		else
			println("Yes")
			for i in 1:n
				println(ans[i])
			end
		end
	end
end

main()

Score : 600 points

Problem Statement

There is a game that involves three variables, denoted A, B, and C.

As the game progresses, there will be N events where you are asked to make a choice.
Each of these choices is represented by a string s_i. If s_i is AB, you must add 1 to A or B then subtract 1 from the other; if s_i is AC, you must add 1 to A or C then subtract 1 from the other; if s_i is BC, you must add 1 to B or C then subtract 1 from the other.

After each choice, none of A, B, and C should be negative.

Determine whether it is possible to make N choices under this condition. If it is possible, also give one such way to make the choices.

Constraints

1 \leq N \leq 10^5

0 \leq A,B,C \leq 10^9

N, A, B, C are integers.

s_i is AB, AC, or BC.

Input

Input is given from Standard Input in the following format:

N A B C
s_1
s_2
:
s_N

Output

If it is possible to make N choices under the condition, print Yes; otherwise, print No.

Also, in the former case, show one such way to make the choices in the subsequent N lines. The (i+1)-th line should contain the name of the variable (A, B, or C) to which you add 1 in the i-th choice.

Sample Input 1

2 1 3 0
AB
AC

Sample Output 1

Yes
A
C

You can successfully make two choices, as follows:

In the first choice, add 1 to A and subtract 1 from B. A becomes 2, and B becomes 2.

In the second choice, add 1 to C and subtract 1 from A. C becomes 1, and A becomes 1.

Sample Input 2

3 1 0 0
AB
BC
AB

Sample Output 2

No

Sample Input 3

1 0 9 0
AC

Sample Output 3

No

Sample Input 4

8 6 9 1
AC
BC
AB
BC
AC
BC
AB
AB

Sample Output 4

Yes
C
B
B
C
C
B
A
A


function solve()
    k = parse(Int, readline())
    a, b = [parse(Int, x) for x in split(readline())]

    if (a ÷ k == b ÷ k) && a % k != 0
        "NG"
    else
        "OK"
    end
end

println(solve())

Score: 100 points

Problem Statement

Takahashi the Jumbo will practice golf.

His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive).

If he can achieve the objective, print OK; if he cannot, print NG.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 1000

1 \leq K \leq 1000

Input

Input is given from Standard Input in the following format:

K
A B

Output

If he can achieve the objective, print OK; if he cannot, print NG.

Sample Input 1

7
500 600

Sample Output 1

OK

Among the multiples of 7, for example, 567 lies between 500 and 600.

Sample Input 2

4
5 7

Sample Output 2

NG

No multiple of 4 lies between 5 and 7.

Sample Input 3

1
11 11

Sample Output 3

OK


const teststr =
"""
1
11 11
"""

function lines()
  Channel{String}(32) do ch
    ll = readlines()
    lines = isempty(ll) ? split(teststr, "\n") : ll
    for s in lines
      put!(ch, s)
    end
  end
end

quit() = exit(0)
in_1(ch) = parse(Int, take!(ch))
in_a(ch) = parse.(Int, split(take!(ch)))

function main()
  ch = lines()
  K = in_1(ch)
  A,B = in_a(ch)
  for i in A:B
    if mod(i, K) == 0
      println("OK")
      quit()
    end
  end
  println("NG")
end

main()


const double = Float64
const int = Int64
const vint = Vector{int}
const vdouble = Vector{double}

int(x) = parse(int,x)
parseint(x) = parse(int, x)

function readint()
  moji = readline(stdin)
  moji = split(moji)
  return map(parseint,moji)

end

function main()
  k = readint()[1]
  a,b = readint()
  if a%k==0 || b÷k - a÷k >= 1
    println("OK")
  else
    println("NG")
  end
end

main()


const double = Float64
const int = Int64
const vint = Vector{int}
const vdouble = Vector{double}

int(x) = parse(int,x)
parseint(x) = parse(int, x)

function readint()
  moji = readline(stdin)
  moji = split(moji)
  return map(parseint,moji)

end

function main()
  k = readint()[1]
  a,b = readint()
  if a%k==0 || b//k-a//k >= 1
    println("OK")
  else
    println("NG")
  end
end

main()


function main()
    K = parse(Int, readline())
    A, B = map(x -> parse(Int, x), split(readline()))
    ans = "NG"
    for i ∈ A:B
        if i % K == 0
            ans = "OK"
            break
        end
    end
    println(ans)
end
main()


function f(k,a,b)
    for i=a:b
        if k%i == 0
            print("OK")
            exit()
        end
    end
    print("NG")
end
k=parse(Int,readline())
a,b=map(x->parse(Int,x),split(readline()))
f(k,a,b)


function solve()
    x = parse(Int, readline())
    sol = 0
    deposit = 100
    while deposit < x
        sol += 1
        deposit += deposit ÷ 100
    end
    sol
end

println(solve())

Score : 200 points

Problem Statement

Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank.

The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.)

Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or above for the first time?

Constraints

101 \le X \le 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of years it takes for Takahashi's balance to reach X yen or above for the first time.

Sample Input 1

103

Sample Output 1

3

The balance after one year is 101 yen.

The balance after two years is 102 yen.

The balance after three years is 103 yen.

Thus, it takes three years for the balance to reach 103 yen or above.

Sample Input 2

1000000000000000000

Sample Output 2

3760

Sample Input 3

1333333333

Sample Output 3

1706


X=parse(Int,readline())
c=1
n=100
while n<X
  c+=1
  n+=div(n,100)
end
println(c)


function main()

  X = parse(BigInt, readline())

  ans = 0
  check = 100

  while check < X
    ans += 1
    check += div(check, 100)
  end

  println(ans)

end

main()


x=parse(Int,readline())
a=100
i=0
while a<x
  global a+=floor(a/100)
  global i+=1
end
print(i)


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)

n,m,q=parseMap(split(readline()))
array=Vector{Vector{Int}}()
function dfs(now,arr::Vector{Int})
    if now==n
        push!(array,arr)
        return
    end
    if now==0
        for i in 1:m
            dfs(now+1,[i])
        end
    else
        for i in arr[end]:m
            dfs(now+1,vcat(arr,i))
        end
    end
end

function main()
    data=[parseMap(split(readline())) for i in 1:q]
    dfs(0,Vector{Int}())
    ans=0
    for i in array
        res=0
        for j in data
            if i[j[2]]-i[j[1]]==j[3]
                res+=j[4]
            end
        end
        ans=max(ans,res)
    end
    println(ans)
end
main()

Score : 300 points

Problem Statement

Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).

Consider a sequence A satisfying the following conditions:

A is a sequence of N positive integers.

1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.

Let us define a score of this sequence as follows:

The score is the sum of d_i over all indices i such that A_{b_i} - A_{a_i} = c_i. (If there is no such i, the score is 0.)

Find the maximum possible score of A.

Constraints

All values in input are integers.

2 ≤ N ≤ 10

1 \leq M \leq 10

1 \leq Q \leq 50

1 \leq a_i < b_i \leq N ( i = 1, 2, ..., Q )

0 \leq c_i \leq M - 1 ( i = 1, 2, ..., Q )

(a_i, b_i, c_i) \neq (a_j, b_j, c_j) (where i \neq j)

1 \leq d_i \leq 10^5 ( i = 1, 2, ..., Q )

Input

Input is given from Standard Input in the following format:

N M Q
a_1 b_1 c_1 d_1
:
a_Q b_Q c_Q d_Q

Output

Print the maximum possible score of A.

Sample Input 1

3 4 3
1 3 3 100
1 2 2 10
2 3 2 10

Sample Output 1

110

When A = \{1, 3, 4\}, its score is 110. Under these conditions, no sequence has a score greater than 110, so the answer is 110.

Sample Input 2

4 6 10
2 4 1 86568
1 4 0 90629
2 3 0 90310
3 4 1 29211
3 4 3 78537
3 4 2 8580
1 2 1 96263
1 4 2 2156
1 2 0 94325
1 4 3 94328

Sample Output 2

357500

Sample Input 3

10 10 1
1 10 9 1

Sample Output 3

1


function main()
  a,b,n=parse.(Int128,split(readline()))
  n%=b
  ans=0
  for i=min(n,b-1):b:n
    ans=max(ans,fld(a*i,b)-a*fld(i,b))
  end
  print(ans)
end
main()

Score : 400 points

Problem Statement

Given are integers A, B, and N.

Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.

Here floor(t) denotes the greatest integer not greater than the real number t.

Constraints

1 ≤ A ≤ 10^{6}

1 ≤ B ≤ 10^{12}

1 ≤ N ≤ 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B N

Output

Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.

Sample Input 1

5 7 4

Sample Output 1

2

When x=3, floor(Ax/B)-A×floor(x/B) = floor(15/7) - 5×floor(3/7) = 2. This is the maximum value possible.

Sample Input 2

11 10 9

Sample Output 2

9


function main()
    a, b, n = parse.(UInt128, split(readline()))
    before = f(one(Float64), a, b)
    hist = Float64[before]
    local res
    for x in 2:n
        y = f(Float64(x), a, b)
        push!(hist, y)
        if before == y
            break
        end
    end
    println(UInt128(maximum(hist)))
end

f(x,a,b)::Float64 = floor(a*x/b) - a*floor(x/b)

main()


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

val(a,b,x) = floor(a*x/b) - a * floor(x/b)

function main()
    A,B,N = reads(Int,Int,Int)
    if N == 1
        println(1)
        return
    end
    fi = 1
    fv = val(A,B,fi)
    ei = N
    ev = val(A,B,ei)
    ci = (fi+ei)÷2
    cv = val(A,B,ci)
    while true
        if fv < cv
            fi = ci
            fv = cv
        else
            ei = ci
            ev = cv
        end
        ci = (fi+ei)÷2
        cv = val(A,B,ci)
        if ci+1 >= ei
            println(Int(max(fv,cv,ev)))
            break
        end
    end
end

main()


let
  A, B, N = map(x -> parse(Int, x), readline() |> split)
  println((A*N)÷B - A*(N÷B))
end


function main()
  n,m=map(x->parse(Int,x),split(readline()))
  for i=1:m
    id=n+1-i
    if n%2==0&&i*4>n
      id-=1
    end
    println("$i $id")
  end
end
main()

Score : 500 points

Problem Statement

You are going to hold a competition of one-to-one game called AtCoder Janken. (Janken is the Japanese name for Rock-paper-scissors.)
N players will participate in this competition, and they are given distinct integers from 1 through N.
The arena has M playing fields for two players. You need to assign each playing field two distinct integers between 1 and N (inclusive).
You cannot assign the same integer to multiple playing fields.
The competition consists of N rounds, each of which proceeds as follows:

For each player, if there is a playing field that is assigned the player's integer, the player goes to that field and fight the other player who comes there.

Then, each player adds 1 to its integer. If it becomes N+1, change it to 1.

You want to ensure that no player fights the same opponent more than once during the N rounds.
Print an assignment of integers to the playing fields satisfying this condition.
It can be proved that such an assignment always exists under the constraints given.

Constraints

1 \leq M

M \times 2 +1 \leq N \leq 200000

Input

Input is given from Standard Input in the following format:

N M

Output

Print M lines in the format below.
The i-th line should contain the two integers a_i and b_i assigned to the i-th playing field.

a_1 b_1
a_2 b_2
:
a_M b_M

Sample Input 1

4 1

Sample Output 1

2 3

Let us call the four players A, B, C, and D, and assume that they are initially given the integers 1, 2, 3, and 4, respectively.

The 1-st round is fought by B and C, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 2, 3, 4, and 1, respectively.

The 2-nd round is fought by A and B, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 3, 4, 1, and 2, respectively.

The 3-rd round is fought by D and A, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 4, 1, 2, and 3, respectively.

The 4-th round is fought by C and D, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 1, 2, 3, and 4, respectively.

No player fights the same opponent more than once during the four rounds, so this solution will be accepted.

Sample Input 2

7 3

Sample Output 2

1 6
2 5
3 4


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()
    N,M = reads(Int,Int)
    tp = 0
    arr = Set(Int[])
    i = 0
    if isodd(M)
        while i < M
            i += 1
            if (i-1+N-(N+1-i-tp)) in arr
                tp += 1
                i -= 1
                continue
            end
            println("$i $(N+1-i-tp)")
            push!(arr, N+1-i-tp-i-1)
        end
    else
        for i in 1:M÷2
            println("$i $(N+1-i)")
        end
        for i in M÷2+1:M
            println("$i $(N+1-i-1)")
        end
    end
end

main()


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()
    N,M = reads(Int,Int)
    tp = 0
    arr = Set(Int[])
    i = 0
    if isodd(M)
    while i <M
        i += 1
        if (i-1+N-(N+1-i-tp)) in arr
            tp += 1
            i -= 1
            continue
        end
        println("$i $(N+1-i-tp)")
        push!(arr, N+1-i-tp-i-1)
    end
    else
    for i in 1:M
        println("$i $(N+1-i)")
    end
end

main()


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()
    N,M = reads(Int,Int)
    if isodd(M)
        for i in 1:M
            println("$i $(N+1-i)")
        end
    else
        for i in 1:M÷2
            println("$i $(N+1-i)")
        end
        for i in M÷2+1:M
            println("$i $(N+1-i-1)")
        end
    end
end

main()


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

function main()
	n,m = readline() |> split |> parseMap
	if n%2==0
		for i in m:-1:1
			if i%2==1
				println((m-i+2)>>1," ",(m-i+2)>>1+i)
			else
				println(n>>1+(m-i+2)>>1," ",n>>1+(m-i+2)>>1+i)
			end
		end
	else
		for i in m:-1:1
			if i%2==1
				println((m-i+2)>>1," ",(m-i+2)>>1+i)
			else
				println((n+1)>>1+(m-i+1)>>1," ",(n+1)>>1+(m-i+1)>>1+i)
			end
		end
	end
end

main()


parseInt(x)=parse(Int, x)
parseMap(x::Array{SubString{String},1})=map(parseInt, x)
function bsearch(a,x);l,r=0,length(a)+1;while r-l>1;m=(r+l)>>1;if a[m]<x;l=m;else;r=m;end;end;l;end

function main()
	n = readline() |> parseInt
	a = readline() |> split |> parseMap
	e = [Int[] for i in 1:n]
	for i in 1:n-1
		u,v = readline() |> split |> parseMap
		push!(e[u],v)
		push!(e[v],u)
	end
	t = zeros(Int,n)
	ans = zeros(Int,n)
	lis = 10^18*ones(Int,n)
	bef=zeros(Int,n)
	sf = zeros(Int,n)
	t[1]=1
	ans[1]=a[1]
	lis[1]=a[1]
	bef[1]=a[1]
	stack = Int[1]
	while !isempty(stack)
		now = pop!(stack)
		k = 1
		if now!=1
			if sf[now]==0
				push!(stack,t[now])
				sf[now]=1
			end
			k = bsearch(lis,a[now])+1
			if bef[now]==0
				bef[now]=lis[k]
			end
			lis[k]=a[now]
			ans[now]=k
		end
		f = 0
		for i in e[now]
			if t[i]==0
				f = 1
				t[i]=now
				push!(stack,i)
				break
			end
		end
		if f == 0
			lis[k]=bef[now]
		end
	end
	for i in 1:n
		println(ans[i])
	end
end

main()

Score : 600 points

Problem Statement

We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i.
Vertex i has an integer a_i written on it.
For every integer k from 1 through N, solve the following problem:

We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.

Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.

Constraints

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

1 \leq a_i \leq 10^9

1 \leq u_i , v_i \leq N

u_i \neq v_i

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.

Sample Input 1

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

Sample Output 1

1
2
3
3
4
4
5
2
2
3

For example, the sequence A obtained from the shortest path from Vertex 1 to Vertex 5 is 1,2,5,3,4. Its longest increasing subsequence is A_1, A_2, A_4, A_5, with the length of 4.


function main()
  s,w = parse.(Int,split(readline()))
  println(w >= s ? "unsafe" : "safe")
end
main()

Score : 100 points

Problem Statement

There are S sheep and W wolves.

If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep.

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Constraints

1 \leq S \leq 100

1 \leq W \leq 100

Input

Input is given from Standard Input in the following format:

S W

Output

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Sample Input 1

4 5

Sample Output 1

unsafe

There are four sheep and five wolves. The number of wolves is not less than that of sheep, so they will attack them.

Sample Input 2

100 2

Sample Output 2

safe

Many a sheep drive away two wolves.

Sample Input 3

10 10

Sample Output 3

unsafe


s, w = split(readline())
println(if s <= w
            "unsafe"
        elseif s > w
            "safe"
        end
       )


parseInt(x) = parse(Int,x)
parseUInt(x) = parse(UInt64,x)
transpose(x::Array{T,3} where T) = permutedims(x,[2,1,3])
import LinearAlgebra

function exec()
    n = readline() |> parseInt
    s = readline() |> split .|> parseInt
    t = readline() |> split .|> parseInt
    u = readline() |> split .|> parseUInt
    v = readline() |> split .|> parseUInt

    tabl = fill(-1,n,n,64)
    for bits = 0:63
        for i = 1:n, j = 1:n
            if (u[i] >> bits) & 1 == (v[j] >> bits) & 1
                tabl[i,j,bits+1] = (u[i] >> bits) & 1
            end
        end
        for i = 1:n
            if t[i] == 0 && (v[i] >> bits) & 1 == 1
                tabl[:,i,bits+1] .= 1
            elseif t[i] == 1 && (v[i] >> bits) & 1 == 0
                tabl[:,i,bits+1] .= 0
            end
        end
        tabl = transpose(tabl)
        for i = 1:n
            if s[i] == 0 && (u[i] >> bits) & 1 == 1
                if count(e -> e == 0, view(tabl,:,i,bits+1)) > 0
                    println(-1)
                    return
                end
                tabl[:,i,bits+1] .= 1
            elseif s[i] == 1 && (u[i] >> bits) & 1 == 0
                if count(e -> e == 1, view(tabl,:,i,bits+1)) > 0
                    println(-1)
                    return
                end
                tabl[:,i,bits+1] .= 0
            end
        end
        for i = 1:n
            if s[i] == 1 && (u[i] >> bits) & 1 == 1 &&
                count(e -> e == 1, view(tabl,:,i,bits+1)) == 0
                suc = false
                for j = 1:n
                    if tabl[j][i][bits+1] != -1 continue end
                    if count(e -> e != 1, view(tabl,j,:,bits+1)) > 1
                        suc = true
                        tabl[j][i][bits+1] = 1
                    end
                end
                if !suc
                    println(-1)
                    return
                end
            end
        end

        tabl = transpose(tabl)
        for i = 1:n
            if t[i] == 1 && (v[i] >> bits) & 1 == 1 &&
                count(e -> e == 1, view(tabl,:,i,bits+1)) == 0
                suc = false
                for j = 1:n
                    if tabl[j][i][bits+1] != -1 continue end
                    if count(e -> e != 1, view(tabl,j,:,bits+1)) > 1
                        suc = true
                        tabl[j][i][bits+1] = 1
                    end
                end
                if !suc
                    println(-1)
                    return
                end
            end
        end
    end
    tabl = transpose(tabl)
    for i=1:n
        for j=1:n
            r = UInt64(0)
            for bits = 64:-1:1
                r = r * 2 + (tabl[j,i,bits] == 1 ? 1 : 0)
            end
            print(r, " ")
        end
        println()
    end
end

exec()

Score : 600 points

Problem Statement

Given are an integer N and arrays S, T, U, and V, each of length N.
Construct an N×N matrix a that satisfy the following conditions:

a_{i,j} is an integer.

0 \leq a_{i,j} \lt 2^{64}.

If S_{i} = 0, the bitwise AND of the elements in the i-th row is U_{i}.

If S_{i} = 1, the bitwise OR of the elements in the i-th row is U_{i}.

If T_{i} = 0, the bitwise AND of the elements in the i-th column is V_{i}.

If T_{i} = 1, the bitwise OR of the elements in the i-th column is V_{i}.

However, there may be cases where no matrix satisfies the conditions.

Constraints

All values in input are integers.

1 \leq N \leq 500

0 \leq S_{i} \leq 1

0 \leq T_{i} \leq 1

0 \leq U_{i} \lt 2^{64}

0 \leq V_{i} \lt 2^{64}

Input

Input is given from Standard Input in the following format:

N
S_{1} S_{2} ... S_{N}
T_{1} T_{2} ... T_{N}
U_{1} U_{2} ... U_{N}
V_{1} V_{2} ... V_{N}

Output

If there exists a matrix that satisfies the conditions, print one such matrix in the following format:

a_{1,1} ... a_{1,N}
:
a_{N,1} ... a_{N,N}

Note that any matrix satisfying the conditions is accepted.

If no matrix satisfies the conditions, print -1.

Sample Input 1

2
0 1
1 0
1 1
1 0

Sample Output 1

1 1
1 0

In Sample Input 1, we need to find a matrix such that:

the bitwise AND of the elements in the 1-st row is 1;

the bitwise OR of the elements in the 2-nd row is 1;

the bitwise OR of the elements in the 1-st column is 1;

the bitwise AND of the elements in the 2-nd column is 0.

Sample Input 2

2
1 1
1 0
15 15
15 11

Sample Output 2

15 11
15 11


function main()

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

  ans = zeros(Int, N)

  for i in 1:N-1
    ans[A[i]] += 1
  end

  println.(ans)

end

main()

Score : 300 points

Problem Statement

A company has N members, who are assigned ID numbers 1, ..., N.

Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number.

When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X.

You are given the information that the immediate boss of the member numbered i is the member numbered A_i. For each member, find how many immediate subordinates it has.

Constraints

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

1 \leq A_i < i

Input

Input is given from Standard Input in the following format:

N
A_2 ... A_N

Output

For each of the members numbered 1, 2, ..., N, print the number of immediate subordinates it has, in its own line.

Sample Input 1

5
1 1 2 2

Sample Output 1

2
2
0
0
0

The member numbered 1 has two immediate subordinates: the members numbered 2 and 3.

The member numbered 2 has two immediate subordinates: the members numbered 4 and 5.

The members numbered 3, 4, and 5 do not have immediate subordinates.

Sample Input 2

10
1 1 1 1 1 1 1 1 1

Sample Output 2

9
0
0
0
0
0
0
0
0
0

Sample Input 3

7
1 2 3 4 5 6

Sample Output 3

1
1
1
1
1
1
0


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
N = parseInt(readline())
A = parseMap(split(readline()))
people = zeros(Int,N)
for a in A
    people[a] += 1
end

for p in people
    println(p)
end


n = parse(Int, readline())
arr = [tpl for tpl in enumerate(parse.(Int, split(readline())))]
arr = sort(arr, by = tpl -> -tpl[2])

dp = Dict()

for ln = 0 : n
  for rn = 0 : n - ln
    if ln + rn > n || get(dp, (ln, rn), 0) > 0
      continue
    end

    if ln + rn > 0
      p, a = arr[ln + rn]
      val_l = ln > 0 ? dp[(ln - 1, rn)] + a * abs(p - ln) : 0
      val_r = rn > 0 ? dp[(ln, rn - 1)] + a * abs(p - (n - rn + 1)) : 0

      dp[(ln, rn)] = max(val_l, val_r)
    else
      dp[(0, 0)] = 0
    end
  end
end

println(maximum([dp[i, n - i] for i in 0 : n]))

Score : 500 points

Problem Statement

There are N children standing in a line from left to right. The activeness of the i-th child from the left is A_i.

You can rearrange these children just one time in any order you like.

When a child who originally occupies the x-th position from the left in the line moves to the y-th position from the left, that child earns A_x \times |x-y| happiness points.

Find the maximum total happiness points the children can earn.

Constraints

2 \leq N \leq 2000

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum total happiness points the children can earn.

Sample Input 1

4
1 3 4 2

Sample Output 1

20

If we move the 1-st child from the left to the 3-rd position from the left, the 2-nd child to the 4-th position, the 3-rd child to the 1-st position, and the 4-th child to the 2-nd position, the children earns 1 \times |1-3|+3 \times |2-4|+4 \times |3-1|+2 \times |4-2|=20 happiness points in total.

Sample Input 2

6
5 5 6 1 1 1

Sample Output 2

58

Sample Input 3

6
8 6 9 1 2 1

Sample Output 3

85


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()
    N = pread(Int)
    c = sum(filter(x -> x % 3 != 0 && x % 5 != 0, 1:N))
    println(c)
end

main()

Score : 200 points

Problem Statement

Let us define the FizzBuzz sequence a_1,a_2,... as follows:

If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}.

If the above does not hold but 3 divides i, a_i=\mbox{Fizz}.

If none of the above holds but 5 divides i, a_i=\mbox{Buzz}.

If none of the above holds, a_i=i.

Find the sum of all numbers among the first N terms of the FizzBuzz sequence.

Constraints

1 \leq N \leq 10^6

Input

Input is given from Standard Input in the following format:

N

Output

Print the sum of all numbers among the first N terms of the FizzBuzz sequence.

Sample Input 1

15

Sample Output 1

60

The first 15 terms of the FizzBuzz sequence are:

1,2,\mbox{Fizz},4,\mbox{Buzz},\mbox{Fizz},7,8,\mbox{Fizz},\mbox{Buzz},11,\mbox{Fizz},13,14,\mbox{FizzBuzz}

Among them, numbers are 1,2,4,7,8,11,13,14, and the sum of them is 60.

Sample Input 2

1000000

Sample Output 2

266666333332

Watch out for overflow.


N=parse(Int,readline())
ans=0
for i=1:N
  if i%3!=0&&i%5!=0
    ans+=i
  end
end
println(ans)


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

function main()
    N = readline() |> parseInt
    count = 0
    for i in 1:N
        if i%5!=0 && i%3!=0
            count += i
        end
    end
    println(count)
end

main()


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

  is_odd = n % 2 > 0

  space = is_odd ? 4 : 3
  dp = zeros(Int, n + space, 3)

  for (i, a) in enumerate(arr)
    i += space
    dp[i, 1] = dp[i - 2, 1] + a
    dp[i, 2] = max(dp[i - 2, 2], dp[i - 3, 1]) + a
    if is_odd
      dp[i, 3] = max(dp[i - 2, 3], dp[i - 3, 2], dp[i - 4, 1]) + a
    end
  end

  n += space
  println(
    is_odd ? max(dp[n - 2, 1], dp[n - 1, 2], dp[n, 3]) : max(dp[n, 2], dp[n - 1, 1])
  )
end

main()

Score : 600 points

Problem Statement

Given is an integer sequence A_1, ..., A_N of length N.

We will choose exactly \left\lfloor \frac{N}{2} \right\rfloor elements from this sequence so that no two adjacent elements are chosen.

Find the maximum possible sum of the chosen elements.

Here \lfloor x \rfloor denotes the greatest integer not greater than x.

Constraints

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

|A_i|\leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

Print the maximum possible sum of the chosen elements.

Sample Input 1

6
1 2 3 4 5 6

Sample Output 1

12

Choosing 2, 4, and 6 makes the sum 12, which is the maximum possible value.

Sample Input 2

5
-1000 -100 -10 0 10

Sample Output 2

0

Choosing -10 and 10 makes the sum 0, which is the maximum possible value.

Sample Input 3

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

5000000000

Watch out for overflow.

Sample Input 4

27
18 -28 18 28 -45 90 -45 23 -53 60 28 -74 -71 35 -26 -62 49 -77 57 24 -70 -93 69 -99 59 57 -49

Sample Output 4

295


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

function ftAdd(ft::Array{Int,1},k::Int,x::Int)
	t = k
	n = length(ft)
	while t<=n
		ft[t] = max(ft[t],x)
		t += t&(-t)
	end
	ft
end

function ftSum(ft::Array{Int,1},rr::Int)
	r = rr
	s = 0
	while r>0
		s = max(s,ft[r])
		r -= r&(-r)
	end
	s
end

function main()
	n = readline() |> parseInt
	a = readline() |> split |> parseMap
	x = zeros(Int,n+1)
	y = zeros(Int,n+1)
	for i in 1:n
		x[i+1]=x[i]
		y[i+1]=y[i]
		if i%2==1
			x[i+1]+=a[i]
		else
			y[i+1]+=a[i]
		end
	end
	if n%2==0
		m = -10^18
		for i in 1:n
			if i%2==1
				m = max(m,x[i+1]+y[n+1]-y[i+2], y[i+1]-x[n+1]-x[i+1])
			else
				if i==n
					m = max(m,y[i+1])
				else
					m = max(m,x[i+1]+y[n+1]-y[i+1], y[i+1]-x[n+1]-x[i+2])
				end
			end
		end
		println(m)
	else
		m = y[n+1]
		for i in 1:2:n
			m = max(m,x[n+1]-a[i])
		end
		for i in 1:n-1
			if i%2==1
				m = max(m,x[i+1]+y[n+1]-y[i+3],y[i+1]+x[n+1]-x[i+3])

			else
				m = max(m,x[i+1]+y[n+1]-y[i+2],x[i+1]+y[n+1]-y[i+2])
			end
		end
		ft = zeros(Int,n)
		for i in 1:n-2
			if i%2==1
				ftAdd(ft,i,y[i]+x[n+1]-x[i+2])
			else
				ftAdd(ft,i,y[i]+x[n+1]-x[i+3])
			end
			for i in 1:n-5
				m = max(m,ftSum(ft,i)-y[i+4]+x[i+1])
			end
		end
		println(m)
	end
end

main()


let
  N, K = map(x -> parse(Int, x), readline() |> split)
  surplus = N%K
  println(min(surplus, K-surplus))
end

Score : 300 points

Problem Statement

Given any integer x, Aoki can do the operation below.

Operation: Replace x with the absolute difference of x and K.

You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.

Constraints

0 ≤ N ≤ 10^{18}

1 ≤ K ≤ 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible value taken by N after Aoki does the operation zero or more times.

Sample Input 1

7 4

Sample Output 1

1

Initially, N=7.

After one operation, N becomes |7-4| = 3.

After two operations, N becomes |3-4| = 1, which is the minimum value taken by N.

Sample Input 2

2 6

Sample Output 2

2

N=2 after zero operations is the minimum.

Sample Input 3

1000000000000000000 1

Sample Output 3

0


n,k=[parse(Int,i) for i=split(readline())]
print(min(n-k*fld(n,k),k*cld(n,k)-n))


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

function main()
    n,k=parseMap(split(readline()))
    println(min(n%k,abs(n%k-k)))
end
main()


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

function main()
N,K = parseMap(split(readline()))
if abs(N - K) > N
    println(N)
else
    if N > K
        h = N ÷ K
        N -= K * h
        ans = min(abs(N-K),N)
        println(ans)
    else
        h = K ÷ N
        K -= N * h
        ans = min(abs(N-K),K)
        println(ans)
    end
end
end

main()


function makelunlun(t)
    ret = []
    for x in t
        d = x % 10
        if d != 0
            push!(ret, 10x+d-1)
        end
        push!(ret, 10x+d)
        if d != 9
            push!(ret, 10x+d+1)
        end
    end
    ret
end

function solve(k)
    t = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    lunlun = copy(t)
    while length(lunlun) < k
        t = makelunlun(t)
        append!(lunlun, t)
    end
    sort!(lunlun)
    lunlun[k]
end

k = parse(Int, readline())
println(solve(k))

Score : 400 points

Problem Statement

A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:

In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1.

For example, 1234, 1, and 334 are lunlun numbers, while none of 31415, 119, or 13579 is.

You are given a positive integer K. Find the K-th smallest lunlun number.

Constraints

1 \leq K \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the answer.

Sample Input 1

15

Sample Output 1

23

We will list the 15 smallest lunlun numbers in ascending order:

1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
21,
22,
23.

Thus, the answer is 23.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

13

Sample Output 3

21

Sample Input 4

100000

Sample Output 4

3234566667

Note that the answer may not fit into the 32-bit signed integer type.


function nxt(Q)
  x=shift!(Q)
  if x%10>0
    push!(Q,x*10+x%10-1)
  end
  push!(Q,x*10+x%10)
  if x%10<9
    push!(Q,x*10+x%10+1)
  end
  Q
end
function main()
  Q=[1,2,3,4,5,6,7,8,9]
  for 2:parse(Int,readline())
    Q=nxt(Q)
  end
  println(Q[1])
end
main()


function makeearlieststartday(N, K, C, S)
    ret = zeros(Int, K)
    d = 1
    k = 1
    while k <= K
        if S[d] == 'o'
            ret[k] = d
            d += C + 1
            k += 1
        elseif S[d] == 'x'
            d += 1
        end
    end
    ret
end

function makelateststartday(N, K, C, S)
    ret = zeros(Int, K)
    d = N
    k = K
    while k >= 1
        if S[d] == 'o'
            ret[k] = d
            d -= C + 1
            k -= 1
        else S[d] == 'x'
            d -= 1
        end
    end
    ret
end

function solve()
    N, K, C = [parse(Int, x) for x in split(readline())]
    S = readline()

    earlieststartday = makeearlieststartday(N, K, C, S)
    lateststartday = makelateststartday(N, K, C, S)
    for (e, l) in zip(earlieststartday, lateststartday)
        if e == l
            println(e)
        end
    end
end

solve()

Score : 500 points

Problem Statement

Takahashi has decided to work on K days of his choice from the N days starting with tomorrow.

You are given an integer C and a string S. Takahashi will choose his workdays as follows:

After working for a day, he will refrain from working on the subsequent C days.

If the i-th character of S is x, he will not work on Day i, where Day 1 is tomorrow, Day 2 is the day after tomorrow, and so on.

Find all days on which Takahashi is bound to work.

Constraints

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

1 \leq K \leq N

0 \leq C \leq N

The length of S is N.

Each character of S is o or x.

Takahashi can choose his workdays so that the conditions in Problem Statement are satisfied.

Input

Input is given from Standard Input in the following format:

N K C
S

Output

Print all days on which Takahashi is bound to work in ascending order, one per line.

Sample Input 1

11 3 2
ooxxxoxxxoo

Sample Output 1

6

Takahashi is going to work on 3 days out of the 11 days. After working for a day, he will refrain from working on the subsequent 2 days.

There are four possible choices for his workdays: Day 1,6,10, Day 1,6,11, Day 2,6,10, and Day 2,6,11.

Thus, he is bound to work on Day 6.

Sample Input 2

5 2 3
ooxoo

Sample Output 2

1
5

There is only one possible choice for his workdays: Day 1,5.

Sample Input 3

5 1 0
ooooo

Sample Output 3

There may be no days on which he is bound to work.

Sample Input 4

16 4 3
ooxxoxoxxxoxoxxo

Sample Output 4

11
16


function main()
    S = readline()
    if S[3]==S[4] && S[5]==S[6]
        println("Yes")
    else
        println("No")
    end
end

main()

Score : 100 points

Problem Statement

A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.

Given a string S, determine whether it is coffee-like.

Constraints

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

Input

Input is given from Standard Input in the following format:

S

Output

If S is coffee-like, print Yes; otherwise, print No.

Sample Input 1

sippuu

Sample Output 1

Yes

In sippuu, the 3-rd and 4-th characters are equal, and the 5-th and 6-th characters are also equal.

Sample Input 2

iphone

Sample Output 2

No

Sample Input 3

coffee

Sample Output 3

Yes


n=parse(Int,readline())
a=fld(n,500)
b=fld(n-500a,5)
print(a*1000+b*5)

Score : 200 points

Problem Statement

Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.)

Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn?

(We assume that there are six kinds of coins available: 500-yen, 100-yen, 50-yen, 10-yen, 5-yen, and 1-yen coins.)

Constraints

0 \leq X \leq 10^9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the maximum number of happiness points that can be earned.

Sample Input 1

1024

Sample Output 1

2020

By exchanging his money so that he gets two 500-yen coins and four 5-yen coins, he gains 2020 happiness points, which is the maximum number of happiness points that can be earned.

Sample Input 2

0

Sample Output 2

0

He is penniless - or yenless.

Sample Input 3

1000000000

Sample Output 3

2000000000

He is a billionaire - in yen.


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

function main()
    k,n=parseMap(split(readline()))
    a=sort(parseMap(split(readline())))
    dif=[0 for i in 1:n]
    for i in 2:n
        dif[i]=a[i]-a[i-1]
    end
    dif[1]=k-a[end]+a[1]
    m=findmax(dif)[2]
    ans=0
    for i in m+1:n
        ans+=a[i]-a[i-1]
    end
    if m!=1
        ans+=k-a[end]+a[1]
        for i in 2:m-1
            ans+=a[i]-a[i-1]
        end
    end
    println(ans)
end
main()

Score : 300 points

Problem Statement

There is a circular pond with a perimeter of K meters, and N houses around them.

The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.

When traveling between these houses, you can only go around the pond.

Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Constraints

2 \leq K \leq 10^6

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

0 \leq A_1 < ... < A_N < K

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K N
A_1 A_2 ... A_N

Output

Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Sample Input 1

20 3
5 10 15

Sample Output 1

10

If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.

Sample Input 2

20 3
0 5 15

Sample Output 2

10

If you start at the 2-nd house and go to the 1-st and 3-rd houses in this order, the total distance traveled will be 10.


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

function main()
	n,x,y = readline() |> split |> parseMap
	d = zeros(Int,n)
	for i in 1:n-1
		for j in i+1:n
			if j<=x||i>=y
				d[j-i] += 1
			elseif i<=x&&j>=y
				d[j-i-y+x+1] += 1
			elseif i<=x
				d[min(j-i,y-j+x-i+1)] += 1
			elseif j>=y
				d[min(j-i,i-x+j-y+1)] += 1
			else
				d[min(j-i,y-j+i-x+1)] += 1
			end
		end
	end
	for i in 1:n-1
		println(d[i])
	end
end

main()

Score : 400 points

Problem Statement

We have an undirected graph G with N vertices numbered 1 to N and N edges as follows:

For each i=1,2,...,N-1, there is an edge between Vertex i and Vertex i+1.

There is an edge between Vertex X and Vertex Y.

For each k=1,2,...,N-1, solve the problem below:

Find the number of pairs of integers (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j in G is k.

Constraints

3 \leq N \leq 2 \times 10^3

1 \leq X,Y \leq N

X+1 < Y

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X Y

Output

For each k=1, 2, ..., N-1 in this order, print a line containing the answer to the problem.

Sample Input 1

5 2 4

Sample Output 1

5
4
1
0

The graph in this input is as follows:

There are five pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 1: (1,2)\,,(2,3)\,,(2,4)\,,(3,4)\,,(4,5).

There are four pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 2: (1,3)\,,(1,4)\,,(2,5)\,,(3,5).

There is one pair (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 3: (1,5).

There are no pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 4.

Sample Input 2

3 1 3

Sample Output 2

3
0

The graph in this input is as follows:

Sample Input 3

7 3 7

Sample Output 3

7
8
4
2
0
0

Sample Input 4

10 4 8

Sample Output 4

10
12
10
8
4
1
0
0
0


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

function main()
    n,x,y=parseMap(split(readline()))
    dis=[[j-i for j in 1:n] for i in 1:n]
    for i in 1:n
        for j in i+1:n
            dis[i][j]=min(dis[i][j],abs(i-x)+abs(j-y)+1)
        end
    end
    cnt=Dict{Int,Int}(i=>0 for i in 1:n-1)
    for i in dis
        for j in i
            if haskey(cnt,j)
                cnt[j]+=1
            end
        end
    end
    for i in 1:n-1
        println(cnt[i])
    end
end
main()


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

function moveup(x::Array{Int,1},n)
	k = length(x)
	for i in 1:k-1
		if x[k-i+1] > n-1
			x[k-i] += div(x[k-i+1],n)
			x[k-i+1] = x[k-i+1]%n
		end
	end
	if x[1] > n-1
		0
	else
		x
	end
end

function main()
	h,w,k = readline() |> split |> parseMap
	a = zeros(Int,h,w)
	bit = zeros(Int,h-1)
	for i in 1:h
		s = readline() |> chomp
		for j in 1:w
			if s[j]=='1'
				a[i,j] = 1
			end
		end
	end
	b = zeros(Int,h+1,w+1)
	for i in 1:h
		for j in 1:w
			b[i+1,j+1] = b[i,j+1]+a[i,j]
		end
	end
	for j in 1:w
		for i in 1:h
			b[i+1,j+1] += b[i+1,j]
		end
	end
	ans = 10^18
	while bit!=0
		l = 1
		lk = 0
		chk = Int[1]
		for i in 1:h-1
			if bit[i]==1
				push!(chk,i+1)
			end
		end
		push!(chk,h+1)
		for j in 1:w
			f = 0
			for i in 2:length(chk)
				if b[chk[i],j+1]-b[chk[i],l]-b[chk[i-1],j+1]+b[chk[i-1],l]>k
					f = 1
					break
				end
			end
			if f==1
				lk += 1
				l = j
			end
		end
		ans = min(ans,lk+sum(bit))
		bit[h-1] += 1
		bit = moveup(bit,2)
	end
	println(ans)
end

main()

Score : 500 points

Problem Statement

We have a chocolate bar partitioned into H horizontal rows and W vertical columns of squares.

The square (i, j) at the i-th row from the top and the j-th column from the left is dark if S_{i,j} is 0, and white if S_{i,j} is 1.

We will cut the bar some number of times to divide it into some number of blocks. In each cut, we cut the whole bar by a line running along some boundaries of squares from end to end of the bar.

How many times do we need to cut the bar so that every block after the cuts has K or less white squares?

Constraints

1 \leq H \leq 10

1 \leq W \leq 1000

1 \leq K \leq H \times W

S_{i,j} is 0 or 1.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of minimum times the bar needs to be cut so that every block after the cuts has K or less white squares.

Sample Input 1

3 5 4
11100
10001
00111

Sample Output 1

2

For example, cutting between the 1-st and 2-nd rows and between the 3-rd and 4-th columns - as shown in the figure to the left - works.

Note that we cannot cut the bar in the ways shown in the two figures to the right.

Sample Input 2

3 5 8
11100
10001
00111

Sample Output 2

0

No cut is needed.

Sample Input 3

4 10 4
1110010010
1000101110
0011101001
1101000111

Sample Output 3

3


function main()
  N,S=map(x->parse(Int,x),split(readline()))
  dp=zeros(Int,S+1)
  ans=0
  const mod=998244353
  for a=map(x->parse(Int,x),split(readline()))
    dp[1]+=1
    for i=S-a:-1:0
      dp[i+1]+=dp[i+a+1]
      if dp[i+1]>=mod
        dp[i+1]-=mod
      end
    end
    ans+=dp[S+1]
  end
  println(ans%mod)
end
main()

Score : 600 points

Problem Statement

Given are a sequence of N integers A_1, A_2, \ldots, A_N and a positive integer S.

For a pair of integers (L, R) such that 1\leq L \leq R \leq N, let us define f(L, R) as follows:

f(L, R) is the number of sequences of integers (x_1, x_2, \ldots , x_k) such that L \leq x_1 < x_2 < \cdots < x_k \leq R and A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.

Find the sum of f(L, R) over all pairs of integers (L, R) such that 1\leq L \leq R\leq N. Since this sum can be enormous, print it modulo 998244353.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq S \leq 3000

1 \leq A_i \leq 3000

Input

Input is given from Standard Input in the following format:

N S
A_1 A_2 ... A_N

Output

Print the sum of f(L, R), modulo 998244353.

Sample Input 1

3 4
2 2 4

Sample Output 1

5

The value of f(L, R) for each pair is as follows, for a total of 5.

f(1,1) = 0

f(1,2) = 1 (for the sequence (1, 2))

f(1,3) = 2 (for (1, 2) and (3))

f(2,2) = 0

f(2,3) = 1 (for (3))

f(3,3) = 1 (for (3))

Sample Input 2

5 8
9 9 9 9 9

Sample Output 2

0

Sample Input 3

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

Sample Output 3

152


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

function main()
	p = 998244353
	n,s = readline() |> split |> parseMap
	a = readline() |> split |> parseMap
	dp = zeros(Int,n,s)
	if a[1]<=s
		dp[1,a[1]] = 1
	end
	ans = dp[1,s]*n
	for i in 2:n
		if a[i]<=s
			dp[i,a[i]] += i
		end
		for j in 1:s
			if j!=s
				dp[i,j]=(dp[i,j]+dp[i-1,j])%p
			end
			if j+a[i]<=s
				dp[i,j+a[i]]=(dp[i,j+a[i]]+dp[i-1,j])%p
			end
		end
		ans = (ans+(dp[i,s]%p)*(n+1-i)%p)%p
	end
	println(ans)
end

main()


Score : 100 points

Problem Statement

Print the K-th element of the following sequence of length 32:

1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51

Constraints

1 \leq K \leq 32

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the K-th element.

Sample Input 1

6

Sample Output 1

2

The 6-th element is 2.

Sample Input 2

27

Sample Output 2

5

The 27-th element is 5.


function main()

  (H,W) = map(x -> parse(BigInt,x), split(readline()))

  ans = 0

  if H % 2 == 0
    ans += W*div(H,2)
  else
    ans += W*div(H,2)
    ans += ceil(Int,W/2)
  end

  println(ans)

end

main()

Score : 200 points

Problem Statement

We have a board with H horizontal rows and W vertical columns of squares.
There is a bishop at the top-left square on this board.
How many squares can this bishop reach by zero or more movements?

Here the bishop can only move diagonally.
More formally, the bishop can move from the square at the r_1-th row (from the top) and the c_1-th column (from the left) to the square at the r_2-th row and the c_2-th column if and only if exactly one of the following holds:

r_1 + c_1 = r_2 + c_2

r_1 - c_1 = r_2 - c_2

For example, in the following figure, the bishop can move to any of the red squares in one move:

Constraints

1 \leq H, W \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H \ W

Output

Print the number of squares the bishop can reach.

Sample Input 1

4 5

Sample Output 1

10

The bishop can reach the cyan squares in the following figure:

Sample Input 2

7 3

Sample Output 2

11

The bishop can reach the cyan squares in the following figure:

Sample Input 3

1000000000 1000000000

Sample Output 3

500000000000000000


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

function main()
	h,w = readline() |> split |> parseMap
	if h==1||w==1
		println(1)
	else
		println((h*w+1)>>1)
	end
end

main()


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

function main()
	h,w = readline() |> split |> parseMap
	println((h*w+1)>>1)
end

main()


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

function flush(a::Array{Int,1},n)
	for i in 1:n
		print(Char(a[i]+97))
	end
	println("")
end

function main()
	n = readline() |> parseInt
	a = zeros(Int,n)
	while 1==1
		if a[1]==1
			break
		end

		flush(a,n)
		a[n]+=1
		for i in n:-1:2
			mx = 0
			for j in 1:i-1
				mx = max(mx,a[j])
			end
			if a[i]>=mx+2
				a[i-1]+=1
				a[i]=a[i]%(mx+2)
			end
		end
	end
end

main()

Score : 400 points

Problem Statement

In this problem, we only consider strings consisting of lowercase English letters.

Strings s and t are said to be isomorphic when the following conditions are satisfied:

|s| = |t| holds.

For every pair i, j, one of the following holds:

s_i = s_j and t_i = t_j.

s_i \neq s_j and t_i \neq t_j.

For example, abcac and zyxzx are isomorphic, while abcac and ppppp are not.

A string s is said to be in normal form when the following condition is satisfied:

For every string t that is isomorphic to s, s \leq t holds. Here \leq denotes lexicographic comparison.

For example, abcac is in normal form, but zyxzx is not since it is isomorphic to abcac, which is lexicographically smaller than zyxzx.

You are given an integer N.
Print all strings of length N that are in normal form, in lexicographically ascending order.

Constraints

1 \leq N \leq 10

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order.
Output should be in the following format:

w_1
:
w_K

Sample Input 1

1

Sample Output 1

a

Sample Input 2

2

Sample Output 2

aa
ab


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

function return_all_pettern(x)  #bit全探索
    count_pettern = x ^ 2
    b = []
    for i in count_pettern - 2:-1:1
        bit = bin(i, x)
        bits = []
        for j in 1:x
            push!(bits, bit[j])
        end
        bits = [bits .== '1']
        push!(b, bits)
    end
    #println(length(b))
    return  b
end

function arrayprinter(A)
    for a in A
        print(a)
    end
    println("")
end

function solver(N)
    s = 'a':'x'
    #println(s)
    pettrens = return_all_pettern(N)
    flag = true
    for pettern in pettrens
        #println(pettern)
        h = 1
        ans = []
        if sum(pettern[1]) == 0 || sum(pettern[1]) == 1
            if flag == true
                arrayprinter(s[1:N])
                flag = false
            end
        else
            a_flag = pettern[1][1]
            push!(ans,'a')
            for j in 2:N
                if a_flag
                    if pettern[1][j]
                        push!(ans,'a')
                    else
                        h += 1
                        push!(ans,s[h])
                    end
                else
                    if pettern[1][j]
                        push!(ans,'b')
                    else
                        h += 1
                        push!(ans,'b')
                    end
                end
            end
            arrayprinter(ans)
        end
        #println(flag)
    end
end

if N == 1
    println("a")
elseif N == 2
    println("aa")
    println("ab")
else
    solver(N)
end


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

function main()
    s=chomp(readline())
    if length(s)%2==1 || "hi"^(length(s)÷2)!=s
        println("No")
    else
        println("Yes")
    end
end
main()

Score : 100 points

Problem Statement

A Hitachi string is a concatenation of one or more copies of the string hi.

For example, hi and hihi are Hitachi strings, while ha and hii are not.

Given a string S, determine whether S is a Hitachi string.

Constraints

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

S is a string consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a Hitachi string, print Yes; otherwise, print No.

Sample Input 1

hihi

Sample Output 1

Yes

hihi is the concatenation of two copies of hi, so it is a Hitachi string.

Sample Input 2

hi

Sample Output 2

Yes

Sample Input 3

ha

Sample Output 3

No


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

function main()
	s = readline() |> chomp
	a = String["hi","hihi","hihihi","hihihihi","hihihihihi"]
	f = 0
	for i in 1:5
		if a[i]==s
			f = 1
		end
	end
	println(f==1?"Yes":"No")
end

main()


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

function main()
    a,b,m=parseMap(split(readline()))
    ai=parseMap(split(readline()))
    bi=parseMap(split(readline()))
    rei=[0 for i in 1:a]
    den=[0 for i in 1:b]
    for i in 1:a
        rei[i]=ai[i]
    end
    for i in 1:b
        den[i]=bi[i]
    end
    sort!(ai)
    sort!(bi)
    xyc=[parseMap(split(readline())) for i in 1:m]
    ans=ai[1]+bi[1]
    for (x,y,c) in xyc
        ans=min(rei[x]+den[y]-c,ans)
    end
    println(ans)
end
main()

Score : 200 points

Problem Statement

You are visiting a large electronics store to buy a refrigerator and a microwave.

The store sells A kinds of refrigerators and B kinds of microwaves. The i-th refrigerator ( 1 \le i \le A ) is sold at a_i yen (the currency of Japan), and the j-th microwave ( 1 \le j \le B ) is sold at b_j yen.

You have M discount tickets. With the i-th ticket ( 1 \le i \le M ), you can get a discount of c_i yen from the total price when buying the x_i-th refrigerator and the y_i-th microwave together. Only one ticket can be used at a time.

You are planning to buy one refrigerator and one microwave. Find the minimum amount of money required.

Constraints

All values in input are integers.

1 \le A \le 10^5

1 \le B \le 10^5

1 \le M \le 10^5

1 \le a_i , b_i , c_i \le 10^5

1 \le x_i \le A

1 \le y_i \le B

c_i \le a_{x_i} + b_{y_i}

Input

Input is given from Standard Input in the following format:

A B M
a_1 a_2 ... a_A
b_1 b_2 ... b_B
x_1 y_1 c_1
\vdots
x_M y_M c_M

Output

Print the answer.

Sample Input 1

2 3 1
3 3
3 3 3
1 2 1

Sample Output 1

5

With the ticket, you can get the 1-st refrigerator and the 2-nd microwave for 3+3-1=5 yen.

Sample Input 2

1 1 2
10
10
1 1 5
1 1 10

Sample Output 2

10

Note that you cannot use more than one ticket at a time.

Sample Input 3

2 2 1
3 5
3 5
2 2 2

Sample Output 3

6

You can get the 1-st refrigerator and the 1-st microwave for 6 yen, which is the minimum amount to pay in this case.
Note that using a ticket is optional.


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

function main()
	ax,bx,m = readline() |> split |> parseMap
	a = readline() |> split |> parseMap
	b = readline() |> split |> parseMap
	ans = minimum(a)+minimum(b)
	for i in 1:m
		x,y,c = readline() |> split |> parseMap
		ans = min(ans,a[x]+b[y]-c)
	end
	println(ans)
end

main()


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

function main()
	n = readline() |> parseInt
	e = [Int[] for i in 1:n]
	for i in 1:n-1
		a,b = readline() |> split |> parseMap
		push!(e[a],b)
		push!(e[b],a)
	end
	chk = -ones(Int,n)
	chk[1] = 0
	stack = Int[1]
	while !isempty(stack)
		now = pop!(stack)
		for i in e[now]
			if chk[i] == -1
				push!(stack,i)
				chk[i]=(chk[now]+1)%2
			end
		end
	end
	ans = zeros(Int,n)
	z = sum(chk)
	sx = 1
	sy = 2
	sz = 3
	if sum(chk)<=div(n,3)
		for i in 1:n
			if chk[i]==1
				ans[i] = sz
				sz += 3
			else
				if sy<=n
					ans[i] = sy
					sy += 3
				elseif sx<=n
					ans[i] = sx
					sx += 3
				else
					ans[i] = sz
					sz += 3
				end
			end
		end
	elseif sum(chk)>2*div(n,3)
		for i in 1:n
			if chk[i]==0
				ans[i] = sz
				sz += 3
			else
				if sy<=n
					ans[i] = sy
					sy += 3
				elseif sx<=n
					ans[i] = sx
					sx += 3
				else
					ans[i] = sz
					sz += 3
				end
			end
		end
	else
		for i in 1:n
			if chk[i]==0
				if sx<=n
					ans[i] = sx
					sx += 3
				else
					ans[i] = sz
					sz += 3
				end
			else
				if sy<=n
					ans[i] = sy
					sy += 3
				else
					ans[i] = sz
					sz += 3
				end
			end
		end
	end
	if n == 2
		println("1 2")
	else
		for i in 1:n-1
			print(ans[i], " ")
		end
		println(ans[n])
	end
end

main()

Score : 600 points

Problem Statement

We have a tree with N vertices. The vertices are numbered 1 to N, and the i-th edge connects Vertex a_i and Vertex b_i.

Takahashi loves the number 3. He is seeking a permutation p_1, p_2, \ldots , p_N of integers from 1 to N satisfying the following condition:

For every pair of vertices (i, j), if the distance between Vertex i and Vertex j is 3, the sum or product of p_i and p_j is a multiple of 3.

Here the distance between Vertex i and Vertex j is the number of edges contained in the shortest path from Vertex i to Vertex j.

Help Takahashi by finding a permutation that satisfies the condition.

Constraints

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

1\leq a_i, b_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}

Output

If no permutation satisfies the condition, print -1.

Otherwise, print a permutation satisfying the condition, with space in between.
If there are multiple solutions, you can print any of them.

Sample Input 1

5
1 2
1 3
3 4
3 5

Sample Output 1

1 2 5 4 3

The distance between two vertices is 3 for the two pairs (2, 4) and (2, 5).

p_2 + p_4 = 6

p_2\times p_5 = 6

Thus, this permutation satisfies the condition.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
S = chomp(readline())
if S[1] == S[2] == S[3]
    println("No")
else
    println("Yes")
end

Score : 100 points

Problem Statement

In AtCoder City, there are three stations numbered 1, 2, and 3.

Each of these stations is operated by one of the two railway companies, A and B. A string S of length 3 represents which company operates each station. If S_i is A, Company A operates Station i; if S_i is B, Company B operates Station i.

To improve the transportation condition, for each pair of a station operated by Company A and one operated by Company B, there will be a bus service connecting them.

Determine if there is a pair of stations that will be connected by a bus service.

Constraints

Each character of S is A or B.

|S| = 3

Input

Input is given from Standard Input in the following format:

S

Output

If there is a pair of stations that will be connected by a bus service, print Yes; otherwise, print No.

Sample Input 1

ABA

Sample Output 1

Yes

Company A operates Station 1 and 3, while Company B operates Station 2.

There will be a bus service between Station 1 and 2, and between Station 2 and 3, so print Yes.

Sample Input 2

BBA

Sample Output 2

Yes

Company B operates Station 1 and 2, while Company A operates Station 3.

There will be a bus service between Station 1 and 3, and between Station 2 and 3, so print Yes.

Sample Input 3

BBB

Sample Output 3

No

Company B operates all the stations. Thus, there will be no bus service, so print No.


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

function main()
	n,a,b = readline() |> split |> parseMap
	x = div(n,a+b)
	y = min(n%(a+b),a)
	println(x*a+y)
end

main()

Score : 200 points

Problem Statement

Takahashi has many red balls and blue balls. Now, he will place them in a row.

Initially, there is no ball placed.

Takahashi, who is very patient, will do the following operation 10^{100} times:

Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.

How many blue balls will be there among the first N balls in the row of balls made this way?

Constraints

1 \leq N \leq 10^{18}

A, B \geq 0

0 < A + B \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the number of blue balls that will be there among the first N balls in the row of balls.

Sample Input 1

8 3 4

Sample Output 1

4

Let b denote a blue ball, and r denote a red ball. The first eight balls in the row will be bbbrrrrb, among which there are four blue balls.

Sample Input 2

8 0 4

Sample Output 2

0

He placed only red balls from the beginning.

Sample Input 3

6 2 4

Sample Output 3

2

Among bbrrrr, there are two blue balls.


ParseInt(x) = parse(Int,x)
parseMap(x::Array{SubString{String},1}) = map(ParseInt,x)
a,b = parseMap(split(readline()))
c = 0
for i in 1:1000
    if floor(i * 0.08) == a && floor(i * 0.10) == b
        println(i)
        c = -1
        break
    end
end
if c == 0
    println(-1)
end

Score : 300 points

Problem Statement

Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.)

Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded down to the nearest integer.

If multiple prices satisfy the condition, print the lowest such price; if no price satisfies the condition, print -1.

Constraints

1 \leq A \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If there is a price that satisfies the condition, print an integer representing the lowest such price; otherwise, print -1.

Sample Input 1

2 2

Sample Output 1

25

If the price of a product before tax is 25 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 25 \times 0.08 \rfloor = \lfloor 2 \rfloor = 2 yen.

When the consumption tax rate is 10 percent: \lfloor 25 \times 0.1 \rfloor = \lfloor 2.5 \rfloor = 2 yen.

Thus, the price of 25 yen satisfies the condition. There are other possible prices, such as 26 yen, but print the minimum such price, 25.

Sample Input 2

8 10

Sample Output 2

100

If the price of a product before tax is 100 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 100 \times 0.08 \rfloor = 8 yen.

When the consumption tax rate is 10 percent: \lfloor 100 \times 0.1 \rfloor = 10 yen.

Sample Input 3

19 99

Sample Output 3

-1

There is no price before tax satisfying this condition, so print -1.


parseInt(x) = parse(Int, x)

function main()
    N = parseInt.(split(readline()))[1]
    println(Int(ceil(N / 2)))
end
main()

Score : 100 points

Problem Statement

Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.

At least how many sheets of paper does he need?

Constraints

N is an integer.

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

5

Sample Output 1

3

By printing the 1-st, 2-nd pages on the 1-st sheet, 3-rd and 4-th pages on the 2-nd sheet, and 5-th page on the 3-rd sheet, we can print all the data on 3 sheets of paper.

Sample Input 2

2

Sample Output 2

1

Sample Input 3

100

Sample Output 3

50


in_1() = parse(Int, readline())
in_a() = [parse(Int,s) for s in split(readline())]
yesno(b) = b ? "Yes" : "No"
function main()
  A = reshape(vcat(in_a(),in_a(), in_a()), 3, 3) |> transpose
  N = in_1()
  c = fill(false, 3, 3)
  for _ in 1:N
    b = in_1()
    c[A .== b] = true
  end
  res = all(c[:,1]) || all(c[:,2]) || all(c[:,3]) ||
        all(c[1,:]) || all(c[2,:]) || all(c[3,:]) ||
        all(diag(c)) || (c[1,3] && c[2,2] && c[3,1])
  res |> yesno |> println
end

isempty(ARGS) && main()

Score : 200 points

Problem Statement

We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.

The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.

Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.

Constraints

All values in input are integers.

1 \leq A_{i, j} \leq 100

A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))

1 \leq N \leq 10

1 \leq b_i \leq 100

b_i \neq b_j (i \neq j)

Input

Input is given from Standard Input in the following format:

A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N

Output

If we will have a bingo, print Yes; otherwise, print No.

Sample Input 1

84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30

Sample Output 1

Yes

We will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal from the top-left to the bottom-right.

Sample Input 2

41 7 46
26 89 2
78 92 8
5
6
45
16
57
17

Sample Output 2

No

We will mark nothing.

Sample Input 3

60 88 34
92 41 43
65 73 48
10
60
43
88
11
48
73
65
41
92
34

Sample Output 3

Yes

We will mark all the squares.


Score : 600 points

Problem Statement

Takahashi wants to grill N pieces of meat on a grilling net, which can be seen as a two-dimensional plane. The coordinates of the i-th piece of meat are \left(x_i, y_i\right), and its hardness is c_i.

Takahashi can use one heat source to grill the meat. If he puts the heat source at coordinates \left(X, Y\right), where X and Y are real numbers, the i-th piece of meat will be ready to eat in c_i \times \sqrt{\left(X - x_i\right)^2 + \left(Y-y_i\right)^2} seconds.

Takahashi wants to eat K pieces of meat. Find the time required to have K or more pieces of meat ready if he put the heat source to minimize this time.

Constraints

All values in input are integers.

1 \leq N \leq 60

1 \leq K \leq N

-1000 \leq x_i , y_i \leq 1000

\left(x_i, y_i\right) \neq \left(x_j, y_j\right) \left(i \neq j \right)

1 \leq c_i \leq 100

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1 c_1
\vdots
x_N y_N c_N

Output

Print the answer.

It will be considered correct if its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

4 3
-1 0 3
0 0 3
1 0 2
1 1 40

Sample Output 1

2.4

If we put the heat source at \left(-0.2, 0\right), the 1-st, 2-nd, and 3-rd pieces of meat will be ready to eat within 2.4 seconds. This is the optimal place to put the heat source.

Sample Input 2

10 5
-879 981 26
890 -406 81
512 859 97
362 -955 25
128 553 17
-885 763 2
449 310 57
-656 -204 11
-270 76 40
184 170 16

Sample Output 2

7411.2252


const N,K=map(x->parse(Int,x),split(readline()))
const X=Float64[]
const Y=Float64[]
const C=Float64[]
for _=1:N
	x,y,c=map(x->parse(Float64,x),split(readline()))
	push!(X,x)
	push!(Y,y)
	push!(C,c)
end
function check(M)
	A=Pair{Float64,Float64}[]
	for i=1:N
		push!(A,X[i]=>Y[i])
	end
	r=[M/c for c=C]
	for i=1:N,j=i+1:N
		d=sqrt((X[i]-X[j])^2+(Y[i]-Y[j])^2)
		ri=r[i]
		rj=r[j]
		if d<abs(ri-rj)||ri+rj<d
			continue
		end
		a=acos((ri^2+d^2-rj^2)/(2*ri*d))
		t=atan2(Y[j]-Y[i],X[j]-X[i])
		push!(A,X[i]+ri*cos(t+a)=>Y[i]+ri*sin(t+a))
		push!(A,X[i]+ri*cos(t-a)=>Y[i]+ri*sin(t-a))
	end
	ret=false;
	for (x,y)=A
		cnt=0
		for i=1:N
			if sqrt((X[i]-x)^2+(Y[i]-y)^2)<r[i]+1e-10
				cnt+=1
			end
		end
		if cnt>=K
			ret=true
		end
	end
	ret
end
function main()
	L=0
	R=1e9
	for _=1:100
		M=(L+R)/2
		if check(M)
			R=M
		else
			L=M
		end
	end
	println(R)
end
main()


Score : 100 points

Problem Statement

Takahashi is a member of a programming competition site, ButCoder.

Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.

The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inner Rating minus 100 \times (10 - K) when the member has participated in K contests.

Takahashi has participated in N contests, and his Displayed Rating is R. Find his Inner Rating.

Constraints

All values in input are integers.

1 \leq N \leq 100

0 \leq R \leq 4111

Input

Input is given from Standard Input in the following format:

N R

Output

Print his Inner Rating.

Sample Input 1

2 2919

Sample Output 1

3719

Takahashi has participated in 2 contests, which is less than 10, so his Displayed Rating is his Inner Rating minus 100 \times (10 - 2) = 800.

Thus, Takahashi's Inner Rating is 2919 + 800 = 3719.

Sample Input 2

22 3051

Sample Output 2

3051


N=parse(Int,readline())
K=split(readline())
Xi=map(x->parse(Int,x),K)

minP=N*100^2
for i in 1:100
    ss=0
    for j in 1:N
        ss+=(Xi[j]-i)^2
    end
    if ss < minP
        minP = ss
#        println("min",ss)
    end
end

print(minP)


quit() = exit(0)
in_1() = parse(Int, readline())
in_a() = [parse(Int,s) for s in split(readline())]
in_t() = (in_a()...,)
yesno(b) = b ? "Yes" : "No"

function main()
  N, K = in_a()
  ans = 0
  while N > 0
    ans += 1
    N = div(N, K)
  end
  ans |> println
end

isempty(ARGS) && main()

Score : 200 points

Problem Statement

Given is an integer N. Find the number of digits that N has in base K.

Notes

For information on base-K representation, see Positional notation - Wikipedia.

Constraints

All values in input are integers.

1 \leq N \leq 10^9

2 \leq K \leq 10

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of digits that N has in base K.

Sample Input 1

11 2

Sample Output 1

4

In binary, 11 is represented as 1011.

Sample Input 2

1010101 10

Sample Output 2

7

Sample Input 3

314159265 3

Sample Output 3

18


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

function main()
	n,k = readline() |> split |> parseMap
	x = 0
	while n>0
		n=div(n,k)
		x += 1
	end
	println(x)
end

main()


N,K=split(readline())
N=parse(Int,N)
K=parse(Int,K)
#print(R)

nth=1
for i in 1:200
    if div(N,K^i)>0
        nth+=1
    else
        break
    end
end
print(nth)