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

function main()
	s = split(chomp(readline()),"")
	k = readline() |> parseInt
	l = length(s)
	t = 0
	tf = 0
	for i in 2:l-1
		if s[i] == s[i-1]
			t += 1
			s[i] = string(i)
			if i==2
				tf = 1
			end
		end
	end
	if s[1]==s[l]
		if tf == 0
			t += 1
		elseif s[l-1]==s[l]
			t += 1
		end
	end
	println(t*k)
end

main()


using DataStructures
parseline(str=readline()) = parse.(Int, split(str))
function PowerfulDiscountTickets()
    N, M = parseline()
    que = PriorityQueue{Int, Int}(Base.Order.Reverse)
    for a in parseline()
        if !haskey(que, a)
            que[a] = 1
        else
            que[a] += 1
        end
    end
    for m in 1:M
        p = peek(que).first
        if que[p]==1
            dequeue!(que)
        else
            que[p] -= 1
        end
        q = p ÷ 2
        if haskey(que, q)
            que[q] += 1
        else
            enqueue!(que, q, 1)
        end
    end
    println(sum([x.first * x.second for x in que.xs]))
end
PowerfulDiscountTickets()

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

Score : 400 points

Problem Statement

Takahashi is going to buy N items one by one.

The price of the i-th item he buys is A_i yen (the currency of Japan).

He has M discount tickets, and he can use any number of them when buying an item.

If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nearest integer) yen.

What is the minimum amount of money required to buy all the items?

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the minimum amount of money required to buy all the items.

Sample Input 1

3 3
2 13 8

Sample Output 1

9

We can buy all the items for 9 yen, as follows:

Buy the 1-st item for 2 yen without tickets.

Buy the 2-nd item for 3 yen with 2 tickets.

Buy the 3-rd item for 4 yen with 1 ticket.

Sample Input 2

4 4
1 9 3 5

Sample Output 2

6

Sample Input 3

1 100000
1000000000

Sample Output 3

0

We can buy the item priced 1000000000 yen for 0 yen with 100000 tickets.

Sample Input 4

10 1
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 4

9500000000

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.


parseline(str=readline()) = parse.(Int, split(str))
function PowerfulDiscountTickets()
    N, M = parseline()
    A = float.(sort(parseline()))
    i = N
    for m in 1:M
        A[i] /= 2.0
        for n in N:-1:1
            A[i]<A[n] && (i=n;break)
        end
    end
    println(sum(floor.(Int, A)))
end
PowerfulDiscountTickets()


parseline(str=readline()) = parse.(Int, split(str))
function PowerfulDiscountTickets()
    N, M = parseline()
    A = float.(sort(parseline()))
    i = N
    for m in 1:M
        A[i] /= 2.0
        if (i>1) && (A[i]<A[i-1])
            i -= 1
        end
    end
    println(sum(floor.(Int, A)))
end
PowerfulDiscountTickets()


parseline(str=readline()) = parse.(Int, split(str))
function PowerfulDiscountTickets()
    N, M = parseline()
    A = float.(parseline())
    for m in 1:M
        i = argmax(A)
        A[i] /= 2.0
    end
    println(sum(floor.(Int, A)))
end
PowerfulDiscountTickets()


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,m=parseMap(split(readline()))
    a=sort(parseMap(split(readline())))
    l,r=1,10^10
    x=0                 # 答え
    while r-l>1
        i=l+(r-l)÷2     # 割引券を使う基準となる価格
        d=m             # 割引券の数
        k=0             # 何円必要か
        for j in 1:n
            num=a[j]
            while i<=num
                num÷=2
                d-=1
            end
            k+=num
        end
        if d>=0
            x=k-i÷2*d
            r=i         # d>=0のとき(割引券があまった/ピッタリのとき)は基準を下げる
        else
            l=i         # d<0のとき(割引券が足りなかったとき)は基準を上げる
        end
    end
    println(max(x,0))
end
main()


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

function main()
    n,m=parseMap(split(readline()))
    a=sort(parseMap(split(readline())))
    l,r=1,1<<30
    x=0
    while r-l>1
        i=l+(r-l)>>1
        d=m
        k=0
        for j in 1:n
            num=a[j]
            while i<=num
                num÷=2
                d-=1
            end
            k+=num
        end
        if d>=0
            r=i
            x=k-i÷2*d
        else
            l=i
        end
    end
    if x>0
        println(x)
    else
        println(0)
    end
end
main()


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

function main()
    n,m=parseMap(split(readline()))
    a=parseMap(split(readline()))
    for i in 1:m
        key=findmax(a)[2]
        a[key]÷=2
    end
    println(sum(a))
end
main()


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

function main()
    n,m=parseMap(split(readline()))
    a=parseMap(split(readline()))
    dict_a=Dict{Int,Int}()
    for i in a
        if haskey(dict_a,i)
            dict_a[i]+=1
        else
            dict_a[i]=1
        end
    end
    for i in 1:m
        # v0.5では(最大key=>個数,個数)を返す？
        key=findmax(dict_a)[1][1]
        if dict_a[key]>1
            dict_a[key]-=1
        else
            delete!(dict_a,key)
        end
        key÷=2
        if haskey(dict_a,key)
            dict_a[key]+=1
        else
            dict_a[key]=1
        end
    end
    ans=0
    for i in keys(dict_a)
        ans+=i*dict_a[i]
    end
    println(ans)
end
main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
#Int 最大値
function heap(a::Array{Int,1})
	h = Float64[a[1]]
	for i in 2:length(a)
		hpush(h,a[i])
	end
	h
end

function hpush(h::Array{Float64,1},x)
	push!(h,x)
	l = length(h)
	if l>1
		k = div(l,2)
		while h[k]<x&&k>=1
			tmp = h[k]
			h[k] = x
			h[l] = tmp
			k = max(div(k,2),1)
			l = div(l,2)
		end
	end
end

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

function main()
	n,m = readline() |> split |> parseMap
	a = readline() |> split |> parseMap
	h = heap(a)
	for i in 1:m
		t = hpop(h)
		t /=2
		hpush(h,t)
	end
	s = 0
	for i in 1:n
		s += floor(Int, h[i])
	end
	println(s)
end

main()


using Base.Collections
function main()
	N,M=map(x->parse(Int,x),split(readline()))
	P=PriorityQueue(Int,Int)
	id=0
	for a=map(x->parse(Int,x),split(readline()))
		P[id+=1]=-a
	end
	for _=1:M
		id,a=peek(P)
		dequeue!(P)
		P[id]=-((-a)>>1)
	end
	ans=0
	while !isempty(P)
		id,a=peek(P)
		ans-=a
		dequeue!(P)
	end
	println(ans)
end
main()


function main()
	N,M=map(x->parse(Int,x),split(readline()))
	A=map(x->parse(Int,x),split(readline()))
	L=0
	R=10^9
	while R-L>1
		M=div(L+R,2)
		cnt=0
		for a=A
			cnt+=ceil(Int,log2(a/M))
		end
		if cnt<=M
			R=M
		else
			L=M
		end
	end
	ans=0
	for a=A
		while M>0&&a>R
			M-=1
			a>>=1
		end
		ans+=a
	end
	println(ans)
end
main()


myparse(x)=parse(Int,x)
function read_line()
N,M=myparse.(split(readline()))
A=myparse.(split(readline()))
return N,M,A
end

N,M,A=read_line()

function get_ans()
for i in 1:M
  max_A=findmax(A)
  print(max_A)
  A[max_A[2]]=div(max_A[1],2)
  println(A)
end
return A
end
res=get_ans()
println(sum(res))


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
mod(x::Int,p::Int)=x%p>0?x%p:x%p+p

function main()
	p = 92709568269121
	n = readline() |> parseInt
	t = readline() |> chomp
	s = zeros(Int,n)
	for i in 1:n
		s[i] = Int(t[i])
	end
	b = 101
	c = zeros(Int,n>>1+1)
	c[1] = 1
	for i in 1:n>>1
		c[i+1] = c[i]*b%p
	end
	ll = 0
	rr = n>>1+1
	while rr-ll>1
		i = (ll+rr)>>1
		f = 0
		set = Set{Int}([])
		arch = Int[0 for i in 1:n-i+1]
		l = 0
		for j in 1:i
			l = mod(l+s[j]*c[i-j+1],p)
		end
		arch[1] = l
		for j in 2:n-i+1
			l = mod(mod(mod(l-s[j-1]*c[i],p)*b,p)+s[j+i-1],p)
			arch[j] = l
			if j>i
				push!(set,arch[j-i])
			end
			if l in set
				f = 1
				break
			end
		end
		if f == 1
			ll = i
		else
			rr = i
		end
	end
	println(ll)
end

main()

Score : 500 points

Problem Statement

Given is a string S of length N.

Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.

More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:

l_1 + len \leq l_2

S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)

If there is no such integer len, print 0.

Constraints

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

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.

Sample Input 1

5
ababa

Sample Output 1

2

The strings satisfying the conditions are: a, b, ab, and ba. The maximum length among them is 2, which is the answer.
Note that aba occurs twice in S as contiguous substrings, but there is no pair of integers l_1 and l_2 mentioned in the statement such that l_1 + len \leq l_2.

Sample Input 2

2
xy

Sample Output 2

0

No non-empty string satisfies the conditions.

Sample Input 3

13
strangeorange

Sample Output 3

5


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
mod(x::Int,p::Int)=x%p>0?x%p:x%p+p

function main()
	p = 10^9+9
	n = readline() |> parseInt
	t = readline() |> chomp
	s = zeros(Int,n)
	for i in 1:n
		s[i] = Int(t[i])
	end
	b = 101
	c = zeros(Int,n>>1+1)
	c[1] = 1
	for i in 1:n>>1
		c[i+1] = c[i]*b%p
	end
	ll = 0
	rr = n>>1+1
	while rr-ll>1
		i = (ll+rr)>>1
		f = 0
		set = Set{Int}([])
		arch = Int[0 for i in 1:n-i+1]
		l = 0
		for j in 1:i
			l = mod(l+s[j]*c[i-j+1],p)
		end
		arch[1] = l
		for j in 2:n-i+1
			l = mod(mod(mod(l-s[j-1]*c[i],p)*b,p)+s[j+i-1],p)
			arch[j] = l
			if j>i
				push!(set,arch[j-i])
			end
			if l in set
				f = 1
				break
			end
		end
		if f == 1
			ll = i
		else
			rr = i
		end
	end
	println(ll)
end

main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
mod(x::Int,p::Int)=x%p>0?x%p:x%p+p
smod(a::Int,b::Int,c::Int,d::Int,e::Int,f::Int)=mod(mod(mod(a-b*c,d)*e,d)+f,d)

function main()
	p = 10^9+9
	n = readline() |> parseInt
	t = readline() |> chomp
	s = zeros(Int,n)
	for i in 1:n
		s[i] = Int(t[i])
	end
	b = 101
	c = zeros(Int,n>>1+1)
	c[1] = 1
	for i in 1:n>>1
		c[i+1] = c[i]*b%p
	end
	ll = 0
	rr = n>>1+1
	while rr-ll>1
		i = (ll+rr)>>1
		f = 0
		for j in 1:n-2*i
			l = 0
			for k in 1:i
				l = mod(l+s[j+k-1]*c[i-k+1],p)
			end
			r = 0
			for k in 1:i
				r = mod(r+s[i+j+k-1]*c[i-k+1],p)
			end
			if l==r
				f = 1
			end
			for k in j+2*i:n
				r = smod(r,s[k-i],c[i],p,b,s[k])
				if l==r
					f = 1
					break
				end
			end
		end
		if f == 1
			ll = i
		else
			rr = i
		end
	end
	println(ll)
end

main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
mod(x::Int,p::Int)=x%p>0?x%p:x%p+p

function main()
	p = 10^9+7
	n = readline() |> parseInt
	t = readline() |> chomp
	s = zeros(Int,n)
	for i in 1:n
		s[i] = Int(t[i])
	end
	b = 101
	c = zeros(Int,n>>1+1)
	c[1] = 1
	for i in 1:n>>1
		c[i+1] = c[i]*b%p
	end
	ll = 0
	rr = n>>1+1
	while rr-ll>1
		i = (ll+rr)>>1
		f = 0
		for j in 1:n-2*i
			l = 0
			for k in 1:i
				l = mod(l+s[j+k-1]*c[i-k+1],p)
			end
			r = 0
			for k in 1:i
				r = mod(r+s[i+j+k-1]*c[i-k+1],p)
			end
			if l==r
				f = 1
			end
			for k in j+2*i:n
				r = mod(mod(mod(r-s[k-i]*c[i],p)*b,p)+s[k],p)
				if l==r
					f = 1
				end
			end
		end
		if f == 1
			ll = i
		else
			rr = i
		end
	end
	println(rr-1)
end

main()


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

function main()
	p = 10^9+7
	n = readline() |> parseInt
	s = readline() |> chomp
	b = 101
	c = zeros(Int,n>>1+1)
	c[1] = 1
	for i in 1:n>>1
		c[i+1] = c[i]*b%p
	end
	ll = 0
	rr = n>>1+1
	while rr-ll>1
		i = (ll+rr)>>1
		f = 0
		for j in 1:n-2*i
			l = 0
			for k in 1:i
				l = mod(l+Int(s[j+k-1])*c[i-k+1],p)
			end
			r = 0
			for k in 1:i
				r = mod(r+Int(s[i+j+k-1])*c[i-k+1],p)
			end
			if l==r
				f = 1
			end
			for k in j+2*i:n
				r = mod(mod(mod(r-Int(s[k-i])*c[i],p)*b,p)+Int(s[k]),p)
				if l==r
					f = 1
				end
			end
		end
		if f == 1
			ll = i
		else
			rr = i
		end
	end
	println(rr-1)
end

main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
mod(i,p)=i%p>0?i%p:i%p+p

function main()
	p = 10^9+7
	n = readline() |> parseInt
	t = readline() |> chomp
	s = zeros(Int,n)
	for i in 1:n
		s[i]=Int(t[i])
	end
	b = 101
	c = zeros(Int,n>>1+1)
	c[1] = 1
	for i in 1:n>>1
		c[i+1] = c[i]*b%p
	end
	m = 0
	for i in 1:n>>1
		for j in 1:n-2*i
			l = 0
			for k in 1:i
				l = mod(l+s[j+k-1]*c[i-k+1],p)
			end
			r = 0
			for k in 1:i
				r = mod(r+s[i+j+k-1]*c[i-k+1],p)
			end
			if l==r
				m = max(m,i)
			end
			for k in j+2*i:n
				r = mod(mod(mod(r-s[k-i]*c[i],p)*b,p)+s[k],p)
				if l==r
					m = max(m,i)
				end
			end
		end
	end
	println(m)
end

main()


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

function main()
	p = 10^9+7
	n = readline() |> parseInt
	s = readline() |> chomp
	b = 101
	c = zeros(Int,n>>1+1)
	c[1] = 1
	for i in 1:n>>1
		c[i+1] = c[i]*b%p
	end
	m = 0
	for i in 1:n>>1
		for j in 1:n-2*i
			l = 0
			for k in 1:i
				l = mod(l+Int(s[j+k-1])*c[i-k+1],p)
			end
			r = 0
			for k in 1:i
				r = mod(r+Int(s[i+j+k-1])*c[i-k+1],p)
			end
			if l==r
				m = max(m,i)
			end
			for k in j+2*i:n
				r = mod(mod(mod(r-Int(s[k-i])*c[i],p)*b,p)+Int(s[k]),p)
				if l==r
					m = max(m,i)
				end
			end
		end
	end
	println(m)
end

main()


function f(s)
	N=length(s)
	ret=zeros(Int,N)
	ret[1]=N
	i=1
	j=0
	while i<N
		while i+j<N&&s[j+1]==s[i+j+1]
			j+=1
		end
		ret[i+1]=j
		if j==0
			i+=1
			continue
		end
		k=1
		while i+k<N&&k+ret[k+1]<j
			ret[i+k+1]=ret[k+1]
			k+=1
		end
		i+=k
		j-=k
	end
	ret
end
function main()
	N=parse(Int,readline())
	s=chomp(readline())
	ans=0
	for i=1:N
		A=f(s[i:end])
		for j=0:N-i
			ans=max(ans,min(j,A[j+1]))
		end
	end
	println(ans)
end
main()


N=parse(Int,readline())
S=readline()
S="?"*S
#dp=[[0 for j in range(N+1)]for i in range(N+1)]
dp=zeros(Int,N+1,N+1)
res=0
for l in 2:N
    for r in (l+res):(N+1)
        global res
        if S[l]==S[r]

            dp[l,r]=min(dp[l-1,r-1]+1,r-l)
            res=max(res,dp[l,r])
        else
            #println(l,r)
            #println(dp)
            dp[l,r]=0
        end
    end
end

print(res)


N=parse(Int,readline())
S=readline()
S="?"*S
#dp=[[0 for j in range(N+1)]for i in range(N+1)]
dp=zeros(Int,N+1,N+1)
for l in 2:N
    for r in (l+1):(N+1)
        if S[l]==S[r]

            dp[l,r]=min(dp[l-1,r-1]+1,r-l)
        else
            #println(l,r)
            #println(dp)
            dp[l,r]=0
        end
    end
end

res=-1
for sdp in dp
    global res
    res=max(res,max(sdp))
end
print(res)


Score : 100 points

Problem Statement

You will be given an integer a and a string s consisting of lowercase English letters as input.

Write a program that prints s if a is not less than 3200 and prints red if a is less than 3200.

Constraints

2800 \leq a < 5000

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

Each character of s is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

a
s

Output

If a is not less than 3200, print s; if a is less than 3200, print red.

Sample Input 1

3200
pink

Sample Output 1

pink

a = 3200 is not less than 3200, so we print s = pink.

Sample Input 2

3199
pink

Sample Output 2

red

a = 3199 is less than 3200, so we print red.

Sample Input 3

4049
red

Sample Output 3

red

a = 4049 is not less than 3200, so we print s = red.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    a=parseInt(readline())
    s=chomp(readline())
    println(ifelse(a>=3200,s,"red"))
end
main()


function main()
    a = parse(Int, readline())
    s = readline() |> chomp
    if a >= 3200
        println(s)
    else
        println("red")
    end
end

main()


function main()

  a = parse(Int,readline())
  s = chomp(readline())

  if a >= 3200
    println(s)
  else
    println("red")
  end

end

main()


function main()

  a = parse(Int,readline())
  s = chomp(readline())

  if a < 3200
    println(s)
  else
    println("red")
  end

end

main()


a = parse(Int32, strip(readline()))
s = strip(readline())
if a >= 3200
    println(s)
else
    println("red")
end


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

function main()
  a = readline() |> parseInt
  s = readline() |> strip

  println(a>=3200?s:"red")
end

main()


parseInt(x) = parse(Int,x)

function main()
  a = parseInt(readline())
  s = chomp(readline())
  a >= 3200 ? println(s) : println("red")
end

main()


parseInt(x) = parse(Int,x)

function main()
  a = parseInt(readline())
  s = chomp(readline())
  a >= 3200 ? println(s) : println("red")
end


a=parse(Int,readline())
b=chomp(readline())
if a >= 3200
  print(b)
else
  print("red")
end


a=parse(readline())
s=readline()
if a<3200
  println("red")
else
  println(s)
end


parseline(str=readline()) = parse.(Int, split(str))
function Ki()
    N, Q = parseline()
    tree = [Int[] for _ in 1:N]
    score = zeros(Int, N)
    for _ in 1:N-1
        a, b = parseline()
        push!(tree[a], b)
        push!(tree[b], a)
    end
    for _ in 1:Q
        p, x = parseline()
        score[p] += x
    end
    que = [1]
    seen = fill(false, N)
    seen[1] = true
    while !isempty(que)
        parent = popfirst!(que)
        for child in tree[parent]
            if !seen[child]
                score[child] += score[parent]
                push!(que, child)
                seen[child] = true
            end
        end
    end
    for s in score
        print(s, " ")
    end
end
Ki()

Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

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

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

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

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

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

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

Sample Output 2

20 20 20 20 20 20


# Jasmine_ss's code modufied by centipede_human

parseline(str=readline()) = parse.(Int, split(str))
function Ki()
    N, Q = parseline()
    tree = [Int[] for n in 1:N]
    score = zeros(Int, N)
    for _ in 1:N-1
        a, b = parseline()
        push!(tree[a], b)
        push!(tree[b], a)
    end
    for _ in 1:Q
        p, x = parseline()
        score[p] += x
    end
    seen = zeros(Bool,N)
    que = [1]; seen[1] = true
    while !isempty(que)
        parent = popfirst!(que)
        for child in tree[parent]
            seen[child] && continue
            seen[child] = true
            score[child] += score[parent]
            push!(que, child)
        end
    end
    for s in score
        print(s, " ")
    end
end
Ki()


 readInt() = parse.(Int,split(readline()))

function dfs(G,v,p,cnt)
    for u in G[v]
        u==p && continue
        cnt[u]+=cnt[v]
        dfs(G,u,v,cnt)
    end
end

function solve()
    N,Q = readInt()
    cnt = zeros(Int,N)
    G = Vector{Vector{Int}}(undef,N)
    for i in 1:N
        G[i] = Vector{Int}(undef,0)
    end
    for i in 1:N-1
        a,b = readInt()
        push!(G[a],b)
        # push!(G[b],a)
    end
    for i in 1:Q
        p,x = readInt()
        cnt[p]+=x
    end
    dfs(G,1,0,cnt)
    for i in 1:N
        println(cnt[i])
    end
end
solve()


 readInt() = parse.(Int,split(readline()))

function dfs(G,v,p,cnt)
    for u in G[v]
        u==p && continue
        cnt[u]+=cnt[v]
        dfs(G,u,v,cnt)
    end
end

function solve()
    N,Q = readInt()
    cnt = zeros(Int,N)
    G = Vector{Vector{Int}}(undef,N)
    for i in 1:N
        G[i] = Vector{Int}(undef,0)
    end
    for i in 1:N-1
        a,b = readInt()
        push!(G[a],b)
        push!(G[b],a)
    end
    for i in 1:Q
        p,x = readInt()
        cnt[p]+=x
    end
    dfs(G,1,0,cnt)
    for i in 1:N
        println(cnt[i])
    end
end
solve()


parseline(str=readline()) = parse.(Int, split(str))
function Ki()
    N, Q = parseline()
    tree = [Int[] for n in 1:N]
    score = zeros(Int, N)
    for _ in 1:N-1
        a, b = parseline()
        push!(tree[a], b)
    end
    for _ in 1:Q
        p, x = parseline()
        score[p] += x
    end
    que = tree[1]
    while !isempty(que)
        node = popfirst!(que)
        score[node] += x
        for c in tree[node]
            push!(que, c)
        end
    end
    for s in score
        print(s, " ")
    end
end
Ki()


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

function main()
  n, q = readline() |> split |> parseArray
  # e = Array{Set{Int}, 1}(undef, n)
  e = Array{Set{Int}, 1}(n)
  for i in 1:n
    e[i] = Set{Int}()
  end
  for i in 1:n-1
    a, b = readline() |> split |> parseArray
    union!(e[a], [b])
    union!(e[b], [a])
  end

  v = zeros(Int, n)
  for i in 1:q
    p, x = readline() |> split |> parseArray
    v[p] += x
  end

  function loop(i, j)
    for k in setdiff(e[i], [j])
      v[k] += v[i]
      loop(k, i)
    end
  end
  loop(1, 0)

  print(v[1])
  for i in 2:n
    print(" ")
    print(v[i])
  end
  println("")
end

main()


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

function main()
  n, q = readline() |> split |> parseArray
  # e = Array{Set{Int}, 1}(undef, n)
  e = Array{Set{Int}, 1}(n)
  for i in 1:n
    e[i] = Set{Int}()
  end
  for i in 1:n-1
    a, b = readline() |> split |> parseArray
    union!(e[a], [b])
    union!(e[b], [a])
  end

  v = zeros(Int, n)
  for i in 1:q
    p, x = readline() |> split |> parseArray
    v[p] += x
  end

  function loop(i, j)
    e′ = setdiff(e[i], [j])
    isempty(e′) && return
    for k in e′
      v[k] += v[i]
      loop(k, i)
    end
  end
  loop(1, 1)

  # i = 1
  # while true
  #   e′ = setdiff(e[i], [i])
  #   length(e′) == 0 && break
  #   for j in e′
  #     v[j] += v[i]
  #     loop(j)
  #   end
  # end

  print(v[1])
  for i in 2:n
    print(" ")
    print(v[i])
  end
  println("")
end

main()


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

n,q=parseMap(split(readline()))
con=[[] for i in 1:n]       # 要素同士のつながりを表す配列
ans=zeros(Int,1,n)          # 各要素の数

# 子のカウンタに親のカウンタの値を足していく関数
function dfs(q,oya)
    for child in con[q]
        if child==oya
            continue
        end
        ans[child]+=ans[q]
        dfs(child,q)
    end
end

function main()
    for i in 1:n-1
        a,b=parseMap(split(readline()))
        push!(con[a],b)
        push!(con[b],a)
    end
    for i in 1:q
        p,x=parseMap(split(readline()))
        ans[p]+=x
    end
    dfs(1,-1)
    println(join(ans," "))
end
main()


function main()
const lines=readlines()
const N,Q=map(x->parse(Int,x),split(shift!(lines)))
const G=[Int[] for _=1:N]
const C=zeros(Int,N)
for i=2:N
	a,b=map(x->parse(Int,x),split(shift!(lines)))
	push!(G[a],b)
	push!(G[b],a)
end
for i=1:Q
	p,x=map(x->parse(Int,x),split(shift!(lines)))
	C[p]+=x
end
function dfs(u,p)
	for v=G[u]
		if v!=p
			C[v]+=C[u]
			dfs(v,u)
		end
	end
end
dfs(1,0)
println.(C)
end
main()


const lines=readlines()
const N,Q=map(x->parse(Int,x),split(shift!(lines)))
const G=[Int[] for _=1:N]
const C=zeros(Int,N)
for i=2:N
	a,b=map(x->parse(Int,x),split(shift!(lines)))
	push!(G[a],b)
	push!(G[b],a)
end
for i=1:Q
	p,x=map(x->parse(Int,x),split(shift!(lines)))
	C[p]+=x
end
function dfs(u,p)
	for v=G[u]
		if v!=p
			C[v]+=C[u]
			dfs(v,u)
		end
	end
end
dfs(1,0)
println.(C)


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

function main()
	n,q = readline() |> split |> parseMap
	e = [Int[] for i in 1:n]
	t = zeros(Int,n)
	t[1] = -1
	for i in 1:n-1
		a,b = readline() |> split |> parseMap
		push!(e[a],b)
		push!(e[b],a)
	end
	stack = Int[1]
	c = zeros(Int,n)
	for i in 1:q
		p,x = readline() |> split |> parseMap
		c[p]+=x
	end
	total = zeros(Int,n)
	while !isempty(stack)
		now = pop!(stack)
		for i in 1:length(e[now])
			if t[e[now][i]] == 0
				t[e[now][i]] = now
				c[e[now][i]] += c[now]
				push!(stack, e[now][i])
			end
		end
	end
	for i in 1:n-1
        print(c[i], " ")
    end
    println(c[n])
end

main()


function acinput()
    in=split(readline(stdin))
    map(x->parse(Int,x),in)
end

function search(n)
    for l in L[n]
        res[l]=res[n]+P[l]
        search(l)
    end
end

N,Q=acinput()

#L=[[]for i in range(N+1)]
L=Dict()
for i in 1:N
    L[i]=[]
end
for i in 1:(N-1)
    tmp=acinput()
    append!(L[tmp[1]],tmp[2])
end

P=zeros(N+1)
for i in 1:Q
    tmp=acinput()
    P[tmp[1]]+=tmp[2]
end

res=zeros(N+1)
res[1]=P[1]
search(1)

tmp=floor.(Int,res[1:end-1])
println(join(tmp," "))


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

function main()
	n,q = readline() |> split |> parseMap
	e = [Int[] for i in 1:n]
	t = zeros(Int,n)
	t[1] = -1
	for i in 1:n-1
		a,b = readline() |> split |> parseMap
		push!(e[a],b)
		push!(e[b],a)
	end
	stack = Int[1]
	c = zeros(Int,n)
	for i in 1:q
		p,x = readline() |> split |> parseMap
		c[p]+=x
	end
	total = zeros(Int,n)
	while !isempty(stack)
		now = shift!(stack)
		for i in 1:length(e[now])
			if t[e[now][i]] == 0
				t[e[now][i]] = now
				c[e[now][i]] += c[now]
				push!(stack, e[now][i])
			end
		end
	end
	for i in 1:n-1
        print(c[i], " ")
    end
    println(c[n])
end

main()


function acinput()
    map(x->(parse(Int64,x)),split(readline(stdin)," "))
end

function search(n)
    for l in L[n]
        res[l]=res[n]+P[l]
        search(l)
    end
end

N,Q=acinput()

#L=[[]for i in range(N+1)]
L=Dict()
for i in 1:N
    L[i]=[]
end
for i in 1:(N-1)
    tmp=acinput()
    append!(L[tmp[1]],tmp[2])
end

P=zeros(N+1)
for i in 1:Q
    tmp=acinput()
    P[tmp[1]]+=tmp[2]
end

res=zeros(N+1)
res[1]=P[1]
search(1)

tmp=floor.(Int,res[1:end-1])
println(join(tmp," "))


function acinput()
    map(x->(parse(Int64,x)),split(readline(stdin)," "))
end

function search(n)
    for l in L[n]
        res[l]=res[n]+P[l]
        search(l)
    end
end

N,Q=acinput()

#L=[[]for i in range(N+1)]
L=Dict()
for i in 1:N
    L[i]=[]
end
for i in 1:(N-1)
    tmp=acinput()
    append!(L[tmp[1]],tmp[2])
end

P=zeros(N+1)
for i in 1:Q
    tmp=acinput()
    P[tmp[1]]+=tmp[2]
end

res=zeros(N+1)
res[1]=P[1]
search(1)

tmp=floor.(Int,res[1:end-1])
print(join(tmp," "))


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

function main()
	n,q = readline() |> split |> parseMap
	e = [Int[] for i in 1:n]
	t = zeros(Int,n)
	t[1] = -1
	for i in 1:n-1
		a,b = readline() |> split |> parseMap
		push!(e[a],b)
		push!(e[b],a)
	end
	stack = Int[1]
	c = zeros(Int,n)
	for i in 1:q
		p,x = readline() |> split |> parseMap
		c[p]+=x
	end
	total = zeros(Int,n)
	while !isempty(stack)
		now = shift!(stack)
		for i in 1:length(e[now])
			if t[e[now][i]] == 0
				t[e[now][i]] = now
				c[e[now][i]] += c[now]
				push!(stack, e[now][i])
			end
		end
	end
	for i in 1:n-1
        print(c[i], " ")
    end
    println(c[n])
end

main()


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

function main()
	n,q = readline() |> split |> parseMap
	e = [Int[] for i in 1:n]
	t = zeros(Int,n)
	t[1] = -1
	for i in 1:n-1
		a,b = readline() |> split |> parseMap
		push!(e[a],b)
		push!(e[b],a)
	end
	stack = Int[1]
	c = zeros(Int,n)
	for i in 1:q
		p,x = readline() |> split |> parseMap
		c[p]+=x
	end
	total = zeros(Int,n)
	while !isempty(stack)
		now = pop!(stack)
		for i in 1:length(e[now])
			if t[e[now][i]] == 0
				t[e[now][i]] = now
				c[e[now][i]] += c[now]
				push!(stack, e[now][i])
			end
		end
	end

end

main()


lines=parse.(split(readline()))
_lines=lines[1]
KI=[]
for i in 1:_lines-1
  Ki=parse.(split(readline()))
  push!(KI,Ki)
end

__lines=lines[2]
ADD=[]
for k in 1:__lines-1
  Add=parse.(split(readline()))
  push!(ADD,Add)
end

super_KI=[]
count=zeros(Int64,_lines)
for ii in KI
  push!(super_KI,KI[1])
end

for _add in ADD
  for ki in KI
    if _add[1]==ki[1]
      count[ki[1]]+=_add[2]
      count[ki[2]]+=_add[2]
      if length(findin(super_KI,ki[1]))>1
        for kk in KI
          if kk[1]==ki[1]
            count[kk[1]]+=_add[2]
            count[kk[2]]+=_add[2]
          end
        end
      end
    end
  end
end

for jj in count
  print(jj)
end

print("\n")


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]
		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(h[2*k],z)>=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,m,p = readline() |> split |> parseMap
	e = Tuple{Int,Int,Int}[(0,0,0) for i in 1:m]
	gin = [Int[] for i in 1:n]
	gout = [Int[] for i in 1:n]
	for i in 1:m
		a,b,c = readline() |> split |> parseMap
		push!(gin[a],b)
		push!(gout[b],a)
		e[i] = (a,b,c-p)
	end
	dish = -ones(Int,n)
	h = Array{Tuple{Int,Int},1}()
	push!(h,(1,0))
	while !isempty(h)
		v,w = hpop(h)
		dish[v] = dish[v]<0?w:min(dish[v],w)
		for i in 1:length(gin[v])
			if dish[gin[v][i]]<0 || dish[gin[v][i]]>w+1
				dish[gin[v][i]] = w+1
				hpush(h,(gin[v][i],w+1))
			end
		end
	end
	disb = -ones(Int,n)
	h = Array{Tuple{Int,Int},1}()
	push!(h,(n,0))
	while !isempty(h)
		v,w = hpop(h)
		disb[v] = disb[v]<0?w:min(disb[v],w)
		for i in 1:length(gout[v])
			if disb[gout[v][i]]<0　|| disb[gout[v][i]]>w+1
				disb[gout[v][i]] = w+1
				hpush(h,(gout[v][i],w+1))
			end
		end
	end
	d = -10^18*ones(Int,n)
	d[1] = 0
	for i in 1:n-1
		for j in 1:m
			u = e[j][1]
			v = e[j][2]
			w = e[j][3]
			d[v]=max(d[v],d[u]+w)
		end
	end
	f = 0
	for j in 1:m
		u = e[j][1]
		v = e[j][2]
		w = e[j][3]
		if d[v]<d[u]+w&&(dish[v]>-1&&disb[v]>-1)
			f = 1
			d[v] = max(d[v],d[u]+w)
		end
	end
	println(f==0?max(d[n],0):-1)
end

main()

Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

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

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.


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

function main()
	n,m,p = readline() |> split |> parseMap
	e = Tuple{Int,Int,Int}[(0,0,0) for i in 1:m]
	for i in 1:m
		a,b,c = readline() |> split |> parseMap
		e[i] = (a,b,c-p)
	end
	d = 10^18*ones(Int,n)
	d[1] = 0
	for i in n-1
		for j in 1:m
			u = e[j][1]
			v = e[j][2]
			w = e[j][3]
			d[v]=min(d[v],d[u]-w)
		end
	end
	neg = zeros(Int,n)
	for j in 1:m
		u = e[j][1]
		v = e[j][2]
		w = e[j][3]
		if d[v]>d[u]-w || neg[u]==1
			neg[v]=1
		end
		d[v] = min(d[v],d[u]-w)
	end
	println(neg[n]==0?max(-d[n],0):-1)
end

main()


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

function main()
	n,m,p = readline() |> split |> parseMap
	e = Tuple{Int,Int,Int}[(0,0,0) for i in 1:m]
	for i in 1:m
		a,b,c = readline() |> split |> parseMap
		e[i] = (a,b,c-p)
	end
	d = -10^18*ones(Int,n)
	d[1] = 0
	for i in n-1
		for j in 1:m
			u = e[j][1]
			v = e[j][2]
			w = e[j][3]
			d[v]=max(d[v],d[u]+w)
		end
	end
	neg = zeros(Int,n)
	for j in 1:m
		u = e[j][1]
		v = e[j][2]
		w = e[j][3]
		if d[v]<d[u]+w || neg[u]==1
			neg[v]=1
		end
	end
	println(neg[n]==0?max(d[n],0):-1)
end

main()


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

type Edge
  from::Int
  to::Int
  cost::Float64
end

function bellmanFord(
  n_vertices::Int, edges::Array{Edge}, s_edge::Int
)::Array{Float64}
  # d[i] = min{d[j] + (cost from j to i) | e = (j to i) in E}

  n_edges = length(edges)
  d_cost = fill(Inf, n_vertices)
  d_cost[s_edge] = 0

  updated = true
  i = 1
  while updated
    updated = false
    for e in edges
      prev = d_cost[e.to]
      d_cost[e.to] = min(d_cost[e.to], d_cost[e.from] + e.cost)
      d_cost[e.to] != prev && (updated = true)
      (i >= n_vertices && d_cost[e.to] != prev) && (d_cost[e.to] = -Inf)
    end
    i += 1
  end

  d_cost
end

function main()
  n_vertices, m_edges, p_cost = readline() |> split |> parseArray
  a_vertex = zeros(Int, m_edges)
  b_vertex = zeros(Int, m_edges)
  c_cost = zeros(Int, m_edges)
  for i in 1:m_edges
    a_vertex[i], b_vertex[i], c_cost[i] = readline() |> split |> parseArray
  end

  c_cost -= p_cost
  c_cost *= -1
  edges = zip(a_vertex, b_vertex, c_cost) |> a -> map(t -> Edge(t...), a)

  d_cost = bellmanFord(n_vertices, edges, 1)

  println(d_cost[n_vertices] |> x -> x == -Inf ? -1 : max(Int(-x), 0))
end

main()


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

type Edge
  from::Int
  to::Int
  cost::Float64
end

function bellmanFord(
  n_vertices::Int, edges::Array{Edge}, s_edge::Int
)::Array{Float64}
  # d[i] = min{d[j] + (cost from j to i) | e = (j to i) in E}

  n_edges = length(edges)
  d_cost = fill(Inf, n_vertices)
  d_cost[s_edge] = 0

  f() =
    for _ in 1:n_vertices
      for e in edges
        d_cost[e.to] = min(d_cost[e.to], d_cost[e.from] + e.cost)
      end
    end

  f()
  prev = copy(d_cost)
  f()
  d_cost[d_cost .!= prev] = -Inf

  d_cost
end

function main()
  n_vertices, m_edges, p_cost = readline() |> split |> parseArray
  a_vertex = zeros(Int, m_edges)
  b_vertex = zeros(Int, m_edges)
  c_cost = zeros(Int, m_edges)
  for i in 1:m_edges
    a_vertex[i], b_vertex[i], c_cost[i] = readline() |> split |> parseArray
  end

  c_cost -= p_cost
  c_cost *= -1
  edges = zip(a_vertex, b_vertex, c_cost) |> a -> map(t -> Edge(t...), a)

  d_cost = bellmanFord(n_vertices, edges, 1)

  println(d_cost[n_vertices] |> x -> x == -Inf ? -1 : max(Int(-x), 0))
end

main()


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

type Edge
  from::Int
  to::Int
  cost::Float64
end

function bellmanFord(
  n_vertices::Int, edges::Array{Edge}, s_edge::Int
)::Array{Float64}
  # d[i] = min{d[j] + (cost from j to i) | e = (j to i) in E}

  n_edges = length(edges)
  d_cost = fill(Inf, n_vertices)
  d_cost[s_edge] = 0

  i = 1
  while i ÷ n_edges <= n_vertices
    e = edges[i % n_edges + 1]
    prev = d_cost[e.to]

    d_cost[e.to] = min(d_cost[e.to], d_cost[e.from] + e.cost)

    (i ÷ n_edges == n_vertices && d_cost[e.to] != prev) && (d_cost[e.to] = -Inf)

    i += 1
  end

  d_cost
end

function main()
  n_vertices, m_edges, p_cost = readline() |> split |> parseArray
  a_vertex = zeros(Int, m_edges)
  b_vertex = zeros(Int, m_edges)
  c_cost = zeros(Int, m_edges)
  for i in 1:m_edges
    a_vertex[i], b_vertex[i], c_cost[i] = readline() |> split |> parseArray
  end

  c_cost -= p_cost
  c_cost *= -1
  edges = zip(a_vertex, b_vertex, c_cost) |> a -> map(t -> Edge(t...), a)

  d_cost = bellmanFord(n_vertices, edges, 1)

  println(d_cost[n_vertices] |> x -> x == -Inf ? -1 : max(Int(-x), 0))
end

main()


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

type Edge
  from::Int
  to::Int
  cost::Float64
end

function bellmanFord(
  n_vertices::Int, edges::Array{Edge}, s_edge::Int, mode = :min
)::Array{Float64}
  # d[i] = min{d[j] + (cost from j to i) | e = (j to i) in E}

  n_edges = length(edges)
  d_cost = fill(mode == :min ? Inf : -Inf, n_vertices)
  d_cost[s_edge] = 0

  i = 1
  counter = 0
  while i ÷ n_edges <= n_vertices
    e = edges[i % n_edges + 1]
    prev = d_cost[e.to]

    d_cost[e.to] = mode == :min ?
      min(d_cost[e.to], d_cost[e.from] + e.cost) :
      max(d_cost[e.to], d_cost[e.from] + e.cost)

    (i ÷ n_edges == n_vertices && d_cost[e.to] != prev) &&
      (d_cost[e.to] = mode == :min ? -Inf : Inf)

    i += 1
  end

  d_cost
end

function main()
  n_vertices, m_edges, p_cost = readline() |> split |> parseArray
  a_vertex = zeros(Int, m_edges)
  b_vertex = zeros(Int, m_edges)
  c_cost = zeros(Int, m_edges)
  for i in 1:m_edges
    a_vertex[i], b_vertex[i], c_cost[i] = readline() |> split |> parseArray
  end

  c_cost -= p_cost
  edges = zip(a_vertex, b_vertex, c_cost) |> a -> map(t -> Edge(t...), a)

  d_cost = bellmanFord(n_vertices, edges, 1, :max)

  println(d_cost[n_vertices] |> x -> x == Inf ? -1 : max(Int(x), 0))
end

main()


using DataStructures
const double = Float64
const int = Int64

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

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

  if N == 1
    println("Yes")
    return
  end
  if H[1] -1 > H[2]
    println("No")
    return
  end

  for i in 2:N-1
    if H[i-1] > H[i] && H[i] > H[i+1]
      println("No")
      return
    end
    if H[i] -1 > H[i+1]
      println("No")
      return
    end

  end
  println("Yes")
  return
end

main()

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i.

For each square, you will perform either of the following operations once:

Decrease the height of the square by 1.

Do nothing.

Determine if it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

If it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right, print Yes; otherwise, print No.

Sample Input 1

5
1 2 1 1 3

Sample Output 1

Yes

You can achieve the objective by decreasing the height of only the second square from the left by 1.

Sample Input 2

4
1 3 2 1

Sample Output 2

No

Sample Input 3

5
1 2 3 4 5

Sample Output 3

Yes

Sample Input 4

1
1000000000

Sample Output 4

Yes


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    n=parseInt(readline())
    h=reverse(parseMap(split(readline())))
    flg=true
    for i in 2:n
        if h[i]-h[i-1]==1
            h[i]-=1
        elseif h[i]-h[i-1]>1
            flg=false
        end
    end
    println(ifelse(flg,"Yes","No"))
end
main()


parseint(x) = parse(Int, x)
readint() = readline() |> parseint
readintlist() = map(parseint, readline() |> split)

function main()
    n = readint()
    h = readintlist()
    ans = "Yes"
    for i = n-1:-1:1
        if h[i] > h[i+1]
            h[i] -= 1
        end
        if h[i] > h[i+1]
            ans = "No"
        end
    end
    println(ans)
end

main()


#=
C:
- Julia version:
- Author: abap
- Date: 2020-01-22
=#
parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
N = parse(readline())
H = parseMap(split(readline()))
l = 1000000001
function main()
for i in N:-1:1
	h = H[i]
	if h - l > 2
		return "No"
	else
		h -= 1
	end
	l = h
end
return "Yes"
end

ans = main()
println(ans)


#=
C:
- Julia version:
- Author: abap
- Date: 2020-01-22
=#
parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
N = parse(readline())
H = parseMap(split(readline()))
l = 1000000001
for i in 1:N
	h = H[i]
	if h - l > 2
		return "No"
	end
    l = h
end
return "Yes"
end

ans = main()
println(ans)


function main()

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

  check = true

  for i in 1:N-1

    if H[i] > H[i+1] || H[i] > H[end]
      H[i] -= 1
    end

  end

  for i in 1:N-1

    if H[i] > H[i+1]
      check = false
    end

  end

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

end

main()


function main()

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

  check = true

  for i in 1:N-1

    if H[i] > H[i+1]
      H[i] -= 1
    end

  end

  for i in 1:N-1

    if H[i] > H[i+1]
      check = false
    end

  end

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

end

main()


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

function main()
  n = readline() |> parseInt
  h = readline() |> split |> parseArray

  for i in n-1:-1:1
    if h[i]>h[i+1]
      h[i]-=1
    end
  end

  check() = begin
    for i in n-1:-1:1
      h[i] > h[i+1] && return false
    end
    true
  end

  println(h)
  (check() ? "Yes" : "No") |> println
end

main()


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

function main()
	n = readline() |> parseInt
	h = readline() |> split |> parseMap
	f = 0
	m = 0
	for i in 1:n-1
		if h[i]-1>h[i+1]
			f = 1
			break
		elseif h[i]==h[i+1]+1
			if h[i]-1<m
				f = 1
				break
			else
				m = h[i]-1
			end
		else
			if h[i]<m
				f = 1
				break
			elseif h[i]-1<m
				m = h[i]
			else
				m = h[i]-1
			end
		end
	end
	if h[n]<m
		f = 1
	end
	println(f==0?"Yes":"No")
end

main()


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

function main()
	n = readline() |> parseInt
	h = readline() |> split |> parseMap
	f = 0
	m = 0
	for i in 1:n-1
		if h[i]-1>h[i+1]
			f = 1
			break
		elseif h[i]+1==h[i+1]
			if h[i]-1<m
				f = 1
				break
			else
				m = h[i]-1
			end
		else
			if h[i]<m
				f = 1
				break
			elseif h[i]-1<m
				m = h[i]
			else
				m = h[i]-1
			end
		end
	end
	if h[n]<m
		f = 1
	end
	println(f==0?"Yes":"No")
end

main()


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

function main()
	n = readline() |> parseInt
	h = readline() |> split |> parseMap
	f = 0
	m = 0
	for i in 1:n-1
		if h[i]-1>h[i+1]
			f = 1
			break
		elseif h[i]+1==h[i+1]
			if h[i]-1<m
				f = 1
				break
			else
				m = h[i]-1
			end
		else
			if h[i]<m
				f = 1
				break
			elseif h[i]-1<m
				m = h[i]
			else
				m = h[i]-1
			end
		end
	end
	println(f==0?"Yes":"No")
end

main()


n=parse(Int,readline())
h=split(readline())
X=Any[]
for i=1:n
    X= push!(X , parse(Int,h[i]))
end
s=0
for i=1:n-1
  if X[n-i]<=X[n-i+1]
    s+=1
  elseif X[n-i]==X[n-i+1]+1
    X[n-i]=X[n-i]-1
    s+=1
  else
    break
  end
end

if n==1
  print("Yes")
  elseif s==n-1
  print("Yes")
else
  print("No")
end


N=parse(Int,readline())
p=0
for h=map(x->parse(Int,x),split(readline()))
	h-=p<h
	if p>h
		println("No")
		exit()
	end
	p=h
end
println("Yes")


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

function main()
	n = readline() |> parseInt
	h = readline() |> split |> parseMap
	f = 0
	m = 0
	for i in 1:n-1
		if h[i]-1>h[i+1]
			f = 1
			break
		elseif h[i]>h[i+1]
			if h[i]-1<m
				f = 1
				break
			else
				m = h[i]-1
			end
		else
			if h[i]<m
				f = 1
				break
			else
				m = h[i]
			end
		end
	end
	println(f==0?"Yes":"No")
end

main()


parseInt(x) = parse(Int,x)

function main()
  N = parseInt(readline())
  H = map(parseInt,split(readline()))
  c = 1
  for i = (N-1):-1:1
    a = H[i+1]-H[i]
    a == -1 ? H[i] -= 1 : tmp = 0
    a < -1 ? c = -1 : tmp = 0
  end
  c == 1 ? println("Yes") :println("No")
end

main()


using DataStructures
const double = Float64
const int = Int64

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

function main()
  L,R = readint()
  if L÷2019 < R÷2019
    println(0)
    return
  elseif L ÷ 3 < R ÷ 3 && L÷673 < R÷673
    println(0)
    return
  else
    mins = typemax(int)
    for i in L:R-1
      for j in i+1:R
        if  (i*j)%2019 < mins
          mins = (i*j)%2019
        end
      end
    end
    println(mins)

  end

end

main()

Score : 300 points

Problem Statement

You are given two non-negative integers L and R.
We will choose two integers i and j such that L \leq i < j \leq R.
Find the minimum possible value of (i \times j) \mbox{ mod } 2019.

Constraints

All values in input are integers.

0 \leq L < R \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

L R

Output

Print the minimum possible value of (i \times j) \mbox{ mod } 2019 when i and j are chosen under the given condition.

Sample Input 1

2020 2040

Sample Output 1

2

When (i, j) = (2020, 2021), (i \times j) \mbox{ mod } 2019 = 2.

Sample Input 2

4 5

Sample Output 2

20

We have only one choice: (i, j) = (4, 5).


using DataStructures
const double = Float64
const int = Int64

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

function main()
  L,R = readint()
  if L÷2019 < R÷2019
    println(0)
    return
  elseif L ÷ 3 < R ÷ 3 && L÷673 < R÷673
    println(0)
    return
  else
    min = typedef(int)
    for i in L:R-1
      for j in i+1:R
        if  (i*j)%2019 < min
          min = (i*j)%2019
        end
      end
    end
    println(min)

  end

end

main()


a,b=(x->parse(Int,x)).(split(readline()))
a%=2019
b=a+(b-a)%2019
print(minimum([i*j%2019 for i=a:b-1 for j=i+1:b]))


a,b=parse.(split(readline()))
print(b-a>2018?0:minimum(i*j%2019 for i in a:b-1 for j in i+1:b))


function main()
	a,b=parse.(split(readline()))
	c,d=a%2019,b%2019
	print(b-a>2018?0:minimum([i*j%2019 for i in c:d-1 for j in i+1:d]))
end
main()


a,b=parse.(split(readline()))
print(b-a>2018?0:minimum([i*j%2019 for i in a:b-1 for j in i+1:b]))


a,b=parse.(split(readline()))
l=[i*j for i in a:b-1 for j in i+1:b]
print(min(map(x->x%2019,l)...))


function main()

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

  ans = 10^10

  if R-L+1 >= 2019
    ans = 0
  else
    for i in L:R-1
      for j in i+1:R
        ans = min(ans,(i*j) % 2019)
      end
    end
  end

  println(ans)

end

main()


function main()

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

  check1 = 10^10
  check2 = 0

  for i in L:R
    check1 = min(check1, i % 2019)
    check2 = max(check2, i % 2019)
  end

  ans = 10^10

  for i in check1:check2-1
    for j in i+1:check2
      ans = min(ans,i*j)
    end
  end

  println(ans)

end

main()


function main()

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

  ans = 10^10

  for i in L:R-1
    for j in i+1:R
      ans = min(ans,(i*j) % 2019)
    end
  end

  println(ans)

end

main()


function main()

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

  ans1 = 10^10

  for i in L:R
    ans1 = min(ans1,i % 2019)
  end

  println(ans1*(ans1+1))

end

main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    l,r=parseMap(split(readline()))
    if l+2019-l%2019<=r
        println(0)
    else
        l%=2019
        r%=2019
        ans=2020
        for i in l:r
            for j in i+1:r
                ans=min(ans,(i*j)%2019)
            end
        end
        println(ans)
    end
end
main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    l,r=parseMap(split(readline()))
    l%=2019
    r%=2019
    l,r=min(l,r),max(l,r)
    ans=2020
    for i in l:r
        for j in i+1:r
            ans=min(ans,(i*j)%2019)
        end
    end
    println(ans)
end
main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    l,r=parseMap(split(readline()))
    if l+2019-l%2019<=r
        println(0)
    else
        println(min(l*(l+1)%2019,r*(r-1)%2019))
    end
end
main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
L,R = parseMap(split(readline()))
if R-L >= 2019
    println(0)
else
    best_ans = 2019^2 + 1
    for i in L:R
        for j in i+1:R
            ans =  i*j % 2019
            ans < best_ans && (best_ans = ans)
            best_ans == 0 && break
        end
    end
    println(best_ans)
end


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
L,R = parseMap(split(readline()))
if L <= 2019 <=R
    println(0)
else
    best_ans = 2019^2 + 1
    for i in L:R
        for j in i+1:R
            ans =  i*j % 2019
            ans < best_ans && (best_ans = ans)
            best_ans == 0 && break
        end
    end
    println(best_ans)
end


parseint(x) = parse(Int, x)
readints() = map(parseint, readline() |> split)

function main()
    l, r = readints()
    if r - l >= 2018
        println(0)
    else
        ans = 2019
        for i = l:r-1, j = i+1:r
            ans = min(ans, (i * j) % 2019)
        end
        println(ans)
    end
end

main()


l,r=parse.(split(readline()))
s=l:min(l+2019,r)
show(minimum(i*j%2019for i=s,j=s if i<j))


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

function main()
  s = readline() |> strip

  s=replace(s, "BC", "D")
  n=0

  # while true
  #   nn=0
  #   a=collect(s)
  #   for m in eachmatch(r"AD", s)
  #     i=m.offset
  #     a[i],a[i+1]=a[i+1],a[i] # "AD" -> "DA"
  #     nn+=1
  #   end
  #   nn==0 && break
  #   n+=nn
  #   s=join(a)
  # end

  for m in eachmatch(r"[AD]+", s)
    ss=m.match
    l=length(ss)
    ix=(1:l)[collect(ss).=='A']
    k=length(ix)
    n+=sum(l-ix)-div((k-1)*k,2)
  end

  n |> println
end

main()

Score : 600 points

Problem Statement

You are given a string s consisting of A, B and C.

Snuke wants to perform the following operation on s as many times as possible:

Choose a contiguous substring of s that reads ABC and replace it with BCA.

Find the maximum possible number of operations.

Constraints

1 \leq |s| \leq 200000

Each character of s is A, B and C.

Input

Input is given from Standard Input in the following format:

s

Output

Find the maximum possible number of operations.

Sample Input 1

ABCABC

Sample Output 1

3

You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.

Sample Input 2

C

Sample Output 2

0

Sample Input 3

ABCACCBABCBCAABCB

Sample Output 3

6


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

function main()
  s = readline() |> strip

  s=replace(s, "BC", "D")
  n=0

  # for ss in eachmatch(r"A|D", s)
  # end

  while true
    nn=0
    a=collect(s)
    for m in eachmatch(r"AD", s)
      i=m.offset
      a[i],a[i+1]=a[i+1],a[i] # "AD" -> "DA"
      nn+=1
    end
    nn==0 && break
    n+=nn
    s=join(a)
  end

  n |> println
end

main()


function read_line()
    map(x->parse(Int64, x), split(readline()))
end
function solve()
    ret = 0
    S = collect(strip(readline()))
    i = 1
    while i < length(S) - 1
        if S[i:i+2] == ['A', 'B', 'C']
            S[i] = 'B'
            S[i+1] = 'C'
            S[i+2] = 'A'
            ret += 1
            if i > 1
                i -= 1
            end
        else
            i += 1
        end
    end
    println(ret)
end
solve()


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

function main()
	s = readline() |> chomp
	s = replace(s,"BC","X")
	n = length(s)
	a = zeros(Int,n)
	k = 0
	for i in 0:n-1
		if s[n-i] == 'A'
			a[n-i] = k
		elseif s[n-i] == 'X'
			k += 1
		else
			k = 0
		end
	end
	println(sum(a))
end

main()


function main()
  (H, W) = map(x -> parse(Int, x), split(readline()))
  c = []
  d = []
  for i = 1:H
    push!(c, split(chomp(readline()), ""))
    push!(d, fill(-1, W))
  end
  q = []
  for i = 1:H
    for j = 1:W
      if c[i][j] == "#"
        push!(q, [i, j])
        d[i][j] = 0
      end
    end
  end
  p = popfirst!(q)
  max = 0
  dx = [1, 0, -1, 0]
  dy = [0, 1, 0, -1]
  while true
    xx = p[1]
    yy = p[2]
    for i = 1:4
      x = xx + dx[i]
      y = yy + dy[i]
      if x > 0 && x < H + 1 && y > 0 && y < W + 1 && d[x][y] < 0
        if c[x][y] == "."
          push!(q, [x, y])
          count = d[xx][yy] + 1
          if max < count
            max = count
          end
          d[x][y] = count
        end
      end
    end
    if length(q) == 0
      break
    end
    p = popfirst!(q)
  end
  println(max)
end
main()

Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

6 6
..#..#
......
#..#..
......
.#....
....#.

Sample Output 2

3


const H,W=map(x->parse(Int,x),split(readline()))
const S=readlines()
const P=Pair{Int,Int}[]
const D=-ones(Int,H,W)
function init()
	for i=1:H,j=1:W
		if S[i][j]=='#'
			push!(P,i=>j)
			D[i,j]=0
		end
	end
end
function ev(x,y)
	for (dx,dy)=[0=>1,0=>-1,1=>0,-1=>0]
		tx=x+dx
		ty=y+dy
		if 1<=tx<=H&&1<=ty<=W&&D[tx,ty]==-1
			D[tx,ty]=D[x,y]+1
			push!(P,tx=>ty)
		end
	end
end
function main()
	init()
	while !isempty(P)
		(x,y)=shift!(P)
		ev(x,y)
	end
	println(maximum(D))
end
main()


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

function main()
	h,w = readline() |> split |> parseMap
	a = ["" for i in 1:h]
	chk = -ones(Int,h,w)
	k = 0
	b = Tuple{Int,Int}[]
	m = 0
	@inbounds for i in 1:h
		a[i] = readline() |> chomp
		for j in 1:w
			if a[i][j] == '#'
				chk[i,j] = 0
				k += 1
				push!(b,(i,j))
			end
		end
	end
	while k < h*w
		x,y = shift!(b)
		if x>1
			if chk[x-1,y] < 0
				push!(b,(x-1,y))
				chk[x-1,y] = chk[x,y]+1
				k += 1
			end
		end
		if x<h
			if chk[x+1,y] < 0
				push!(b,(x+1,y))
				chk[x+1,y] = chk[x,y]+1
				k += 1
			end
		end
		if y>1
			if chk[x,y-1] < 0
				push!(b,(x,y-1))
				chk[x,y-1] = chk[x,y]+1
				k += 1
			end
		end
		if y<w
			if chk[x,y+1] < 0
				push!(b,(x,y+1))
				chk[x,y+1] = chk[x,y]+1
				k += 1
			end
		end
		m = max(m,chk[x,y]+1)
	end
	println(m)
end

main()


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

function main()
	h,w = readline() |> split |> parseMap
	a = ["" for i in 1:h]
	chk = -ones(Int,h,w)
	k = 0
	b = Tuple[]
	m = 0
	for i in 1:h
		a[i] = readline() |> chomp
		for j in 1:w
			if a[i][j] == '#'
				chk[i,j] = 0
				k += 1
				push!(b,(i,j))
			end
		end
	end
	while k < h*w
		x,y = shift!(b)
		if x>1
			if chk[x-1,y] < 0
				push!(b,(x-1,y))
				chk[x-1,y] = chk[x,y]+1
				k += 1
			end
		end
		if x<h
			if chk[x+1,y] < 0
				push!(b,(x+1,y))
				chk[x+1,y] = chk[x,y]+1
				k += 1
			end
		end
		if y>1
			if chk[x,y-1] < 0
				push!(b,(x,y-1))
				chk[x,y-1] = chk[x,y]+1
				k += 1
			end
		end
		if y<w
			if chk[x,y+1] < 0
				push!(b,(x,y+1))
				chk[x,y+1] = chk[x,y]+1
				k += 1
			end
		end
		m = max(m,chk[x,y]+1)
	end
end

main()


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

function main()
	h,w = readline() |> split |> parseMap
	a = ["" for i in 1:h]
	chk = -ones(Int,h,w)
	k = 0
	b = Tuple[]
	for i in 1:h
		a[i] = readline() |> chomp
		for j in 1:w
			if a[i][j] == '#'
				chk[i,j] = 0
				k += 1
				push!(b,(i,j))
			end
		end
	end
	while k < h*w
		x,y = shift!(b)
		if x>1
			if chk[x-1,y] < 0
				push!(b,(x-1,y))
				chk[x-1,y] = chk[x,y]+1
				k += 1
			end
		end
		if x<h
			if chk[x+1,y] < 0
				push!(b,(x+1,y))
				chk[x+1,y] = chk[x,y]+1
				k += 1
			end
		end
		if y>1
			if chk[x,y-1] < 0
				push!(b,(x,y-1))
				chk[x,y-1] = chk[x,y]+1
				k += 1
			end
		end
		if y<w
			if chk[x,y+1] < 0
				push!(b,(x,y+1))
				chk[x,y+1] = chk[x,y]+1
				k += 1
			end
		end
	end
	println(maximum(chk))
end

main()


function main()
  h, w = map(n -> parse(Int,n), split(readline()))
  grid = fill(1000000000, (w,h))

  for y in 1:h
    s = readline()
    for x in 1:w
      if s[x] == '#'
        grid[x,y] = 0
      end
    end
  end

  for y in 1:h
    for x in 2:w
      if grid[x,y] > grid[x-1,y]+1
        grid[x,y] = grid[x-1,y]+1
      end
      if grid[w-x+1,y] > grid[w-x+2,y]+1
        grid[w-x+1,y] = grid[w-x+2,y]+1
      end
    end
  end

  for x in 1:w
    for y in 2:h
      if grid[x,y] > grid[x,y-1]+1
        grid[x,y] = grid[x,y-1]+1
      end
      if grid[x,h-y+1] > grid[x,h-y+2]+1
        grid[x,h-y+1] = grid[x,h-y+2]+1
      end
    end
  end

  println(maximum(grid))
end

main()


let
  H, W = map(x -> parse(Int, x), split(readline()))
  A = []
  for i=1:H
    grid = split(readline(), "")
    push!(A, [if grid[w]=="#" 0 else H*W end for w=1:W])
  end

  black = []
  white = []

  for h = 1:H
    for w = 1:W
      if A[h][w] == 0
        push!(black, (h,w))
      else
        push!(white, (h,w))
      end
    end
  end

  m = 0
  for w in white
    for b in black
      dis = abs(b[1] - w[1]) + abs(b[2] - w[2])
      A[w[1]][w[2]] = min(A[w[1]][w[2]], dis)
    end
    m = max(m, A[w[1]][w[2]])
  end

  println(m)
end


let
  H, W = map(x -> parse(Int, x), split(readline()))
  grid = []
  for i=1:H
    push!(grid, split(readline(), ""))
  end
  A = [[if grid[h][w]=="#" 0 else H*W end for w=1:W] for h=1:H]

  black = []
  white = []

  for h = 1:H
    for w = 1:W
      if A[h][w] == 0
        push!(black, (h,w))
      else
        push!(white, (h,w))
      end
    end
  end

  m = 0
  for w in white
    for b in black
      dis = abs(b[1] - w[1]) + abs(b[2] - w[2])
      A[w[1]][w[2]] = min(A[w[1]][w[2]], dis)
    end
    m = max(m, A[w[1]][w[2]])
  end

  println(m)
end


let
  H, W = map(x -> parse(Int, x), split(readline()))
  grid = []
  for i=1:H
    push!(grid, readline())
  end
  A = [[if grid[h][w]=='#' 0 else H*W end for w=1:W] for h=1:H]

  black = []
  white = []

  for h = 1:H
    for w = 1:W
      if A[h][w] == 0
        push!(black, (h,w))
      else
        push!(white, (h,w))
      end
    end
  end

  m = 0
  for w in white
    for b in black
      dis = abs(b[1] - w[1]) + abs(b[2] - w[2])
      A[w[1]][w[2]] = min(A[w[1]][w[2]], dis)
    end
    m = max(m, A[w[1]][w[2]])
  end

  println(m)
end


let
  H, W = map(x -> parse(Int, x), split(readline()))
  grid = []
  for i=1:H
    push!(grid, readline())
  end
  A = [[if grid[h][w]=='#' 0 else H*W end for w=1:W] for h=1:H]

  black = []
  white = []

  for h = 1:H
    for w = 1:W
      if A[h][w] == 0
        push!(black, (h,w))
      else
        push!(white, (h,w))
      end
    end
  end

  for w in white
    for b in black
      dis = abs(b[1] - w[1]) + abs(b[2] - w[2])
      A[w[1]][w[2]] = min(A[w[1]][w[2]], dis)
      if dis == 1
        break
      end
    end
  end

  m = 0
  for distances in A
    for d in distances
      m = max(m, d)
    end
  end

  println(m)
end


parseInt(x) = parse(Int,x)
findall(f,x) = find(f,x)
parseMap(x::Array{SubString{String}, 1}) = map(parseInt, x)
function main()
  h,w = map(parseInt, split(readline()))
  ss = [readline() for i in 1:h]
  sm = [zeros(w) for i in 1:h]
  for i = 1:h
    ii = findall(x-> x == '#',ss[i])
    if !isempty(ii)
      sm[i][ii] = 1
    end
  end
  a = [ones(w) for i in 1:h]
  ans = 0
  if h==1 && w==1
    if sm[1][1] == 1
      ans =0
    else
      ans =1
    end
  elseif h == 1
    while true
      if sm == a
        break
      else
        ans += 1
        temp = sm[1:end]
        temp[1][1:end-1] =temp[1][1:end-1]+ sm[1][1:end-1] + sm[1][2:end]
        temp[1][2:end] =temp[1][2:end]+ sm[1][2:end] + sm[1][1:end-1]
        ii = findall(x-> x>=2,temp[h])
        if !isempty(ii)
          temp[1][ii]  = 1
        end
        sm = temp
      end
    end
  elseif w == 1
    while true
      if sm == a
        break
      else
        ans += 1
        temp = sm[1:end]
        temp[1:end-1][1] =temp[1:end-1][1]+ sm[2:end][1] + sm[1:end-1][1]
        temp[2:end][1] =temp[2:end][1]+ sm[2:end][1] + sm[1:end-1][1]
        for i = 1:h
          ii = findall(x-> x>=2,temp[h])
          if !isempty(ii)
            temp[h][ii]  = 1
          end
      end
        sm = temp
      end
    end
  else
    while true
      if sm == a
        break
      else
        ans += 1
        temp = sm[1:end]
        temp[1][1:end-1] =temp[1][1:end-1]+ sm[1][1:end-1] + sm[1][2:end]
        temp[1][2:end] = temp[1][2:end]+sm[1][2:end] + sm[1][1:end-1]
        temp[2][1:end] = temp[2][1:end]+sm[2][1:end] + sm[1][1:end]
        for i = 2:h-1
          temp[i][1:end-1] = temp[i][1:end-1]+sm[i][1:end-1] + sm[i][2:end]
          temp[i][2:end] = temp[i][2:end] +sm[i][2:end] + sm[i][1:end-1]
          temp[i+1][1:end] = temp[i+1][1:end]+sm[i+1][1:end] + sm[i][1:end]
          temp[i-1][1:end] =temp[i-1][1:end]+ sm[i-1][1:end] + sm[i][1:end]
        end
        temp[end][1:end-1] = temp[end][1:end-1]+sm[end][1:end-1] + sm[end][2:end]
        temp[end][2:end] = temp[end][2:end]+sm[end][2:end] + sm[end][1:end-1]
        temp[end-1][1:end] = temp[end-1][1:end]+sm[end-1][1:end] + sm[end][1:end]
        if sm[1][1] >= 1
          temp[1][2] = temp[2][1] =1
        end
        if sm[1][w] >= 1
          temp[1][w-1] = temp[2][w] =1
        end
        if sm[h][1] >= 1
          temp[h][2] = temp[h-1][1] =1
        end
        if sm[h][w] >= 1
          temp[h][w-1] = temp[h-1][w] =1
        end
      end
      for i = 1:h
        ii = findall(x-> x>=2,temp[h])
        if !isempty(ii)
          temp[i][ii]  = 1
        end
      end
      sm = temp
    end
  end
  println(Int64(ans))
end
main()


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

  A = []
  for i=1:H
    push!(A, readline())
  end

  black = []
  initBCount = 0
  white = zeros(H*W)
  wcount = 0

  h = 0
  for ah in A
    w = 0
    for aw in ah
      if aw === '#'
        push!(black, W * h + w + 1)
        white[W * h + w + 1] = 0
        initBCount += 1
      else
        white[W * h + w + 1] = 1
        wcount += 1
      end
      w += 1
    end
    h += 1
  end
  retCount = 0
  nextBCount = 0

  while true

    b = pop!(black)
    initBCount -= 1
    addNum = []
    if b > W
      push!(addNum, b - W)
    end
    if b <= W * (H - 1)
      push!(addNum, b + W)
    end
    if b % W != 0
      push!(addNum, b + 1)
    end
    if b % W != 1
      push!(addNum, b - 1)
    end
    for num in addNum
      if white[num] == 1
        white[num] = 0
        black = append!([num], black)
        nextBCount += 1
        wcount -= 1
      end
    end
    if initBCount == 0
      retCount += 1
      if wcount == 0
        break
      end

      initBCount = nextBCount
      nextBCount = 0
    end
  end
  print(retCount)

end


function StringChange(str,n,char)
    buf=collect(str)
    buf[n]=char
    return join(buf)
end
function isBlack(array,h,w)
    if (h<1) | (h > size(array)[1])
        return false
    end
    if (w<1) | (w > length(array[1]))
        return false
    end
    if array[h][w]=='#'
        return true
    end
    return false
end

function count(array,h,w)
    ctr=0
    for h_=h-1:h+1
        for w_=w-1:w+1
            if h_==h & w_==w
                continue
            end
            ctr=ctr+isBlack(array,h_,w_)
        end
    end
    return ctr
end

function isAllBlack(array)
    for h_=1:size(array)[1]
        for w_=1:length(array[1])
            if array[h_][w_] !== '#'
                return false
            end
        end
    end
    return true
end

function nextStep(array)
    buf=copy(array)
    for h_=1:size(array)[1]
        for w_=1:length(array[1])
            if count(buf,h_,w_) >= 1
                array[h_]=StringChange(array[h_],w_,'#')
            end
        end
    end
end

function main()
    buf=map(x ->parse(Int64,x), split(readline()))
    h=buf[1]
    w=buf[2]
    array=Array{String,1}(undef,h)
    for h_ = 1:h
        array[h_]=readline()
        println(h_)
    end
    ctr=0
    while true
        if isAllBlack(array)
            break
        end
        nextStep(array)
        ctr=ctr+1
    end
    print(ctr)
end
main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    n=parseInt(readline())
    a=parseMap(split(readline()))
    l=[a[1] for i in 1:n]
    r=[a[n] for i in 1:n]
    for i in 2:n
        l[i]=gcd(l[i-1],a[i])
        r[i]=gcd(r[i-1],a[n-i+1])
    end
    ans=1
    for i in 1:n
        if i==1
            ans=max(ans,r[n-1])
        elseif i==n
            ans=max(ans,l[n-1])
        else
            ans=max(ans,gcd(r[i-1],l[i-1]))
        end
    end
    println(ans)
end
main()

Score : 300 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on the blackboard.

You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Output

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Sample Input 1

3
7 6 8

Sample Output 1

2

If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be 2, which is the maximum possible value.

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.


parseInt(x) = parse(Int,x)
function gc(a::Array,m::Int,N::Int)
  if m == 1
    g = gcd(a[2:N])
  elseif m == N
    g = gcd(a[1:(N-1)])
  else
    g = gcd(gcd(a[1:(m-1)]),gcd(a[(m+1):N]))
  end
  return(g)
end

function main()
  N = parseInt(readline())
  a = map(parseInt,split(readline()))
  (b,k) = findmin(a)
  g = gc(a,k,N)
  d = zeros(Int,N)
  for i=1:N
    d[i] = gcd(b,a[i])
  end
  (c,l)=findmin(d)
  h = gc(a,l,N)
  GCD = maximum([g,h])
  println(GCD)
end

main()


parseInt(x) = parse(Int,x)
function gc(a::Array,m::Int,N:Int)
  if m == 1
    g = gcd(a[2:N])
  elseif m == N
    g = gcd(a[1:(N-1)])
  else
    g = gcd(gcd(a[1:(m-1)]),gcd(a[(m+1):N]))
  end
  return(g)
end

function main()
  N = parseInt(readline())
  a = map(parseInt,split(readline()))
  (b,k) = findmin(a)
  g = gc(a,k,N)
  d = zeros(Int,N)
  for i=1:N
    d[i] = gcd(b,a[i])
  end
  (c,l)=findmin(d)
  h = gc(a,l,N)
  GCD = maximum([g,h])
  println(GCD)
end

main()


parseInt(x) = parse(Int,x)

function main()
  N = parseInt(readline())
  a = map(parseInt,split(readline()))
  b = zeros(Int,N)
  c = 1
  d = 1
  b[1] = gcd(a[2:N])
  for i = 2:(N-1)
    c = gcd(a[1:(i-1)])
    d = gcd(a[(i+1):N])
    b[i] = gcd(c,d)
  end
  b[N]=gcd(a[1:(N-1)])
  GCD = maximum(b)
  println(GCD)
end

main()


parseInt(x) = parse(Int,x)

function main()
  N = parseInt(readline())
  a = map(parseInt,split(readline()))
  b = zeros(Int,N)
  c,d = 1
  b[1] = gcd(a[2:N])
  for i = 2:(N-1)
    c = gcd(a[1:(i-1)])
    d = gcd(a[(i+1):N])
    b[i] = gcd(c,d)
  end
  b[N]=gcd(a[1:(N-1)])
  GCD = maximum(b)
  println(GCD)
end

main()


parseInt(x) = parse(Int,x)

function main()
  N = parseInt(readline())
  a = map(parseInt,split(readline()))
  b = zeros(Int,N)
  b[1] = gcd(a[2:N])
  for i = 2:(N-1)
    b[i] = gcd(gcd(a[1:(i-1)]),gcd(a[(i+1):N]))
  end
  b[N]=gcd(a[1:(N-1)])
  GCD = maximum(b)
  println(GCD)
end

main()


N=parse(Int,readline())
A=map(x->parse(Int,x),split(readline()))
L=Array{Int}(0)
push!(L,0)
tmp=0
for i=A
	tmp=gcd(tmp,i)
	push!(L,tmp)
end
R=Array{Int}(0)
push!(R,0)
tmp=0
for i=reverse(A)
	tmp=gcd(tmp,i)
	push!(R,tmp)
end
R=reverse(R)
ans=0
for i=1:N
	ans=max(ans,gcd(L[i],R[i+1]))
end
println(ans)


parseInt(x) = parse(Int, x)

function main()
  N = readline() |> parseInt
  # A = readdlm(STDIN, Int)
  A = map(parseInt, split(readline()))

  a_gcd = Array{Int}(N)
  a_gcd[1] = A[1]
  for i in 2:N
    a_gcd[i] = gcd(a_gcd[i - 1], A[i])
  end

  a_gcd_r = Array{Int}(N)
  a_gcd_r[end] = A[end]
  for i in N-1:-1:1
    a_gcd_r[i] = gcd(a_gcd_r[i + 1], A[i])
  end

  a = map(1:N) do i
    if i == 1
      a_gcd_r[2]
    elseif i == N
      a_gcd[end - 1]
    else
      gcd(a_gcd[i - 1], a_gcd_r[i + 1])
    end
  end
  # println(a)
  result = maximum(a)

  println(result)
end

main()


parseInt(x) = parse(Int, x)

function main()
  N = readline() |> parseInt
  # A = readdlm(STDIN, Int)
  A = map(parseInt, split(readline()))

  a_gcd = Array{Int}(N)
  a_gcd[1] = A[1]
  for i in 2:N
    a_gcd[i] = gcd(a_gcd[i - 1], A[i])
  end

  a_gcd_r = Array{Int}(N)
  a_gcd_r[end] = A[end]
  for i in N-1:1:-1
    a_gcd_r[i] = gcd(a_gcd_r[i + 1], A[i])
  end

  result = map(1:N) do i
    if i == 1
      a_gcd_r[2]
    elseif i == N
      a_gcd[end - 1]
    else
      gcd(a_gcd[i - 1], a_gcd_r[i + 1])
    end
  end |> maximum

  println(result)
end

main()


function gcd(a :: Vector)
    sorted = sort(a)
    # println(STDERR, "gcd: sorted: $(sorted)")
    a_diff = map(1:length(sorted)) do i
        i == 1 ? sorted[i] : sorted[i] - sorted[i-1]
    end
    # println(STDERR, "gcd: a_diff: $(a_diff)")
    if any(a_diff .== 1)
        # println(STDERR, "gcd: return 1")
        return 1
    end
    a_nonzero = a_diff[a_diff .!= 0]
    # println(STDERR, "gcd: a_nonzero: $(a_nonzero)")
    if length(a_nonzero) == 1
        # println(STDERR, "gcd: return $(a_nonzero[1])")
        return a_nonzero[1]
    else
        # println(STDERR, "gcd: next gcd")
        return gcd(a_nonzero)
    end
end

parseInt(x) = parse(Int, x)

function main()
    readline() # skip
    # A = readdlm(STDIN, Int)
    A = map(parseInt, split(readline()))

    result = maximum(map(1:length(A)) do i
        gcd(vcat(A[1:i-1], A[i+1:end]))
    end)
    println(result)
end

main()


function gcd(a :: Vector)
    sorted = sort(a)
    println(STDERR, "gcd: sorted: $(sorted)")
    a_diff = map(1:length(sorted)) do i
        i == 1 ? sorted[i] : sorted[i] - sorted[i-1]
    end
    println(STDERR, "gcd: a_diff: $(a_diff)")
    if any(a_diff .== 1)
        println(STDERR, "gcd: return 1")
        return 1
    end
    a_nonzero = a_diff[a_diff .!= 0]
    println(STDERR, "gcd: a_nonzero: $(a_nonzero)")
    if length(a_nonzero) == 1
        println(STDERR, "gcd: return $(a_nonzero[1])")
        return a_nonzero[1]
    else
        println(STDERR, "gcd: next gcd")
        return gcd(a_nonzero)
    end
end

function main()
    readline() # skip
    A = readdlm(STDIN, Int)

    result = maximum(map(1:length(A)) do i
        gcd(vcat(A[1:i-1], A[i+1:end]))
    end)
    println(result)
end

main()


parseInt(x) = parse(Int,x)
function main()
	n = map(parseInt, split(readline()))[1]
    a = map(parseInt, split(readline()))
  gl = zeros(Int,1,n)
  gr = zeros(Int,1,n)
  for i = 1 : n-1
  	gl[i+1] = gcd(gl[i],a[i])
    gr[i+1] = gcd(gr[i],a[end -i +1])
  end
  g = zeros(Int,n)
  for i = 1 : n
    g[i] = gcd(gl[i],gr[i])
  end
    println(Int64(maximum(g)))
end
main()


parseInt(x) = parse(Int,x)
function main()
	n = map(parseInt, split(readline()))[1]
    a = map(parseInt, split(readline()))
  gl = zeros(Int,1,n)
  gr = zeros(Int,1,n)
  for i = 1 : n-1
  	gl[i+1] = gcd(gl[i],a[i])
    gr[i+1] = gcd(gr[i],a[end])
  end
  g = zeros(Int,n)
  for i = 1 : n
    g[i] = gcd(gl[i],gr[i])
  end
    println(Int64(maximum(g)))
end
main()


parseInt(x) = parse(Int,x)
function main()
n =3
    a = [12 15 18]
  gl = zeros(Int64,1,n)
  gr = zeros(Int64,1,n)
  for i in 1:n-1
  	gl[i+1] = gcd(gl[i],a[i])
    gr[i+1] = gcd(gr[i],a[end])
  end
  g = zeros(Int64,1,n)
  for i in 1:n
    g[i] = gcd(gl[i],gr[i])
  end
    println(Int64(maximum(g)))
end
  main()


let
  n = parse(Int, readline())
  black_board_numbers = map(x -> parse(Int, x), split(readline()))

  left_gcd = zeros(Int, n - 1)
  right_gcd = zeros(Int, n - 1)

  left_gcd[1] = black_board_numbers[1]
  right_gcd[1] = black_board_numbers[n]

  for i = 2:n - 1
    left_gcd[i] = gcd(left_gcd[i - 1], black_board_numbers[i])
    right_gcd[i] = gcd(right_gcd[i - 1], black_board_numbers[n - i + 1])
  end

  max_gcd = max(left_gcd[n - 1], right_gcd[n - 1])

  for i = 2:n - 1
    max_gcd = max(max_gcd, gcd(left_gcd[i - 1], right_gcd[n - i]))
  end

  println(max_gcd)
end


let
  n = parse(Int, readline())
  black_board_numbers = map(x -> parse(Int, x), split(readline()))

  left_gcd = zeros(Int, n - 1)
  right_gcd = zeros(Int, n - 1)

  left_gcd[1] = black_board_numbers[1]
  right_gcd[n - 1] = black_board_numbers[n]

  for i = 2:n - 1
    left_gcd[i] = gcd(left_gcd[i - 1], black_board_numbers[i])
    right_gcd[n - i] = gcd(right_gcd[n - i + 1], black_board_numbers[n - i + 1])
  end

  max_gcd = max(left_gcd[n - 1], right_gcd[1])

  for i = 2:n - 1
    max_gcd = max(max_gcd, gcd(left_gcd[n - i], right_gcd[i]))
  end

  println(max_gcd)
end


function main()
  n = parse(Int, readline())
  a = map(x -> parse(Int, x), split(readline(), " "))

  lgcd = zeros(Int, n)
  rgcd = zeros(Int, n)

  for i in 1:n
    if i == 1
      lgcd[i] = a[i]
    else
      lgcd[i] = gcd(a[i], lgcd[i-1])
    end
  end

  for i in 1:n
    if i == 1
      rgcd[end-i+1] = a[end]
    else
      rgcd[end-i+1] = gcd(a[end-i+1], rgcd[end-i+2])
    end
  end

  ans = 0
  for i in 1:n
    if i == 1
      temp = rgcd[i+1]
    elseif i == n
      temp = lgcd[i-1]
    else
      temp = gcd(lgcd[i-1], rgcd[i+1])
    end
    ans = temp > ans ? temp : ans
  end
  println(ans)
end

main()


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

function main()
	n = readline() |> parseInt
	a = readline() |> split |> parseMap
	if length(a) == 2
		println(maximum(a))
	else
		k = Array{Int}(n)
		k[1] = lcm(a[1],a[2],a[n])
		for i in 2:n-1
			k[i] = lcm(a[i-1],a[i],a[i+1])
		end
		k[n] = lcm(a[n-1],a[n],a[1])
		x = indmin(k)
		deleteat!(a,x)
		println(gcd(a))
	end
end
main()


function f()
    n = parse(Int, chomp(readline()))
    a = map(x -> parse(Int, x), split(chomp(readline()), " "))

    if all(a .== a[1])
        print(a[1])
    else
        id = a % 2 .== 0
        if all(id .== false)
            print(findmax(a)[1])
        else
            gusu = a[id]
            min = findmin(gusu)[1]

            amari = gusu % min
            ret = 0
            while any(amari .!= 0)
                ret = findmax(amari)[1]
                amari = gusu % findmax(amari)[1]
            end
            print(ret)
        end
    end
end
f()


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

function main()
	n = readline() |> parseInt
	a = readline() |> split |> parseMap
	if length(a) == 2
		println(maximum(a))
	else
		k = Array{Int}(n)
		for i in 1:n-1
			k[i] = gcd(a[i],a[i+1])
		end
		k[n] = gcd(a[n],a[1])
	    tmp = k[n]
		for i in 0:n-2
			k[n-i] = lcm(k[n-i-1],k[n-i])
		end
		k[1] = lcm(tmp,k[1])
		x = indmin(k)
		deleteat!(a,x)
		println(gcd(a))
	end
end
main()


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

function main()
	n = readline() |> parseInt
	a = readline() |> split |> parseMap
	if length(a) == 2
		println(maximum(a))
	else
		k = Array{Int}(n)
		for i in 1:n-1
			k[i] = gcd(a[i],a[i+1])
		end
		k[n] = gcd(a[n],a[1])
	    tmp = k[n]
		for i in 0:n-2
			k[n-i] = gcd(k[n-i-1],k[n-i])
		end
		k[1] = gcd(tmp,k[1])
		x = indmin(k)
		deleteat!(a,x)
		println(gcd(a))
	end
end
main()


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

function main()
	n = readline() |> parseInt
	a = readline() |> split |> parseMap
	if length(a) == 2
		println(maximum(a))
	else
		k = Array{Int}(n)
		for i in 1:n-1
			k[i] = gcd(a[i],a[i+1])
		end
		k[n] = gcd(a[n],a[1])
	    tmp = k[n]
		for i in 0:n-2
			k[n-i] = k[n-i-1]*k[n-i]
		end
		k[1] = tmp*k[1]
		x = indmin(k)
		deleteat!(a,x)
		println(gcd(a))
	end
end
main()


function f()
    n = parse(Int, chomp(readline()))
    a = map(x -> parse(Int, x), split(chomp(readline()), " "))

    check = findmax(a)[1]
    if all(a .== check)
        print(check)
    end

    id = a % 2 .== 0
    max = findmax(a[id])[1]
    min = findmin(a[id])[1]
    ret = max - min
    print(ret)
end
f()


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

function main()
	q = 998244353
	n = readline() |> parseInt
	a = zeros(Int,n)
	for i in 1:n
		a[i] = readline() |> parseInt
	end
	s = sum(a)
	dp = zeros(Int,n+1,s+1,n+1)
	dp[1,1,1] = 1
	for i in 1:n
		for j in 1:s+1
			for k in 1:n
				if dp[i,j,k]>0
					dp[i+1,j,k] += dp[i,j,k]
					dp[i+1,j+a[i],k+1] += dp[i,j,k]
				end
			end
		end
	end
	x = 0
	k2 = zeros(Int32,n+1)
	k2[1] = 1
	for i in 2:n+1
		k2[i] = (k2[i-1]*2)%q
	end
	for j in (s+1)>>1+1:s+1
		for k in 1:n-2
			if dp[n+1,j,k+1] > 0
				x = (((k2[n-k+1]-2)*3*dp[n+1,j,k+1]%q)+x)%q
			end
		end
	end
	y = 1
	for i in 1:n
		y = (y*3)%q
	end
	z = y-3*k2[n+1]-x+3
	while z<0
		z += q
	end
	println(z)
end

main()

Score : 600 points

Problem Statement

You are given N integers. The i-th integer is a_i.
Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied:

Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area whose sides have lengths R, G and B.

Constraints

3 \leq N \leq 300

1 \leq a_i \leq 300(1\leq i\leq N)

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 number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the condition is satisfied.

Sample Input 1

4
1
1
1
2

Sample Output 1

18

We can only paint the integers so that the lengths of the sides of the triangle will be 1, 2 and 2, and there are 18 such ways.

Sample Input 2

6
1
3
2
3
5
2

Sample Output 2

150

Sample Input 3

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

Sample Output 3

563038556


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    a,b,c=parseMap(split(readline()))
    println(min(c,div(b,a)))
end
main()

Score : 100 points

Problem Statement

Takahashi likes the sound when he buys a drink from a vending machine.

That sound can be heard by spending A yen (the currency of Japan) each time.

Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time.

How many times will he hear the sound?

Constraints

All values in input are integers.

1 \leq A, B, C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times Takahashi will hear his favorite sound.

Sample Input 1

2 11 4

Sample Output 1

4

Since he has not less than 8 yen, he will hear the sound four times and be satisfied.

Sample Input 2

3 9 5

Sample Output 2

3

He may not be able to be satisfied.

Sample Input 3

100 1 10

Sample Output 3

0


const lines=readlines(open("/dev/fd/0"))
input()=shift!(lines)
int(s::String)=parse(Int32,s)
intSub(s::SubString{String})=parse(Int32,s)
intLine()=map(intSub,split(input()))
function main()
    a,b,c=intLine()
    println(min(c,Int(floor(b/a))))
end
main()


parseInt(x) = parse(Int,x)
parseMap(x::Array{SubString{String}, 1}) = map(parseInt, x)
function main()
    a,b,c = map(parseInt, split(readline()))
  	if b/a < c
    	println(Int64(floor(b/a)))
  else
    println(Int64(c))
  end
end
main()


parseInt(x) = parse(Int,x)
parseMap(x::Array{SubString{String}, 1}) = map(parseInt, x)
function main()
    a,b,c = map(parseInt, split(readline()))
  	if b/a > c
    	println(Int64(b÷a))
  else
    println(c)
  end
end
main()


parseInt(x) = parse(Int,x)
parseMap(x::Array{SubString{String}, 1}) = map(parseInt, x)
function main()
    a,b,c = map(parseInt, split(readline()))
  	if b/a > c
    	println(b÷a)
  else
    println(c)
  end
end
main()


parseInt(x) = parse(Int,x)
parseMap(x::Array{SubString{String}, 1}) = map(parseInt, x)
function main()
    a,b,c = map(parseInt, split(readline()))
  	if b/a > c
    	println(floor(b/a))
  else
    println(c)
  end
end
main()


a,b,c = parse.(split(readline()))
println(floor(Int64,b/a)<c?floor(Int64,b/a):c)


a,b,c=map(x->parse(x),split(readline()))
t=floor(Int,b/a)
if t<c
  print(t)
else
  print(c)
end


function f()
    input = map(x -> parse(Int, x), split(chomp(readline()), " "))
    a = input[1]
    b = input[2]
    c = input[3]

    d = floor(b / a)

    if b < a
        print("0")
    elseif d >= c
        print(c)
    else
        print(Int(d))
    end
end
f()


function f()
    input = map(x -> parse(Int, x), split(chomp(readline()), " "))
    a = input[1]
    b = input[2]
    c = input[3]

    d = b / a

    if b < a
        print("0")
    elseif d > c
        print(c)
    else
        print(Int(d))
    end
end
f()


function main()

  n = parse(Int, readline())
  h = parse.(Int, split(readline()))

  dp = [0, abs(h[2]-h[1])]
  for i in 3:n
    push!(dp, min(dp[i-1] + abs(h[i]-h[i-1]), dp[i-2] + abs(h[i]-h[i-2])))
  end

  println(dp[n])

end

main()

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 30 40 20

Sample Output 1

30

If we follow the path 1 → 2 → 4, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

2
10 10

Sample Output 2

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 3

6
30 10 60 10 60 50

Sample Output 3

40

If we follow the path 1 → 3 → 5 → 6, the total cost incurred would be |30 - 60| + |60 - 60| + |60 - 50| = 40.


data = readlines()
N = parse(Int, data[1])
h = parse.(Int, split(data[2]))
d(i, j) = abs(h[i]-h[j])
dp_mtx = [zeros(Int, 10sum(h)) for n in 1:N]
function main(present)
    now = present == 1 ? 1 : findfirst(x->x==1, dp_mtx[present])
    present<N && (dp_mtx[present+1][now + d(present, present+1)] = 1)
    present<N-1 && (dp_mtx[present+2][now + d(present, present+2)] = 1)
    return present<N ? main(present+1) : println(findfirst(x->x==1, dp_mtx[N])-1)
end
main(1)


data = readlines()
N = parse(Int, data[1])
h = parse.(Int, split(data[2]))
d(i, j) = abs(h[i]-h[j])
dp_mtx = [zeros(Int, sum(h)) for n in 1:N]
function main(present)
    now = present == 1 ? 1 : findfirst(x->x==1, dp_mtx[present])
    present<N && (dp_mtx[present+1][now + d(present, present+1)] = 1)
    present<N-1 && (dp_mtx[present+2][now + d(present, present+2)] = 1)
    return present<N ? main(present+1) : println(findfirst(x->x==1, dp_mtx[N])-1)
end
main(1)


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

const INF=2<<32
function main()
    n::Int=parseInt(readline())
    h::Vector{Int}=vcat(parseMap(split(readline())),[INF])
    dp::Vector{Int}=fill(INF,100010)
    dp[1]=0
    for i in 1:n-1
        dp[i+1]=min(dp[i+1],dp[i]+abs(h[i]-h[i+1]))
        dp[i+2]=min(dp[i+2],dp[i]+abs(h[i]-h[i+2]))
    end
    println(dp[n])
end
main()


if isfile("mystdin.txt");mystdin=open("mystdin.txt","r");redirect_stdin(mystdin);end
pI(x)=parse(Int,x)
pM(x::Array{SubString{String},1})=map(pI,x)
function main()
  n=pI(readline())
  h=pM(split(readline()))
  dp=[0 for i=1:n]
  dp[2]=abs(h[1]-h[2])
  for i=3:n
    dp[i]=min(dp[i-1]+abs(h[i]-h[i-1]),dp[i-2]+abs(h[i]-h[i-2]))
  end
  println(dp[end])
end
main()
if isdefined(Base, :mystdin);close(mystdin);end


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

function main()
    INF = 10 ^ 5
    N = parseInt(readline())
    H = parseMap(split(readline()))
    dp = fill(INF,N)
    dp[1] = 0
    for i in 2:N
        if i > 2
            o = dp[i-1] + abs(H[i-1] - H[i])
            t = dp[i-2] + abs(H[i-2] - H[i])
            dp[i] = min(o,t)
        else
            dp[i] = dp[i-1] + abs(H[i-1] - H[i])
        end
    end
    println(dp[N])
end

main()


INF = 1000000000
read(T) = parse(T, readline())
reads(T) = map(x->parse(T,x),split(readline()))

function main()
    n = read(Int)
    v = reads(Int)
    dp = [INF for i in 1:n]
    dp[1] = 0
    for i in 1:n-1
        if (i + 1 <= n) dp[i+1] = min(dp[i+1], dp[i] + abs(v[i] - v[i+1])) end
        if (i + 2 <= n) dp[i+2] = min(dp[i+2], dp[i] + abs(v[i] - v[i+2])) end
    end
    println(dp[n])
end

@inbounds main()


INF = 1000000000
read(T) = parse(T, readline())
reads(T) = map(x->parse(T,x),split(readline()))

function main()
    n = read(Int)
    v = reads(Int)
    dp = [INF for i in 1:n]
    dp[1] = 0
    for i in 1:n-1
        if (i + 1 <= n) dp[i+1] = min(dp[i+1], dp[i] + abs(v[i] - v[i+1])) end
        if (i + 2 <= n) dp[i+2] = min(dp[i+2], dp[i] + abs(v[i] - v[i+2])) end
    end
    println(dp[n])
end

main()


function memoit(f::Function, param)
    if !isdefined(Main, :memoit_cache)
        global memoit_cache = Dict{Function, Dict{Any, Any}}()
    end
    cache = haskey(memoit_cache, f) ? memoit_cache[f] : memoit_cache[f] = Dict()
    haskey(cache, param) ? cache[param] : cache[param] = f(param)
end

macro memo(arg)
    return quote
        memoit($(esc(arg.args[1])), $(esc(arg.args[2])))
    end
end

read(T) = parse(T, readline())
reads(T) = map(x->parse(T,x),split(readline()))

function dp(n::Int)
    ret = 1000000000
    if (n == 1) ret = 0 end
    if (n > 1) ret = min(ret, ((@memo dp(n-1)) + abs(v[n] -  v[n-1]))) end
    if (n > 2) ret = min(ret, ((@memo dp(n-2)) + abs(v[n] -  v[n-2]))) end
    ret
end

function main()
    n = read(Int)
    global v = reads(Int)
    println(dp(n))
end

main()


function memoit(f::Function, param)
    if !isdefined(Main, :memoit_cache)
        global memoit_cache = Dict{Function, Dict{Any, Any}}()
    end
    cache = haskey(memoit_cache, f) ? memoit_cache[f] : memoit_cache[f] = Dict()
    haskey(cache, param) ? cache[param] : cache[param] = f(param)
end

macro memo(arg)
    (!(typeof(arg) <: Expr) || !(arg.head == :call)) && error("wrong atgs")
    return quote
        memoit($(esc(arg.args[1])), $(esc(arg.args[2])))
    end
end

read(T) = parse(T, readline())
reads(T) = map(x->parse(T,x),split(readline()))

function dp(n::Int)
    ret = 1000000000
    if (n == 1) ret = 0 end
    if (n > 1) ret = min(ret, ((@memo dp(n-1)) + abs(v[n] -  v[n-1]))) end
    if (n > 2) ret = min(ret, ((@memo dp(n-2)) + abs(v[n] -  v[n-2]))) end
    ret
end

function main()
    n = read(Int)
    global v = reads(Int)
    println(dp(n))
end

main()


function memoit(f::Function, param)
    if !isdefined(Main, :memoit_cache)
        global memoit_cache = Dict{Function, Dict{Any, Any}}()
    end
    cache = haskey(memoit_cache, f) ? memoit_cache[f] : memoit_cache[f] = Dict()
    haskey(cache, param) ? cache[param] : cache[param] = f(param)
end

macro memo(arg)
    (!(typeof(arg) <: Expr) || !(arg.head == :call)) && error("wrong atgs")
    return quote
        memoit($(esc(arg.args[1])), $(esc(arg.args[2])))
    end
end

read(T) = parse(T, readline())
reads(T) = map(x->parse(T,x),split(readline()))

function dp(n::Int)
    ret = 1000000000
    if (n == 1) ret = 0 end
    if (n > 1) ret = min(ret, ((@memo dp(n-1)) + abs(v[n] -  v[n-1]))) end
    if (n > 2) ret = min(ret, ((@memo dp(n-2)) + abs(v[n] -  v[n-2]))) end
    ret
end

function main()
    n = read(Int)
    global v = reads(Int)
    println(dp(n))
end

@inbounds main()


function memoit(f::Function, param)
    if !isdefined(Main, :memoit_cache)
        global memoit_cache = Dict{Function, Dict{Any, Any}}()
    end
    cache = haskey(memoit_cache, f) ? memoit_cache[f] : memoit_cache[f] = Dict()
    haskey(cache, param) ? cache[param] : cache[param] = f(param)
end

macro memo(arg)
    (!(typeof(arg) <: Expr) || !(arg.head == :call)) && error("wrong atgs")
    return quote
        memoit($(esc(arg.args[1])), $(esc(arg.args[2])))
    end
end

read(T) = parse(T, readline(stdin))
reads(T) = map(x->parse(T,x),split(readline()))

function dp(n::Int)
    ret = 1000000000
    (n == 1) && local ret = 0
    (n > 1) && local ret = min(ret, ((@memo dp(n-1)) + abs(v[n] -  v[n-1])))
    (n > 2) && local ret = min(ret, ((@memo dp(n-2)) + abs(v[n] -  v[n-2])))
    ret
end

function main()
    n = read(Int)
    global v = reads(Int)
    println(dp(n))
end

@inbounds main()


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

function main()
	n = readline() |> parseInt
	h = readline() |> split |> parseMap
	dp = Array{Int}(n)
	dp[1] = 0
	dp[2] = abs(h[2]-h[1])
	for i in 3:n
		dp[i] = min(dp[i-2]+abs(h[i]-h[i-2]),dp[i-1]+abs(h[i]-h[i-1]))
	end
	println(dp[n])
end

main()


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

const INF=2<<32
function main()
    n::Int,k::Int=parseMap(split(readline()))
    h::Vector{Int}=parseMap(split(readline()))
    dp::Vector{Int}=fill(INF,100010)
    dp[1]=0
    for i in 1:n-1
        for j in 1:k
            if i+j>n
                break
            end
            dp[i+j]=min(dp[i+j],dp[i]+abs(h[i]-h[i+j]))
        end
    end
    println(dp[n])
end
main()

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 100

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

5 3
10 30 40 50 20

Sample Output 1

30

If we follow the path 1 → 2 → 5, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

3 1
10 20 10

Sample Output 2

20

If we follow the path 1 → 2 → 3, the total cost incurred would be |10 - 20| + |20 - 10| = 20.

Sample Input 3

2 100
10 10

Sample Output 3

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 4

10 4
40 10 20 70 80 10 20 70 80 60

Sample Output 4

40

If we follow the path 1 → 4 → 8 → 10, the total cost incurred would be |40 - 70| + |70 - 70| + |70 - 60| = 40.


N, K = parse.(Int, split(readline()))
hs = parse.(Int, split(readline()))

a = zeros(Int, N)
a[1] = 0
a[2] = abs(hs[2] - hs[1])

for i in 3:N
    b = zeros(Int, K)
    for j in 1:K
        b[j] = a[max(i-j,1)] + abs(hs[i] - hs[max(i-j,1)])
    end
    a[i] = minimum(b)
end
println(a[end])


N, K = parse.(Int, split(readline()))
hs = parse.(Int, split(readline()))

i = 0
total_cost = 0

a = zeros(Int, N)
a[1] = 0
a[2] = abs(hs[2] - hs[1])

for i in 3:N
    bmin = Inf
    for j in 1:K
        bmin = min(bmin, a[max(i-j,1)] + abs(hs[i] - hs[max(i-j,1)]))
    end
    a[i] = bmin
end
println(a[end])


if isfile("mystdin.txt");mystdin=open("mystdin.txt","r");redirect_stdin(mystdin);end
pI(x)=parse(Int,x)
pM(x::Array{SubString{String},1})=map(pI,x)
function main()
  n,k=pM(split(readline()))
  h=pM(split(readline()))
  dp=Int[100000000000 for i=1:n+k]
  dp[1]=0
  for i=1:n-1
    for j=1:k
      if i+j<=n
        dp[i+j]=min(dp[i+j],dp[i]+abs(h[i+j]-h[i]))
      end
    end
  end
  println(dp[n])
end
main()
if isdefined(Base, :mystdin);close(mystdin);end


if isfile("mystdin.txt");mystdin=open("mystdin.txt","r");redirect_stdin(mystdin);end
pI(x)=parse(Int,x)
pM(x::Array{SubString{String},1})=map(pI,x)
function main()
  n,k=pM(split(readline()))
  h=pM(split(readline()))
  dp=BigInt[100000000000 for i=1:n+k]
  dp[1]=0
  for i=1:n-1
    for j=1:k
      if i+j<=n
        dp[i+j]=min(dp[i+j],dp[i]+abs(h[i+j]-h[i]))
      end
    end
  end
  println(dp[n])
end
main()
if isdefined(Base, :mystdin);close(mystdin);end