parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
abs(a::Int32)=a<0?-a:a
addAll(a::Set{Int32},x::Int32)=map(f->f+x,a)
operation(b::Set{Int32},a::Set{Int32},x::Int32)=union(b,addAll(a,x),addAll(a,-x))
operation(b::Set{Int32},a::Set{Int32},x::Int32,y::Int32)=union(b,addAll(a,x),addAll(a,-x),addAll(a,-y),addAll(a,y))

function read()
	h,w = readline() |> split |> parseMap
	a = zeros(Int32,h,w)
	b = zeros(Int32,h,w)
	for i in 1:h
		a[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		b[i,:] = readline() |> split |> parseMap
	end
	c = zeros(Int32,h,w)
	for i in 1:h
		for j in 1:w
			c[i,j] = abs(a[i,j]-b[i,j])
		end
	end
	main(h,w,c)
end

function main(h::Int,w::Int,c::Array{Int32,2})
	ms = 80
	base = (h+w)*ms

	dp = [Set{Int32}() for i in 1:h+w-1]
	push!(dp[1],c[1,1])
	for p in 1:h+w-2
		for q in max(1,p+1-h):min(p,w)
			x = p-q+1
			y = q
			if y<w&&x<h
				dp[p+1]=operation(dp[p+1],dp[p],c[x,y+1],c[x+1,y])
			elseif y<h
				dp[p+1]=operation(dp[p+1],dp[p],c[x,y+1])
			elseif x<h
				dp[p+1]=operation(dp[p+1],dp[p],c[x+1,y])
			end
		end
	end
	z = base
	for i in dp[h+w-1]
		z = min(z,abs(i))
	end
	println(z)
end

read()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
abs(a::Int32)=a<0?-a:a
addAll(a::Set{Int32},x::Int32)=map(f->f+x,a)
operation(a::Set{Int32},x::Int32)=union(addAll(a,x),addAll(a,-x))
doperation(b::Set{Int32},a::Set{Int32},x::Int32)=union(b,addAll(a,x),addAll(a,-x))

function spush(s::Set{Int32},x::Int32)
	if !(x in s)
		push!(s,x)
	end
end

function read()
	h,w = readline() |> split |> parseMap
	a = zeros(Int32,h,w)
	b = zeros(Int32,h,w)
	for i in 1:h
		a[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		b[i,:] = readline() |> split |> parseMap
	end
	c = zeros(Int32,h,w)
	for i in 1:h
		for j in 1:w
			c[i,j] = abs(a[i,j]-b[i,j])
		end
	end
	main(h,w,c)
end

function main(h::Int,w::Int,c::Array{Int32,2})
	ms = 80
	base = (h+w)*ms

	dp = [Set{Int32}() for i in 1:h+w-1]
	push!(dp[1],c[1,1])
	for p in 1:h+w-2
		for q in max(1,p+1-h):min(p,w)
			x = p-q+1
			y = q
			if y<w
				dp[p+1]=operation(dp[p],c[x,y+1])
			end
			if x<h
				dp[p+1]=doperation(dp[p+1],dp[p],c[x+1,y])
			end
		end
	end
	z = base
	for i in dp[h+w-1]
		z = min(z,abs(i))
	end
	println(z)
end

read()

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

Score : 500 points

Problem Statement

We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.

The square (i, j) has two numbers A_{ij} and B_{ij} written on it.

First, for each square, Takahashi paints one of the written numbers red and the other blue.

Then, he travels from the square (1, 1) to the square (H, W). In one move, he can move from a square (i, j) to the square (i+1, j) or the square (i, j+1). He must not leave the grid.

Let the unbalancedness be the absolute difference of the sum of red numbers and the sum of blue numbers written on the squares along Takahashi's path, including the squares (1, 1) and (H, W).

Takahashi wants to make the unbalancedness as small as possible by appropriately painting the grid and traveling on it.

Find the minimum unbalancedness possible.

Constraints

2 \leq H \leq 80

2 \leq W \leq 80

0 \leq A_{ij} \leq 80

0 \leq B_{ij} \leq 80

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W
A_{11} A_{12} \ldots A_{1W}
:
A_{H1} A_{H2} \ldots A_{HW}
B_{11} B_{12} \ldots B_{1W}
:
B_{H1} B_{H2} \ldots B_{HW}

Output

Print the minimum unbalancedness possible.

Sample Input 1

2 2
1 2
3 4
3 4
2 1

Sample Output 1

0

By painting the grid and traveling on it as shown in the figure below, the sum of red numbers and the sum of blue numbers are 3+3+1=7 and 1+2+4=7, respectively, for the unbalancedness of 0.

Sample Input 2

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

Sample Output 2

2

Submitted source-code file size, in bytes.

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

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


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function spush(s::Set{Int32},x::Int32)
	if !(x in s)
		push!(s,x)
	end
end

function main()
	h,w = readline() |> split |> parseMap
	a = zeros(Int32,h,w)
	b = zeros(Int32,h,w)
	ms = 0
	for i in 1:h
		a[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		b[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		for j in 1:w
			ms = max(ms,a[i,j]-b[i,j],b[i,j]-a[i,j])
		end
	end
	base = (h+w)*ms
	dp = [Set{Int32}() for i in 1:h+w-1]
	push!(dp[1],a[1,1]-b[1,1])
	push!(dp[1],-a[1,1]+b[1,1])
	for p in 1:h+w-2
		for q in max(1,p+1-h):min(p,w)
			x = p-q+1
			y = q
			if y<w
				for i in dp[p]
					v1 = a[x,y+1]-b[x,y+1]
					spush(dp[p+1],i-v1)
					spush(dp[p+1],i+v1)
				end
			end
			if x<h
				for i in dp[p]
					v2 = a[x+1,y]-b[x+1,y]
					spush(dp[p+1],i-v2)
					spush(dp[p+1],i+v2)
				end
			end
		end
	end
	z = base
	for i in dp[h+w-1]
		z = min(z,abs(i))
	end
	println(z)
end

main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function spush(s::Set{Int32},x::Int32)
	if !(x in s)
		push!(s,x)
	end
end

function main()
	h,w = readline() |> split |> parseMap
	a = zeros(Int32,h,w)
	b = zeros(Int32,h,w)
	ms = 0
	for i in 1:h
		a[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		b[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		for j in 1:w
			ms = max(ms,a[i,j]-b[i,j],b[i,j]-a[i,j])
		end
	end
	base = (h+w)*ms
	dp = [Set{Int32}() for i in 1:h*w]
	push!(dp[1],a[1,1]-b[1,1])
	push!(dp[1],-a[1,1]+b[1,1])
	for x in 1:h
		for y in 1:w
			if y<w
				v1 = a[x,y+1]-b[x,y+1]
				for i in dp[(x-1)*w+y]
					spush(dp[(x-1)*w+y+1],i-v1)
					spush(dp[(x-1)*w+y+1],i+v1)
				end
			end
			if x<h
				v2 = a[x+1,y]-b[x+1,y]
				for i in dp[(x-1)*w+y]
					spush(dp[x*w+y],i-v2)
					spush(dp[x*w+y],i+v2)
				end
			end
		end
	end
	z = base
	for i in dp[h*w]
		z = min(z,abs(i))
	end
	println(z)
end

main()


function make(k,X,D,N)
	L=fld(k*X,D)
	U=L+div(k*(k-1),2)=>L+N*k-div(k*(k+1),2)
	mod(k*X,D)=>U
end
function main()
	N,X,D=map(x->parse(Int,x),split(readline()))
	if D==0
		println(X==0 ? 1 : N+1)
		exit()
	end
	if D<0
		D=-D
		X=-X
	end
	S=Pair{Int,Pair{Int,Int}}[]
	for k=0:N
		push!(S,make(k,X,D,N))
	end
	ans=0
	pm=-1
	pre=0
	for (k,(l,r))=sort(S)
		if k==pm
			ans+=max(0,r-max(pre,l-1))
			pre=max(pre,r)
		else
			pm=k
			ans+=r-l+1
			pre=r
		end
	end
	println(ans)
end
main()

Score : 600 points

Problem Statement

We have an integer sequence A of length N, where A_1 = X, A_{i+1} = A_i + D (1 \leq i < N ) holds.

Takahashi will take some (possibly all or none) of the elements in this sequence, and Aoki will take all of the others.

Let S and T be the sum of the numbers taken by Takahashi and Aoki, respectively. How many possible values of S - T are there?

Constraints

-10^8 \leq X, D \leq 10^8

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X D

Output

Print the number of possible values of S - T.

Sample Input 1

3 4 2

Sample Output 1

8

A is (4, 6, 8).

There are eight ways for (Takahashi, Aoki) to take the elements: ((), (4, 6, 8)), ((4), (6, 8)), ((6), (4, 8)), ((8), (4, 6))), ((4, 6), (8))), ((4, 8), (6))), ((6, 8), (4))), and ((4, 6, 8), ()).

The values of S - T in these ways are -18, -10, -6, -2, 2, 6, 10, and 18, respectively, so there are eight possible values of S - T.

Sample Input 2

2 3 -3

Sample Output 2

2

A is (3, 0). There are two possible values of S - T: -3 and 3.

Sample Input 3

100 14 20

Sample Output 3

49805


function f(kv)
	pre=-10^18
	ret=0
	for (l,r)=kv
		ret+=max(0,r-max(pre,l-1))
		pre=max(pre,r)
	end
	ret
end
function main()
	N,X,D=map(x->parse(Int,x),split(readline()))
	if D==0
		println(X==0 ? 1 : N+1)
		exit()
	end
	if D<0
		D=-D
		X=-X
	end
	S=Pair{Int,Pair{Int,Int}}[]
	for k=0:N
		L=fld(k*X,D)
		U=L+div(k*(k-1),2)=>L+N*k-div(k*(k+1),2)
		push!(S,mod(k*X,D)=>U)
	end
	ans=0
	pm=-1
	pre=0
	for (k,(l,r))=sort(S)
		if k==pm
			ans+=max(0,r-max(pre,l-1))
		else
			pm=k
			ans+=r-l+1
		end
		pre=r
	end
	println(ans)
end
main()


function main()
N = parse(readline())
x = div(N,1.08)
ans = false
for i in x-10:x+10
    money = 1.08*i
    money = trunc(money)
    if money == N
        println(i)
        ans = true
    end
end
if ans != true
    println(":(")
end
end
main()

Score: 200 points

Problem Statement

Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it.

The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer).

Takahashi forgot the price of his apple pie before tax, X, and wants to know it again. Write a program that takes N as input and finds X. We assume X is an integer.

If there are multiple possible values for X, find any one of them. Also, Takahashi's memory of N, the amount he paid, may be incorrect. If no value could be X, report that fact.

Constraints

1 \leq N \leq 50000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If there are values that could be X, the price of the apple pie before tax, print any one of them.

If there are multiple such values, printing any one of them will be accepted.

If no value could be X, print :(.

Sample Input 1

432

Sample Output 1

400

If the apple pie is priced at 400 yen before tax, you have to pay 400 \times 1.08 = 432 yen to buy one.

Otherwise, the amount you have to pay will not be 432 yen.

Sample Input 2

1079

Sample Output 2

:(

There is no possible price before tax for which you have to pay 1079 yen with tax.

Sample Input 3

1001

Sample Output 3

927

If the apple pie is priced 927 yen before tax, by rounding down 927 \times 1.08 = 1001.16, you have to pay 1001 yen.


function main()
N = parse(readline())
x = div(N,1.08)
x = convert(Int,x)
ans = false
for i in x:x+500
    money = 1.08*i
    if money == N
        println(i)
        ans = true
        break
    end
end
if ans != true
    println(":(")
end
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()
  x=pI(readline())
  if x>=2000
    println(1)
  elseif x%100<=fld(x,100)*5
    println(1)
  else
    println(0)
  end
end
main()
if isdefined(Base, :mystdin);close(mystdin);end

Score: 300 points

Problem Statement

AtCoder Mart sells 1000000 of each of the six items below:

Riceballs, priced at 100 yen (the currency of Japan) each

Sandwiches, priced at 101 yen each

Cookies, priced at 102 yen each

Cakes, priced at 103 yen each

Candies, priced at 104 yen each

Computers, priced at 105 yen each

Takahashi wants to buy some of them that cost exactly X yen in total.
Determine whether this is possible.

(Ignore consumption tax.)

Constraints

1 \leq X \leq 100000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If it is possible to buy some set of items that cost exactly X yen in total, print 1; otherwise, print 0.

Sample Input 1

615

Sample Output 1

1

For example, we can buy one of each kind of item, which will cost 100+101+102+103+104+105=615 yen in total.

Sample Input 2

217

Sample Output 2

0

No set of items costs 217 yen in total.


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

function main()
	x = readline() |> parseInt
	y = x%100
	f = 0
	for b in 0:50
		for c in 0:33
			for d in 0:25
				for e in 0:20
					if (2*b+3*c+4*d+5*e)%100<=y
						v = 102*b+103*c+104*d+105*e+(y-((2*b+3*c+4*d+5*e)%100))*101
						if v==x || (v<x&&v%100==0)
							f = 1
							break
						end
					end
				end
			end
		end
	end
	println(f)
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=parseInt(readline())
    s=chomp(readline())
    ans=0
    for i in 0:999
        t=lpad(i,3,"0")
        tmp=1
        f=true
        for j in 1:3
            flg=false
            for k in tmp:n
                if t[j]==s[k]
                    tmp=k+1
                    flg=true
                    break
                end
            end
            if !flg
                f=false
                break
            end
        end
        if f
            ans+=1
        end
    end
    println(ans)
end
main()

Score: 400 points

Problem Statement

AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code.

The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code.

How many different PIN codes can he set this way?

Both the lucky number and the PIN code may begin with a 0.

Constraints

4 \leq N \leq 30000

S is a string of length N consisting of digits.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of different PIN codes Takahashi can set.

Sample Input 1

4
0224

Sample Output 1

3

Takahashi has the following options:

Erase the first digit of S and set 224.

Erase the second digit of S and set 024.

Erase the third digit of S and set 024.

Erase the fourth digit of S and set 022.

Thus, he can set three different PIN codes: 022, 024, and 224.

Sample Input 2

6
123123

Sample Output 2

17

Sample Input 3

19
3141592653589793238

Sample Output 3

329


T1,T2=map(x->parse(Int,x),split(readline()))
A1,A2=map(x->parse(Int,x),split(readline()))
B1,B2=map(x->parse(Int,x),split(readline()))
X=T1*A1+T2*A2
Y=T1*B1+T2*B2
if X==Y
	println("infinity")
else
	d=(X>Y ? -1 : 1)*(T1*A1-T1*B1)
	D=abs(X-Y)
	if d<0
		println(0)
	elseif d==0
		println(1)
	else
		ans=1
		d-=D
		if d>=0
			ans+=div(d,D)*2+2
			if d%D==0
				ans-=1
			end
		end
		println(ans)
	end
end

Score: 600 points

Problem Statement

Takahashi and Aoki are training for long-distance races in an infinitely long straight course running from west to east.

They start simultaneously at the same point and moves as follows towards the east:

Takahashi runs A_1 meters per minute for the first T_1 minutes, then runs at A_2 meters per minute for the subsequent T_2 minutes, and alternates between these two modes forever.

Aoki runs B_1 meters per minute for the first T_1 minutes, then runs at B_2 meters per minute for the subsequent T_2 minutes, and alternates between these two modes forever.

How many times will Takahashi and Aoki meet each other, that is, come to the same point? We do not count the start of the run. If they meet infinitely many times, report that fact.

Constraints

1 \leq T_i \leq 100000

1 \leq A_i \leq 10^{10}

1 \leq B_i \leq 10^{10}

A_1 \neq B_1

A_2 \neq B_2

All values in input are integers.

Input

Input is given from Standard Input in the following format:

T_1 T_2
A_1 A_2
B_1 B_2

Output

Print the number of times Takahashi and Aoki will meet each other.

If they meet infinitely many times, print infinity instead.

Sample Input 1

1 2
10 10
12 4

Sample Output 1

1

They will meet just once, \frac{4}{3} minutes after they start, at \frac{40}{3} meters from where they start.

Sample Input 2

100 1
101 101
102 1

Sample Output 2

infinity

They will meet 101, 202, 303, 404, 505, 606, ... minutes after they start, that is, they will meet infinitely many times.

Sample Input 3

12000 15700
3390000000 3810000000
5550000000 2130000000

Sample Output 3

113

The values in input may not fit into a 32-bit integer type.


Score : 100 points

Problem Statement

Given is a string S representing the day of the week today.

S is SUN, MON, TUE, WED, THU, FRI, or SAT, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.

After how many days is the next Sunday (tomorrow or later)?

Constraints

S is SUN, MON, TUE, WED, THU, FRI, or SAT.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of days before the next Sunday.

Sample Input 1

SAT

Sample Output 1

1

It is Saturday today, and tomorrow will be Sunday.

Sample Input 2

SUN

Sample Output 2

7

It is Sunday today, and seven days later, it will be Sunday again.


n=parse(Int,readline())
s=chomp(readline())
for i in s
  i+n <= 'Z' ? print(i+n) : print(i+n+('A'-'Z')-1)
end

Score : 200 points

Problem Statement

We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.

Shift each character of S by N in alphabetical order (see below), and print the resulting string.

We assume that A follows Z. For example, shifting A by 2 results in C (A \to B \to C), and shifting Y by 3 results in B (Y \to Z \to A \to B).

Constraints

0 \leq N \leq 26

1 \leq |S| \leq 10^4

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the string resulting from shifting each character of S by N in alphabetical order.

Sample Input 1

2
ABCXYZ

Sample Output 1

CDEZAB

Note that A follows Z.

Sample Input 2

0
ABCXYZ

Sample Output 2

ABCXYZ

Sample Input 3

13
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Sample Output 3

NOPQRSTUVWXYZABCDEFGHIJKLM


parseInt(x) = parse(Int, x)
n = parseInt(readline())
s = chomp(readline())
for i in 1:length(s)
    a = Char((Int(s[i])-Int('A') + n)%26+Int('A'))
    print(a)
end
println()


function main()

  N = parse(Int,readline())
  S = collect(chomp(readline()))

  for i in 1:length(S)

    if S[i] + N > 'Z'
      S[i] += N
      S[i] -= 26
    else
      S[i] += N
    end

  end

  println(join(S))

end

main()


function main()
	N,K=map(x->parse(Int,x),split(readline()))
	A=map(x->parse(Int,x),split(readline()))
	D=Dict{Int,Int}()
	D[0]=1
	X=[0]
	now=0
	ans=0
	for a=A
		now=(now+a-1)%K
		push!(X,now)
		if length(X)>K
			D[shift!(X)]-=1
		end
		u=get(D,now,0)
		ans+=u
		D[now]=u+1
	end
	println(ans)
end
main()

Score : 500 points

Problem Statement

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

Find the number of non-empty contiguous subsequences in A such that the remainder when dividing the sum of its elements by K is equal to the number of its elements. We consider two subsequences different if they are taken from different positions, even if they are equal sequences.

Constraints

All values in input are integers.

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

1 \leq K \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_N

Output

Print the number of subsequences that satisfy the condition.

Sample Input 1

5 4
1 4 2 3 5

Sample Output 1

4

Four sequences satisfy the condition: (1), (4,2), (1,4,2), and (5).

Sample Input 2

8 4
4 2 4 2 4 2 4 2

Sample Output 2

7

(4,2) is counted four times, and (2,4) is counted three times.

Sample Input 3

10 7
14 15 92 65 35 89 79 32 38 46

Sample Output 3

8


function main()

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

  ans1 = 0
  ans2 = 0

  if 4 > X
    ans1 = 100000*(4-X)
  end

  if 4 > Y
    ans2 = 100000*(4-Y)
  end

  if X == 1 && Y == 1
    println(1000000)
  else
    println(ans1+ans2)
  end

end

main()

Score: 100 points

Problem Statement

We held two competitions: Coding Contest and Robot Maneuver.

In each competition, the contestants taking the 3-rd, 2-nd, and 1-st places receive 100000, 200000, and 300000 yen (the currency of Japan), respectively. Furthermore, a contestant taking the first place in both competitions receives an additional 400000 yen.

DISCO-Kun took the X-th place in Coding Contest and the Y-th place in Robot Maneuver.
Find the total amount of money he earned.

Constraints

1 \leq X \leq 205

1 \leq Y \leq 205

X and Y are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the amount of money DISCO-Kun earned, as an integer.

Sample Input 1

1 1

Sample Output 1

1000000

In this case, he earned 300000 yen in Coding Contest and another 300000 yen in Robot Maneuver. Furthermore, as he won both competitions, he got an additional 400000 yen.
In total, he made 300000 + 300000 + 400000 = 1000000 yen.

Sample Input 2

3 101

Sample Output 2

100000

In this case, he earned 100000 yen in Coding Contest.

Sample Input 3

4 4

Sample Output 3

0

In this case, unfortunately, he was the highest-ranked contestant without prize money in both competitions.


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()
    h,w,k=parseMap(split(readline()))
    s=[readline() for i in 1:h]
    ans=[[-1 for i in 1:w] for j in 1:h]
    cnt=1
    for i in 1:h
        flg=false
        for j in 1:w
            if s[i][j]=='#'
                if flg
                    cnt+=1
                else
                    flg=true
                end
            end
            ans[i][j]=cnt
        end
        if flg
            cnt+=1
        end
    end
    println(join([join(ans[i]," ") for i in 1:h],"\n"))
end
main()

Score: 400 points

Problem Statement

Chokudai made a rectangular cake for contestants in DDCC 2020 Finals.

The cake has H - 1 horizontal notches and W - 1 vertical notches, which divide the cake into H \times W equal sections. K of these sections has a strawberry on top of each of them.

The positions of the strawberries are given to you as H \times W characters s_{i, j} (1 \leq i \leq H, 1 \leq j \leq W). If s_{i, j} is #, the section at the i-th row from the top and the j-th column from the left contains a strawberry; if s_{i, j} is ., the section does not contain one. There are exactly K occurrences of #s.

Takahashi wants to cut this cake into K pieces and serve them to the contestants. Each of these pieces must satisfy the following conditions:

Has a rectangular shape.

Contains exactly one strawberry.

One possible way to cut the cake is shown below:

Find one way to cut the cake and satisfy the condition. We can show that this is always possible, regardless of the number and positions of the strawberries.

Constraints

1 \leq H \leq 300

1 \leq W \leq 300

1 \leq K \leq H \times W

s_{i, j} is # or ..

There are exactly K occurrences of # in s.

Input

Input is given from Standard Input in the following format:

H W K
s_{1, 1} s_{1, 2} \cdots s_{1, W}
s_{2, 1} s_{2, 2} \cdots s_{2, W}
:
s_{H, 1} s_{H, 2} \cdots s_{H, W}

Output

Assign the numbers 1, 2, 3, \dots, K to the K pieces obtained after the cut, in any order. Then, let a_{i, j} be the number representing the piece containing the section at the i-th row from the top and the j-th column from the left of the cake. Output should be in the following format:

a_{1, 1} \ a_{1, 2} \ \cdots \ a_{1, W}
a_{2, 1} \ a_{2, 2} \ \cdots \ a_{2, W}
:
a_{H, 1} \ a_{H, 2} \ \cdots \ a_{H, W}

If multiple solutions exist, any of them will be accepted.

Sample Input 1

3 3 5
#.#
.#.
#.#

Sample Output 1

1 2 2
1 3 4
5 5 4

One way to cut this cake is shown below:

Sample Input 2

3 7 7
#...#.#
..#...#
.#..#..

Sample Output 2

1 1 2 2 3 4 4
6 6 2 2 3 5 5
6 6 7 7 7 7 7

One way to cut this cake is shown below:

Sample Input 3

13 21 106
.....................
.####.####.####.####.
..#.#..#.#.#....#....
..#.#..#.#.#....#....
..#.#..#.#.#....#....
.####.####.####.####.
.....................
.####.####.####.####.
....#.#..#....#.#..#.
.####.#..#.####.#..#.
.#....#..#.#....#..#.
.####.####.####.####.
.....................

Sample Output 3

12 12 23 34 45 45 60 71 82 93 93 2 13 24 35 35 17 28 39 50 50
12 12 23 34 45 45 60 71 82 93 93 2 13 24 35 35 17 28 39 50 50
12 12 56 89 89 89 60 104 82 31 31 46 13 24 35 35 61 61 39 50 50
12 12 67 67 100 100 60 9 9 42 42 57 13 24 6 72 72 72 72 72 72
12 12 78 5 5 5 20 20 20 53 68 68 90 24 6 83 83 83 83 83 83
16 16 27 38 49 49 64 75 86 97 79 79 90 101 6 94 94 105 10 21 21
16 16 27 38 49 49 64 75 86 97 79 79 90 101 6 94 94 105 10 21 21
32 32 43 54 65 65 80 11 106 95 22 22 33 44 55 55 70 1 96 85 85
32 32 43 54 76 76 91 11 106 84 84 4 99 66 66 66 81 1 96 74 74
14 14 3 98 87 87 102 11 73 73 73 4 99 88 77 77 92 92 63 63 63
25 25 3 98 87 87 7 29 62 62 62 15 99 88 77 77 103 19 30 52 52
36 36 47 58 69 69 18 29 40 51 51 26 37 48 59 59 8 19 30 41 41
36 36 47 58 69 69 18 29 40 51 51 26 37 48 59 59 8 19 30 41 41


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

function main()
	h,w,k = readline() |> split |> parseMap
	a = String["" for i in 1:h]
	fs = 0
	ls = 0
	v = [Int[0] for i in 1:h]
	for i in 1:h
		a[i] = readline() |> chomp
		for j in 1:w
			if a[i][j]=='#'
				if fs == 0
					fs = i
				end
				ls = i
				push!(v[i],j)
			end
		end
	end
	x = 1
	o = zeros(Int,h,w)
	for i in 1:h
		if length(v[i])>1
			for j in 2:length(v[i])-1
				for k in v[i][j-1]+1:v[i][j]
					o[i,k]=x
				end
				x += 1
			end
			for k in v[i][length(v[i])-1]+1:w
				o[i,k]=x
			end
			x += 1
		end
	end
	for i in 1:fs-1
		for j in 1:w
			o[i,j] = o[fs,j]
		end
	end
	for i in ls+1:h
		for j in 1:w
			o[i,j] = o[ls,j]
		end
	end
	for i in 1:h
		for j in 1:w-1
			print(o[i,j]," ")
		end
		println(o[i,w])
	end
end
main()


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

function main()
	m = readline() |> parseInt
	d = 0
	s = 0
	for i in 1:m
		a,b = readline() |> split |> parseMap
		d += b
		s += a
	end
	println(d-1+div(s-1,9))
end

main()

Score: 500 points

Problem Statement

N programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most 9 contestants can participate in the finals.

The preliminary stage consists of several rounds, which will take place as follows:

All the N contestants will participate in the first round.

When X contestants participate in some round, the number of contestants advancing to the next round will be decided as follows:

The organizer will choose two consecutive digits in the decimal notation of X, and replace them with the sum of these digits. The number resulted will be the number of contestants advancing to the next round.

For example, when X = 2378, the number of contestants advancing to the next round will be 578 (if 2 and 3 are chosen), 2108 (if 3 and 7 are chosen), or 2315 (if 7 and 8 are chosen).

When X = 100, the number of contestants advancing to the next round will be 10, no matter which two digits are chosen.

The preliminary stage ends when 9 or fewer contestants remain.

Ringo, the chief organizer, wants to hold as many rounds as possible.
Find the maximum possible number of rounds in the preliminary stage.

Since the number of contestants, N, can be enormous, it is given to you as two integer sequences d_1, \ldots, d_M and c_1, \ldots, c_M, which means the following: the decimal notation of N consists of c_1 + c_2 + \ldots + c_M digits, whose first c_1 digits are all d_1, the following c_2 digits are all d_2, \ldots, and the last c_M digits are all d_M.

Constraints

1 \leq M \leq 200000

0 \leq d_i \leq 9

d_1 \neq 0

d_i \neq d_{i+1}

c_i \geq 1

2 \leq c_1 + \ldots + c_M \leq 10^{15}

Input

Input is given from Standard Input in the following format:

M
d_1 c_1
d_2 c_2
:
d_M c_M

Output

Print the maximum possible number of rounds in the preliminary stage.

Sample Input 1

2
2 2
9 1

Sample Output 1

3

In this case, N = 229 contestants will participate in the first round. One possible progression of the preliminary stage is as follows:

229 contestants participate in Round 1, 49 contestants participate in Round 2, 13 contestants participate in Round 3, and 4 contestants advance to the finals.

Here, three rounds take place in the preliminary stage, which is the maximum possible number.

Sample Input 2

3
1 1
0 8
7 1

Sample Output 2

9

In this case, 1000000007 will participate in the first round.


Score : 100 points

Problem Statement

Given is an integer r.

How many times is the area of a circle of radius r larger than the area of a circle of radius 1?

It can be proved that the answer is always an integer under the constraints given.

Constraints

1 \leq r \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r

Output

Print the area of a circle of radius r, divided by the area of a circle of radius 1, as an integer.

Sample Input 1

2

Sample Output 1

4

The area of a circle of radius 2 is 4 times larger than the area of a circle of radius 1.

Note that output must be an integer - for example, 4.0 will not be accepted.

Sample Input 2

100

Sample Output 2

10000


parseInt(x) = parse(Int, x)
n = parseInt(readline())
s = chomp(readline())

if n % 2 == 1
    println("No")
else
    cnt = 0
    for i in 1:Int(n/2)
        if s[i] == s[Int(n/2)+i]
            global cnt += 1
        end
    end
    if cnt == Int(n/2)
        println("Yes")
    else
        println("No")
    end
end

Score : 200 points

Problem Statement

Given are a positive integer N and a string S of length N consisting of lowercase English letters.

Determine whether the string is a concatenation of two copies of some string.
That is, determine whether there is a string T such that S = T + T.

Constraints

1 \leq N \leq 100

S consists of lowercase English letters.

|S| = N

Input

Input is given from Standard Input in the following format:

N
S

Output

If S is a concatenation of two copies of some string, print Yes; otherwise, print No.

Sample Input 1

6
abcabc

Sample Output 1

Yes

Let T = abc, and S = T + T.

Sample Input 2

6
abcadc

Sample Output 2

No

Sample Input 3

1
z

Sample Output 3

No


function permutation(n::Int)
    if n == 1
        return [[1]]
    else
        p = length(permutation(n-1))
        list = insert!.(permutation(n-1),1,n)
        for i = 2:n
            tmp = permutation(n-1)
            insert!.(tmp,i,n)
            for j = 1:p
                push!(list,tmp[j])
            end
        end
        return list
    end
end

N = parse(Int,readline())
x = zeros(Int,N)
y = zeros(Int,N)
for i = 1:N
    x[i],y[i] = parse.(Int,split(readline()))
end
list = permutation(N)
l = length(list)
d = zeros(l)
for i = 1:l
    for j = 1:N-1
        d[i] += sqrt((x[ list[i][j] ]-x[ list[i][j+1] ])^2+(y[ list[i][j] ]-y[ list[i][j+1] ])^2)
    end
end
println(sum(d)/l)

Score : 300 points

Problem Statement

There are N towns in a coordinate plane. Town i is located at coordinates (x_i, y_i). The distance between Town i and Town j is \sqrt{\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2}.

There are N! possible paths to visit all of these towns once. Let the length of a path be the distance covered when we start at the first town in the path, visit the second, third, \dots, towns, and arrive at the last town (assume that we travel in a straight line from a town to another). Compute the average length of these N! paths.

Constraints

2 \leq N \leq 8

-1000 \leq x_i \leq 1000

-1000 \leq y_i \leq 1000

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

(Added 21:12 JST) All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the average length of the paths.
Your output will be judges as correct when the absolute difference from the judge's output is at most 10^{-6}.

Sample Input 1

3
0 0
1 0
0 1

Sample Output 1

2.2761423749

There are six paths to visit the towns: 1 → 2 → 3, 1 → 3 → 2, 2 → 1 → 3, 2 → 3 → 1, 3 → 1 → 2, and 3 → 2 → 1.

The length of the path 1 → 2 → 3 is \sqrt{\left(0-1\right)^2+\left(0-0\right)^2} + \sqrt{\left(1-0\right)^2+\left(0-1\right)^2} = 1+\sqrt{2}.

By calculating the lengths of the other paths in this way, we see that the average length of all routes is:

\frac{\left(1+\sqrt{2}\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)}{6} = 2.276142...

Sample Input 2

2
-879 981
-866 890

Sample Output 2

91.9238815543

There are two paths to visit the towns: 1 → 2 and 2 → 1. These paths have the same length.

Sample Input 3

8
-406 10
512 859
494 362
-955 -475
128 553
-986 -885
763 77
449 310

Sample Output 3

7641.9817824387


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

function permutation(a,n)
	ans = Array{Int,1}[copy(a)]
	c = ones(Int,n)
	i = 1
	while i<=n
		if c[i]<i
			if i%2==1
				tmp = a[1]
				a[1] = a[i]
				a[i] = tmp
			else
				tmp = a[c[i]]
				a[c[i]] = a[i]
				a[i] = tmp
			end
			c[i] += 1
			i = 1
			push!(ans,copy(a))
		else
			c[i] = 1
			i += 1
		end
	end
	ans
end

function main()
    n = readline() |> parseInt
    a = zeros(Int,2,n)
    for i in 1:n
        a[:,i] = readline() |> split |> parseMap
    end
    g = zeros(Float64,n,n)
    for i in 1:n
        for j in 1:n
            g[i,j] = sqrt((a[1,i]-a[1,j])^2+(a[2,i]-a[2,j])^2)
        end
    end
    arr = Int[i for i in 1:n]
    rev = factorial(n)
    prm = permutation(arr,n)
    s = 0.0
    for i in 1:length(prm)
        for j in 2:n
            s += g[prm[i][j-1],prm[i][j]]/rev
        end
    end
    println(s)
end
main()


parseInt(x) = parse(Int, x)
N_MAX = 1 * 10^6;fac = Array{Int}(N_MAX+1);inv = Array{Int}(N_MAX+1);MOD = 10^9 + 7;
#初期化
function COMINIT();fac[1] = 1;for i in 1:N_MAX-1;fac[i+1] = fac[i] * (i+1) % MOD;end;for i in 1:N_MAX;inv[i] = powermod(fac[i], MOD-2, MOD);end;end;
#nCk
function Comb(n, k);if n <= 0 || k < 0;return 0;end;if k > n;return 0;end;if k == 0 || n == k;return 1;end;return ((fac[n] * inv[k]) % MOD * inv[n-k])%MOD;end;
function H(n, m);return Comb(n + m, m);end;
function main()
    COMINIT()
    x, y = parseInt.(split(readline()))
    z = min(x, y)
    ans = 0
    if (x + y) % 3 == 0
        n = Int((x + y) / 3)
        l = z - n
        if l >= 0
            ans = Comb(n,l)
        end
    end
    println(ans)
end

main()

Score : 400 points

Problem Statement

There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.

When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).

In how many ways can the knight reach the square (X, Y)?

Find the number of ways modulo 10^9 + 7.

Constraints

1 \leq X \leq 10^6

1 \leq Y \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.

Sample Input 1

3 3

Sample Output 1

2

There are two ways: (0,0) \to (1,2) \to (3,3) and (0,0) \to (2,1) \to (3,3).

Sample Input 2

2 2

Sample Output 2

0

The knight cannot reach (2,2).

Sample Input 3

999999 999999

Sample Output 3

151840682

Print the number of ways modulo 10^9 + 7.


#=
D:
- Julia version:
- Author: abap
- Date: 2019-11-16
=#
x,y = parse.(split(readline()))

X,Y = 0,0
for i in 1:x
    X += 2
    Y += 1
    print(X,Y)
    if (x - X)/(y - Y) == 1/2
        yoko = x
        tate = x - X
        break
    end
end
count = factorial(tate + yoko)/(factorial(tate)+factorial(yoko))
println(count % (10^9 +7))


const N,T=map(x->parse(Int,x),split(readline()))
function nxt(dp,a,b)
  ret=0
  ndp=dp[:]
  for j=T:-1:1
    if j+a>T
      ret=max(ret,dp[j]+b)
    else
      ndp[j+a]=max(ndp[j+a],dp[j]+b)
    end
  end
  ret,ndp
end
function main()
  A=Pair{Int,Int}[]
  for s=readlines()
    a,b=map(x->parse(Int,x),split(s))
    push!(A,a=>b)
  end
  sort!(A)
  ans=0
  dp=zeros(Int,T)
  for (a,b)=A
    k,dp=nxt(dp,a,b)
    ans=max(ans,k)
  end
  println(ans)
end
main()

Score : 500 points

Problem Statement

Takahashi is at an all-you-can-eat restaurant.

The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i.

The restaurant has the following rules:

You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.

You cannot order the same kind of dish more than once.

Until you finish eating the dish already served, you cannot order a new dish.

After T-0.5 minutes from the first order, you can no longer place a new order, but you can continue eating the dish already served.

Let Takahashi's happiness be the sum of the deliciousness of the dishes he eats in this restaurant.

What is the maximum possible happiness achieved by making optimal choices?

Constraints

2 \leq N \leq 3000

1 \leq T \leq 3000

1 \leq A_i \leq 3000

1 \leq B_i \leq 3000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N T
A_1 B_1
:
A_N B_N

Output

Print the maximum possible happiness Takahashi can achieve.

Sample Input 1

2 60
10 10
100 100

Sample Output 1

110

By ordering the first and second dishes in this order, Takahashi's happiness will be 110.

Note that, if we manage to order a dish in time, we can spend any amount of time to eat it.

Sample Input 2

3 60
10 10
10 20
10 30

Sample Output 2

60

Takahashi can eat all the dishes within 60 minutes.

Sample Input 3

3 60
30 10
30 20
30 30

Sample Output 3

50

By ordering the second and third dishes in this order, Takahashi's happiness will be 50.

We cannot order three dishes, in whatever order we place them.

Sample Input 4

10 100
15 23
20 18
13 17
24 12
18 29
19 27
23 21
18 20
27 15
22 25

Sample Output 4

145


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

function main()
	n,k = readline() |> split |> parseMap
	h = readline() |> split |> parseMap
	dpv = 10^18*ones(Int,n+1,k+1,2)
	dph = 10^18*ones(Int,n+1,k+1,2)
	dpv[1,1] = 0
	dph[1,1] = 0
	for i in 1:n
		for j in 1:min(k,i)+1
			dpv[i+1,j,1] = min(dpv[i,j,1]+max(h[i]-dph[i,j,1],0),dpv[i,j,2]+max(h[i]-dph[i,j,2],0))
			dph[i+1,j,1]=h[i]
			if j<min(k,i)+1
				if dpv[i,j,1]<dpv[i,j,2]
					dpv[i+1,j+1,2] = dpv[i,j,1]
					dph[i+1,j+1,2] = dph[i,j,1]
				else
					dpv[i+1,j+1,2] = dpv[i,j,2]
					dph[i+1,j+1,2] = dph[i,j,2]
				end
			end
		end
	end
	m = 10^18
	for i in 1:k+1
		for j in 1:2
			m = min(m,dpv[n+1,i,j])
		end
	end
	println(m)
end

main()

Score : 600 points

Problem Statement

We will create an artwork by painting black some squares in a white square grid with 10^9 rows and N columns.

The current plan is as follows: for the i-th column from the left, we will paint the H_i bottommost squares and will not paint the other squares in that column.

Before starting to work, you can choose at most K columns (possibly zero) and change the values of H_i for these columns to any integers of your choice between 0 and 10^9 (inclusive).

Different values can be chosen for different columns.

Then, you will create the modified artwork by repeating the following operation:

Choose one or more consecutive squares in one row and paint them black. (Squares already painted black can be painted again, but squares not to be painted according to the modified plan should not be painted.)

Find the minimum number of times you need to perform this operation.

Constraints

1 \leq N \leq 300

0 \leq K \leq N

0 \leq H_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
H_1 H_2 ... H_N

Output

Print the minimum number of operations required.

Sample Input 1

4 1
2 3 4 1

Sample Output 1

3

For example, by changing the value of H_3 to 2, you can create the modified artwork by the following three operations:

Paint black the 1-st through 4-th squares from the left in the 1-st row from the bottom.

Paint black the 1-st through 3-rd squares from the left in the 2-nd row from the bottom.

Paint black the 2-nd square from the left in the 3-rd row from the bottom.

Sample Input 2

6 2
8 6 9 1 2 1

Sample Output 2

7

Sample Input 3

10 0
1 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000

Sample Output 3

4999999996


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

function main()
    n,k = readline() |> split |> parseMap
    h = readline() |> split |> parseMap
    hh = copy(h)
    if n==k
        println(0)
    else
        t = Tuple{Int,Int}[(0,0) for i in 1:n]
        for i in 1:n
            t[i] = (i,h[i])
        end
        t = sort(t,rev=true,by=x->x[2])
        for i in k:-1:1
            if t[i][1] == 1
                h[t[i][1]] = h[2]
            elseif t[i][1] == n
                h[t[i][1]] = h[n-1]
            else
                h[t[i][1]] = min(h[t[i][1]-1],h[t[i][1]+1])
            end
        end
        s = 0
        x = sort(h)
        for i in 1:n
            c = 0
            f = 0
            q = i==1?x[i]:x[i]-x[i-1]
            for i in 1:n
                if h[i] == 0 && f == 1
                    f = 0
                elseif h[i] > 0 && f == 0
                    f = 1
                    c += 1
                end
                h[i]-=q
            end
            s += c*q
        end

        t = Tuple{Int,Int}[(0,0) for i in 1:n]
        for i in 1:n
            t[i] = (i,hh[i])
        end
        t = sort(t,by=x->x[2])
        for i in k:-1:1
            if t[i][1] == 1
                hh[t[i][1]] = hh[2]
            elseif t[i][1] == n
                hh[t[i][1]] = hh[n-1]
            else
                hh[t[i][1]] = min(hh[t[i][1]-1],hh[t[i][1]+1])
            end
        end
        t = 0
        x = sort(hh)
        for i in 1:n
            c = 0
            f = 0
            q = i==1?x[i]:x[i]-x[i-1]
            for i in 1:n
                if hh[i] == 0 && f == 1
                    f = 0
                elseif hh[i] > 0 && f == 0
                    f = 1
                    c += 1
                end
                hh[i]-=q
            end
            t += c*q
        end

        println(min(s,t))
    end
end
main()


#=
A:
- Julia version:
- Author: abap
- Date: 2019-11-09
=#

parseInt(x) = parse(Int,x)

x = parseInt(readline())
if x % 2 == 0
    println(div(x,2)-1)
else
    println(div(x,2))
end

Score : 100 points

Problem Statement

How many ways are there to choose two distinct positive integers totaling N, disregarding the order?

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

4

Sample Output 1

1

There is only one way to choose two distinct integers totaling 4: to choose 1 and 3. (Choosing 3 and 1 is not considered different from this.)

Sample Input 2

999999

Sample Output 2

499999


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

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

  ans=any(n==i*j for i in 1:9, j in 1:9)
  println(ans ? "Yes" : "No")
end

main()

Score : 200 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.

Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print Yes; if it cannot, print No.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N can be represented as the product of two integers between 1 and 9 (inclusive), print Yes; if it cannot, print No.

Sample Input 1

10

Sample Output 1

Yes

10 can be represented as, for example, 2 \times 5.

Sample Input 2

50

Sample Output 2

No

50 cannot be represented as the product of two integers between 1 and 9.

Sample Input 3

81

Sample Output 3

Yes


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

function main()
	n = readline() |> parseInt
	a = Int[n-1]
	t = 2
	while t<=sqrt(n)
		if n%t==0
			push!(a,div(n,t)+t-2)
		end
		t+=1
	end
	println(minimum(a))
end

main()

Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.


N=parse(readline())
function get_num(N)
  for i in 1:1:sqrt(N)
    if N%i==0
      global a = i
    end
  end
  return a
end

a=get_num(N)
b=N/a

println((a-1)+(b-1))


Score : 400 points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)

We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

1 \leq a \leq 100

1 \leq b \leq 100

1 \leq x \leq a^2b

Input

Input is given from Standard Input in the following format:

a b x

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.


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

function main()
	a,b,x = readline() |> split |> parseMap
	if a*a*b*0.5>=x
		println(atand(a*b*b/(2*x)))
	else
		println(atand((2*(a*a*b-x))/(a^3)))
	end
end

main()


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

function main(a,b,x)
  menseki=x/a
  takasa=(menseki/b)*2
  if takasa>a
    menseki2=a*b-menseki
    takasa2=(menseki2/a)*2
    c=sqrt(takasa2^2+a^2)
    cosA=(c^2+a^2-takasa2^2)/(2*a*c)
    A=acosd(cosA)
    return 90-(90-A)
  else
    c=sqrt(takasa^2+b^2)
    cosA=(c^2+b^2-takasa^2)/(2*b*c)
    A=acosd(cosA)
    return 90-A
  end
end

ans=main(a,b,x)
print(ans)


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

function main(a,b,x)
  menseki=x/a
  takasa=(menseki/b)*b
  c=sqrt(takasa^2+b^2)
  A=(c^2+b^2-takasa^2)/(2*b*c)
  cosA=acosd(A)
  return cosA
end

ans=main(a,b,x)
print(ans)


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    n=parseInt(readline())
    s=chomp(readline())*':'
    cnt=0
    for i in 1:n
        if s[i]!=s[i+1]
            cnt+=1
        end
    end
    println(cnt)
end
main()

Score : 300 points

Problem Statement

There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.

Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.

Ultimately, how many slimes will be there?

Constraints

1 \leq N \leq 10^5

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the final number of slimes.

Sample Input 1

10
aabbbbaaca

Sample Output 1

5

Ultimately, these slimes will fuse into abaca.

Sample Input 2

5
aaaaa

Sample Output 2

1

All the slimes will fuse into one.

Sample Input 3

20
xxzaffeeeeddfkkkkllq

Sample Output 3

10


parseline(str=readline()) = parse.(Int, split(str))
function Triangles()
    N = parse(Int, readline())
    L = sort(parseline())
    ans = Array{Int, 1}[]
    for m in 1:N-2
        for n in m+2:N
            for l in L[m+1:n-1]
                if (L[n] - L[m]) < l < (L[n] + L[m])
                    push!(ans, sort([L[m], l, L[n]]))
                end
            end
        end
    end
    println(length(unique(ans)))
end
Triangles()

Score : 400 points

Problem Statement

Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.

He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:

a < b + c

b < c + a

c < a + b

How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

Constraints

All values in input are integers.

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

1 \leq L_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Constraints

Print the number of different triangles that can be formed.

Sample Input 1

4
3 4 2 1

Sample Output 1

1

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

Sample Input 2

3
1 1000 1

Sample Output 2

0

No triangles can be formed.

Sample Input 3

7
218 786 704 233 645 728 389

Sample Output 3

23


import numpy as np
n = int(input())

l = np.int32(input().split())
l.sort()

c = np.bincount(l,minlength = 2100)

cum = c.cumsum()

ans = 0
for i in range(n):
    for j in range(i+1, n):
        ans += cum[min(l[i]+l[j]-1, 1000)] - (j+1)
print(ans)


function f(D,N)
	for k=1:N,i=1:N,j=1:N
		D[i,j]=min(D[i,j],D[i,k]+D[k,j])
	end
	D
end
const lines=readlines()
function main()
	N,M,L=map(x->parse(Int,x),split(shift!(lines)))
	D=(1-eye(Int,N))*1145141919810
	for i=1:M
		a,b,c=map(x->parse(Int,x),split(shift!(lines)))
		D[a,b]=D[b,a]=c
	end
	D=f(D,N)
	for i=1:N,j=1:N
		if i==j
			D[i,j]=0
		elseif D[i,j]<=L
			D[i,j]=1
		else
			D[i,j]=1145141919810
		end
	end
	D=f(D,N)
	shift!(lines)
	for s=lines
		u,v=map(x->parse(Int,x),split(s))
		ans=D[u,v]
		println(ans<1145141919810 ? ans-1 : -1)
	end
end
main()

Score : 500 points

Problem Statement

There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i.

Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each unit distance traveled. When visiting a town while traveling, he can full the tank (or choose not to do so). Travel that results in the tank becoming empty halfway on the road cannot be done.

Process the following Q queries:

The tank is now full. Find the minimum number of times he needs to full his tank while traveling from Town s_i to Town t_i. If Town t_i is unreachable, print -1.

Constraints

All values in input are integers.

2 \leq N \leq 300

0 \leq M \leq \frac{N(N-1)}{2}

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

\left(A_i, B_i\right) \neq \left(A_j, B_j\right) (if i \neq j)

\left(A_i, B_i\right) \neq \left(B_j, A_j\right) (if i \neq j)

1 \leq C_i \leq 10^9

1 \leq Q \leq N\left(N-1\right)

1 \leq s_i, t_i \leq N

s_i \neq t_i

\left(s_i, t_i\right) \neq \left(s_j, t_j\right) (if i \neq j)

Input

Input is given from Standard Input in the following format:

N M L
A_1 B_1 C_1
:
A_M B_M C_M
Q
s_1 t_1
:
s_Q t_Q

Output

Print Q lines.

The i-th line should contain the minimum number of times the tank needs to be fulled while traveling from Town s_i to Town t_i. If Town t_i is unreachable, the line should contain -1 instead.

Sample Input 1

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

Sample Output 1

0
1

To travel from Town 3 to Town 2, we can use the second road to reach Town 2 without fueling the tank on the way.

To travel from Town 1 to Town 3, we can first use the first road to get to Town 2, full the tank, and use the second road to reach Town 3.

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

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

Sample Output 3

0
0
1
2
0
0
1
2
0
0
0
1
1
1
0
0
2
2
1
0


function main()
	N=parse(Int,readline())
	A=map(x->parse(Int,x),split(readline()))
	cnt=zeros(Int,N)
	sum=zeros(Int,N)
	for a=A
		cnt[a]+=1
		sum[cnt[a]]+=1
	end
	it=N
	acc=N
	for i=1:N
		while acc<it*i
			acc-=sum[it]
			it-=1
		end
		println(it)
	end
end
main()

Score : 600 points

Problem Statement

Takahashi has N cards. The i-th of these cards has an integer A_i written on it.

Takahashi will choose an integer K, and then repeat the following operation some number of times:

Choose exactly K cards such that the integers written on them are all different, and eat those cards. (The eaten cards disappear.)

For each K = 1,2, \ldots, N, find the maximum number of times Takahashi can do the operation.

Constraints

1 \le N \le 3 \times 10^5

1 \le A_i \le N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print N integers.
The t-th (1 \le t \le N) of them should be the answer for the case K=t.

Sample Input 1

3
2 1 2

Sample Output 1

3
1
0

For K = 1, we can do the operation as follows:

Choose the first card to eat.

Choose the second card to eat.

Choose the third card to eat.

For K = 2, we can do the operation as follows:

Choose the first and second cards to eat.

For K = 3, we cannot do the operation at all. Note that we cannot choose the first and third cards at the same time.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

5
2
1
1
1

Sample Input 3

4
1 3 3 3

Sample Output 3

4
1
0
0


Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000


a = parse(Int,readline())
x = (a + a%2)/2
println(x/a)


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

H = parse.(spit(readline()))

count = 0

for i in H
  if i >= K
      count += 1
  end
  end

println(count)

Score : 200 points

Problem Statement

N friends of Takahashi has come to a theme park.

To ride the most popular roller coaster in the park, you must be at least K centimeters tall.

The i-th friend is h_i centimeters tall.

How many of the Takahashi's friends can ride the roller coaster?

Constraints

1 \le N \le 10^5

1 \le K \le 500

1 \le h_i \le 500

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the number of people among the Takahashi's friends who can ride the roller coaster.

Sample Input 1

4 150
150 140 100 200

Sample Output 1

2

Two of them can ride the roller coaster: the first and fourth friends.

Sample Input 2

1 500
499

Sample Output 2

0

Sample Input 3

5 1
100 200 300 400 500

Sample Output 3

5


function main()

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

  ans = ""

  for i in 1:N, j in 1:N

      if A[j] == i
        ans *= string(j)
        ans *= " "
      end

  end

  println(ans)

end

main()

Score : 300 points

Problem Statement

Takahashi is a teacher responsible for a class of N students.

The students are given distinct student numbers from 1 to N.

Today, all the students entered the classroom at different times.

According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including student number i).

From these records, reconstruct the order in which the students entered the classroom.

Constraints

1 \le N \le 10^5

1 \le A_i \le N

A_i \neq A_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print the student numbers of the students in the order the students entered the classroom.

Sample Input 1

3
2 3 1

Sample Output 1

3 1 2

First, student number 3 entered the classroom.

Then, student number 1 entered the classroom.

Finally, student number 2 entered the classroom.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

1 2 3 4 5

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

8 2 4 5 6 7 3 1


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

function main()
	n = readline() |> parseInt
	a = readline() |> split |> parseMap
	b = zeros(Int,n)
	for i in 1:n
		b[a[i]] = i
	end
	for i in 1:n-1
		print(b[i], " ")
	end
	println(b[n])
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()
    a,b=parseMap(split(readline()))
    soinsu1=Set{Int}([1,a])
    soinsu2=Set{Int}([1,b])
    for i in 2:trunc(Int,sqrt(a))+1
        while a%i==0
            a÷=i
            push!(soinsu1,i)
        end
    end
    for i in 2:trunc(Int,sqrt(b))+1
        while b%i==0
            b÷=i
            push!(soinsu2,i)
        end
    end
    ans=0
    for i in soinsu1
        if i in soinsu2
            ans+=1
        end
    end
    println(ans)
end
main()

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


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

function main()
	a,b = readline() |> split |> parseMap
	q = gcd(a,b)
	if q == 1
		println(1)
	else
	a = Int[]
	i = 1
	while i<=sqrt(q)
		if q%i == 0
			push!(a,i)
			push!(a,div(q,i))
		end
		i+=1
	end
	a = sort(a)
	f = ones(Int,length(a))
	for j in 1:length(a)
		for k in j+1:length(a)
			if gcd(a[j],a[k])>1
				f[k] = 0
			end
		end
	end
	println(sum(f))
end
end

main()


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

function main()
  h,w,a,b = readline() |> split |> parseArray

  # if 2a<w || 2b<h
  #   println("No")
  #   return
  # end

  aa=max(2a,1)
  bb=max(2b,1)

  pat=falses((bb,aa))
  pat[1:b,1:a]=true
  pat[b+1:bb,a+1:aa]=true
  println(pat)

  ans=falses((h,w))
  for i=1:h÷bb,j=1:w÷aa
    ans[(i-1)*bb+1:i*bb,1:aa]=pat
    ans[1:bb,(j-1)*aa+1:j*aa]=pat
  end
  if a!=0
    j=w÷aa
    ans[1:bb,j*aa+1:w]=pat[:,w%aa]
  end
  if b!=0
    i=h÷bb
    ans[i*bb+1:h,1:aa]=pat[h%bb,:]
  end

  println(ans)
end

main()

Score : 300 points

Problem Statement

We have a square grid with H rows and W columns.
Snuke wants to write 0 or 1 in each of the squares.
Here, all of the following conditions have to be satisfied:

For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers are equal, “the smaller” should be read as “either”.)

For every column, the smaller of the following is B: the number of 0s contained in the column, and the number of 1s contained in the column.

Determine if these conditions can be satisfied by writing 0 or 1 in each of the squares. If the answer is yes, show one way to fill the squares so that the conditions are satisfied.

Constraints

1 \leq H,W \leq 1000

0 \leq A

2 \times A \leq W

0 \leq B

2 \times B \leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W A B

Output

If the conditions cannot be satisfied by writing 0 or 1 in each of the squares, print -1.

If the conditions can be satisfied, print one way to fill the squares so that the conditions are satisfied, in the following format:

s_{11}s_{12}\cdots s_{1W}
s_{21}s_{22}\cdots s_{2W}
\vdots
s_{H1}s_{H2}\cdots s_{HW}

Here s_{ij} is the digit written in the square at the i-th row from the top and the j-th column from the left in the grid.

If multiple solutions exist, printing any of them will be accepted.

Sample Input 1

3 3 1 1

Sample Output 1

100
010
001

Every row contains two 0s and one 1, so the first condition is satisfied.
Also, every column contains two 0s and one 1, so the second condition is satisfied.

Sample Input 2

1 5 2 0

Sample Output 2

01010


function test()
    w = Dict("Sunny"=>"Cloudy","Cloudy"=>"Rainy","Rainy"=>"Sunny")
    s = readline()
    print(w[s])
end

test()

Score: 100 points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string S representing the weather in the town today. Predict the weather tomorrow.

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny


s=chomp(readline())
println(s=="Sunny" ? "Cloudy" : s=="Cloudy" ? "Rainy" : "Sunny")


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    n,k,q=parseMap(split(readline()))
    points=[k-q for i in 1:n]

    for i in 1:q
        points[parseInt(readline())]+=1
    end
    for i in points
        println(ifelse(i>0,"Yes","No"))
    end
end
main()

Score: 300 points

Problem Statement

Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.

A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.

When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.

At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.

In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 10^9

1 \leq Q \leq 10^5

1 \leq A_i \leq N\ (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N K Q
A_1
A_2
.
.
.
A_Q

Output

Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.

Sample Input 1

6 3 4
3
1
3
2

Sample Output 1

No
No
Yes
No
No
No

In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).

Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).

Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).

Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).

Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).

Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.

Sample Input 2

6 5 4
3
1
3
2

Sample Output 2

Yes
Yes
Yes
Yes
Yes
Yes

Sample Input 3

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

Sample Output 3

No
No
No
No
Yes
No
No
No
Yes
No


Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    n=parseInt(readline())
    a=parseMap(split(readline()))
    b=parseMap(split(readline()))
    c=parseMap(split(readline()))
    ans=0
    for i in 1:n
        ans+=b[a[i]]
        if i>1 && a[i]==a[i-1]+1
            ans+=c[a[i-1]]
        end
    end
    println(ans)
end
main()

Score : 200 points

Problem Statement

Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.

The i-th dish (1 \leq i \leq N) he ate was Dish A_i.

When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.

Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.

Find the sum of the satisfaction points he gained.

Constraints

All values in input are integers.

2 \leq N \leq 20

1 \leq A_i \leq N

A_1, A_2, ..., A_N are all different.

1 \leq B_i \leq 50

1 \leq C_i \leq 50

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}

Output

Print the sum of the satisfaction points Takahashi gained, as an integer.

Sample Input 1

3
3 1 2
2 5 4
3 6

Sample Output 1

14

Takahashi gained 14 satisfaction points in total, as follows:

First, he ate Dish 3 and gained 4 satisfaction points.

Next, he ate Dish 1 and gained 2 satisfaction points.

Lastly, he ate Dish 2 and gained 5 + 3 = 8 satisfaction points.

Sample Input 2

4
2 3 4 1
13 5 8 24
45 9 15

Sample Output 2

74

Sample Input 3

2
1 2
50 50
50

Sample Output 3

150


N=parse(Int,readline())
A=map(x->parse(Int,x),split(readline()))
B=map(x->parse(Int,x),split(readline()))
C=map(x->parse(Int,x),split(readline()))
p=-1
ans=0
for a=A
	ans+=B[a]
	if p+1==a
		ans+=C[p]
	end
	p=a
end
println(ans)


N=parse(readline())
A=parse.(split(readline()))
B=parse.(split(readline()))
C=parse.(split(readline()))
res=0
res+=sum(B)
for i in 1:N-1
  if A[i]==A[i+1]-1
    res+=C[A[i]]
    end
  end
println(res)


N=parse(readline())
B=parse.(split(readline()))
A=[]
for i in 1:N-2
  push!(A,min(B[i],B[i+1]))
end
push!(A,B[N-1])
println(sum(A))

Score : 300 points

Problem Statement

There is an integer sequence A of length N whose values are unknown.

Given is an integer sequence B of length N-1 which is known to satisfy the following:

B_i \geq \max(A_i, A_{i+1})

Find the maximum possible sum of the elements of A.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq B_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
B_1 B_2 ... B_{N-1}

Output

Print the maximum possible sum of the elements of A.

Sample Input 1

3
2 5

Sample Output 1

9

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53


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

function main()
	n,k = readline() |> split |> parseMap
	s = readline() |> chomp
	v = 0
	if s[1]==s[2]=='R'
		v += 1
	end
	if s[n-1]==s[n]=='L'
		v += 1
	end
	for i in 2:n-1
		if s[i-1]==s[i]=='L' || s[i]==s[i+1]=='R'
			v += 1
		end
	end
	println(min(n-1,v+2k))
end

main()

Score : 400 points

Problem Statement

There are N people standing in a queue from west to east.

Given is a string S of length N representing the directions of the people.
The i-th person from the west is facing west if the i-th character of S is L, and east if that character of S is R.

A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.

You can perform the following operation any number of times between 0 and K (inclusive):

Operation: Choose integers l and r such that 1 \leq l \leq r \leq N, and rotate by 180 degrees the part of the queue: the l-th, (l+1)-th, ..., r-th persons. That is, for each i = 0, 1, ..., r-l, the (l + i)-th person from the west will stand the (r - i)-th from the west after the operation, facing east if he/she is facing west now, and vice versa.

What is the maximum possible number of happy people you can have?

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

|S| = N

Each character of S is L or R.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of happy people after at most K operations.

Sample Input 1

6 1
LRLRRL

Sample Output 1

3

If we choose (l, r) = (2, 5), we have LLLRLL, where the 2-nd, 3-rd, and 6-th persons from the west are happy.

Sample Input 2

13 3
LRRLRLRRLRLLR

Sample Output 2

9

Sample Input 3

10 1
LLLLLRRRRR

Sample Output 3

9

Sample Input 4

9 2
RRRLRLRLL

Sample Output 4

7


isnothing(x) = x == nothing

typealias Maybe{T} Union{T, Void}

type Node
  value::Int
  count::Int
  left::Maybe{Node}
  right::Maybe{Node}

  Node(v::Int) = new(v, 1, nothing, nothing)
end

# binary search tree
type Tree
  root::Maybe{Node}
  first::Maybe{Node}
  last::Maybe{Node}

  Tree() = new(nothing, nothing, nothing)
end

Tree(itr) = union!(Tree(), itr)

# implement interfaces
# see https://docs.julialang.org/en/v0.5/manual/interfaces/

# iteration interface
Base.start(::Tree) = 1
Base.next(tree::Tree, state) = (tree[state], state + 1)
Base.done(tree::Tree, state) = state > endof(tree)
Base.iteratorsize(::Type{Tree}) = Base.HasLength()
Base.length(tree::Tree) = !isnothing(tree.root) ? tree.root.count : 0
Base.iteratoreltype(::Type{Tree}) = Base.HasEltype()
Base.eltype(::Type{Tree}) = Int

# indexing interface
# O(log(N))
function Base.getindex(tree::Tree, i::Int)::Int
  (i <= 0 || i > endof(tree)) && throw(BoundsError(tree, i))

  i == 1 && return first(tree)
  i == endof(tree) && return last(tree)

  node = tree.root
  while (l = !isnothing(node.left) ? node.left.count : 0; i != l + 1)
    # l = !isnothing(node.left) ? node.left.count : 0
    if i > l
      i -= l + 1
      node = node.right
    else
      node = node.left
    end
  end

  node.value
end

Base.endof(tree::Tree) = length(tree)

# efficient operations for iterable
Base.in(val::Int, tree::Tree) = find(val, tree) != 0

# stack operations
function Base.push!(tree::Tree, val::Int)::Tree
  isnothing(tree.root) && (tree.root = tree.first = tree.last = Node(val))

  node = tree.root
  nodes = [node]
  while true
    if node.value > val && !isnothing(node.left)
      node = node.left
    elseif node.value < val && !isnothing(node.right)
      node = node.right
    else
      break
    end
    push!(nodes, node)
  end

  newnode = Node(val)
  if node.value > val
    node.left = newnode
    foreach(node -> node.count += 1, nodes)
    val < tree.first.value && (tree.first = newnode)
  elseif node.value < val
    node.right = newnode
    foreach(node -> node.count += 1, nodes)
    val > tree.last.value && (tree.last = newnode)
  end

  tree
end

function Base.push!(tree::Tree, vals...)::Tree
  foreach(val -> push!(tree, val), vals)
  tree
end

function Base.pop!(tree::Tree)::Int
  val = last(tree)
  delete!(tree, val)
  val
end

function Base.shift!(tree::Tree)::Int
  val = first(tree)
  delete!(tree, val)
  val
end

Base.find(val::Int, tree::Tree)::Int = first(_find(val, tree))

Base.isempty(tree::Tree) = length(tree) == 0
Base.empty!(tree::Tree) = (tree.root = tree.first = tree.last = nothing)
Base.minimum(tree::Tree) = first(tree)
Base.maximum(tree::Tree) = last(tree)
Base.extrema(tree::Tree) = (minimum(tree), maximum(tree))
Base.first(t::Tree) = t.first.value
Base.last(t::Tree) = t.last.value

function Base.union!(tree::Tree, itr)::Tree
  foreach(val -> push!(tree, val), itr)
  tree
end

# O(Nlog(N))
function shake!(tree::Tree)::Tree
  sorted = collect(tree)
  empty!(tree)

  f(a::Vector{Int}) = begin
    isempty(a) && return

    i = length(a) ÷ 2 + 1
    push!(tree, a[i])
    f(a[1:i - 1])
    f(a[i + 1:end])
  end
  f(sorted)

  tree
end

function _find(val::Int, tree::Tree)::Tuple{Int, Maybe{Node}}
  isnothing(tree.root) && return (0, nothing)

  node = tree.root
  i = 0
  while true
    if node.value > val && !isnothing(node.left)
      node = node.left
    elseif node.value < val && !isnothing(node.right)
      i += node.count - node.right.count
      node = node.right
    else
      break
    end
  end
  i += node.count - (!isnothing(node.right) ? node.right.count : 0)

  node.value == val ? (i, node) : (0, nothing)
end

# end of bst.jl

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

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

  ix=zeros(Int,n)
  ix[px]=1:n
  tree=Tree()

  ans=0
  for p in n:-1:1
    i=ix[p]
    push!(tree,i)
    log2(length(tree))%1==0 && shake!(tree)
    j = find(i, tree)

    y,z=map(k -> j+k<=endof(tree) ? tree[j+k] : n+1, 1:2)
    x,w=map(k -> j-k>=1 ? tree[j-k] : 0, 1:2)
    ans+=p*((x-w)*(y-i)+(i-x)*(z-y))
  end

  println(ans)
end

main()

Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

2 \le N \le 10^5

1 \le P_i \le N

P_i \neq P_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136


a,b=readlines()
c=0
for i=1:3
  a[i]==b[i]?c+=1:
end
print(c)

Score : 100 points

Problem Statement

You will be given a string S of length 3 representing the weather forecast for three days in the past.

The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

You will also be given a string T of length 3 representing the actual weather on those three days.

The i-th character (1 \leq i \leq 3) of S represents the actual weather on the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

Print the number of days for which the forecast was correct.

Constraints

S and T are strings of length 3 each.

S and T consist of S, C, and R.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the number of days for which the forecast was correct.

Sample Input 1

CSS
CSR

Sample Output 1

2

For the first day, it was forecast to be cloudy, and it was indeed cloudy.

For the second day, it was forecast to be sunny, and it was indeed sunny.

For the third day, it was forecast to be sunny, but it was rainy.

Thus, the forecast was correct for two days in this case.

Sample Input 2

SSR
SSR

Sample Output 2

3

Sample Input 3

RRR
SSS

Sample Output 3

0


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    s=chomp(readline())
    t=chomp(readline())
    println(sum([s[i]==t[i] for i in 1:3]))
end
main()


A, B = parse.(split(readline()))
up = A - 1
want = B - 1
println(Int(cld(want, up)))


S = strip(readline())
T = strip(readline())
println(sum(map(x -> x[1] == x[2], zip(S, T))))


const PAIR = Pair{Int,Int}

#################### library ####################

#################### graph ####################

const Graph = Dict{Int,Vector{Int}}
const GraphPAIR = Dict{PAIR,Vector{PAIR}}

# graph: { node: [node] }
function is_cyclic(graph::GraphPAIR)
	for pair in graph
		x0 = pair.first
		v = [x0]	# stack
		s::Set{Pair} = Set{Pair}()
		while !isempty(v)
			x = pop!(v)
			for y in graph[x]
				if !in(y, s)
					push!(s, y)
					push!(v, y)
				end
			end
		end

		if in(x0, s)
			return true
		end
	end

	return false
end

#################### naive ####################

#################### process ####################

function read_input()
	N = parse(Int, readline())
	table = [ [ parse(Int, s) for s in split(readline()) ] for _ in 1:N ]
	return table
end

function make_graph(table)::GraphPAIR
	function f(v)
		dic::Dict{Int,Int} = Dict()
		k = 0
		for e in v
			dic[e] = k
		end
		return dic
	end

	N = length(table)
	dics = [ f(v) for v in table ]
	graph::GraphPAIR = Dict()
	for i in 1:N-1
		for j in i+1:N
			graph[PAIR(i,j)] = []
		end
	end
	for pair in graph
		k = pair.first.first
		l = pair.first.second
		i1 = dics[k][l]
		if i1 < N-1
			j1 = table[k][i1+1]
			push!(graph[Pair(k, l)], minimum([Pair(k, j1), Pair(j1, k)]))
		end
		i2 = dics[l][k]
		if i2 < N-1
			j2 = table[l][i2+1]
			push!(graph[Pair(k, l)], minimum([Pair(l, j2), Pair(j2, l)]))
		end
	end
	return graph
end

function f()
	table = read_input()
	N = length(table)
	memo::Dict{PAIR,Int} = Dict()
	graph::GraphPAIR = make_graph(table)
	if is_cyclic(graph)
		return -1
	end

	unvisited = Set(Pair(n, m) for n in 1:N-1 for m in n+1:N)
	for pair in graph
		if length(pair.second) == 0
			memo[pair.first] = 1
			pop!(unvisited, pair.first)
		end
	end

	for i in 1:N-1
		for j in i+1:N
			v = Pair(i, j)
			if !in(v, unvisited)
				continue
			end
			stack = [v]
			while !isempty(stack)
				v = pop!(stack)
				unvs = [ v1 for v1 in graph[v] if in(v1, unvisited) ]
				if isempty(unvs)
					dist = maximum([memo[v1]+1 for v1 in graph[v]])
					memo[v] = dist
					pop!(unvisited, v)
				else
					push!(stack, v)
					for v1 in unvs
						push!(stack, v1)
					end
				end
			end
		end
	end

	return maximum(pair.second for pair in memo)
end

#################### main ####################

println(f())


a=readline()
t=readline()
a=a[1:length(a)-1]
t=t[1:length(t)-1]
count=0
for (i,t) in zip(a,t)
  if i==t
    count+=1
  end
end
println(count)


s=readline()
t=readline()
count=0
for (i,j) in zip(s,t)
  if i==j
    count+=1
  end
end
print(count)


A, B = parse.(split(readline()))
up = A - 1
want = B - 1
println(Int(div(want, up)))

Score : 200 points

Problem Statement

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.

One power strip with A sockets can extend one empty socket into A empty sockets.

Find the minimum number of power strips required.

Constraints

All values in input are integers.

2 \leq A \leq 20

1 \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of power strips required.

Sample Input 1

4 10

Sample Output 1

3

3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.

Sample Input 2

8 9

Sample Output 2

2

2 power strips, each with 8 sockets, extend the socket into 15 empty sockets.

Sample Input 3

8 8

Sample Output 3

1


A, B = parse.(split(readline())
up = A - 1
want = B - 1
println(Int(div(want, up)))


parseInt(x) = parse(Int,x)

function main()
  A,B = map(parseInt,split(readline()))
  c = div(B,A)
  A*c >= B ? d = c : d = c+1
  println(d)
end

main()


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

function main()
	n = readline() |> parseInt
	a = [Array{Int}(n-1) for i in 1:n]
	for i in 1:n
		a[i] = readline() |> split |> parseMap
	end
	f = 0
	k = 0
	l = n-1*ones(Int,n)
	while sum(l)>0
		t = 0
		c = Int[]
		for i in 2:n
			if !isempty(a[i])
				for j in 1:i-1
					if !isempty(a[j])
						if a[i][1]==j && a[j][1]==i
							t += 1
							l[i] -= 1
							l[j] -= 1
							push!(c,i)
							push!(c,j)
						end
					end
				end
			end
		end
		if t>0
			k += 1
			for i in 1:length(c)
				shift!(a[c[i]])
			end
		else
			f = 1
			break
		end
	end
	println(f==0?k:-1)
end

main()

Score : 500 points

Problem Statement

N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.

The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

Constraints

3 \leq N \leq 1000

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

A_{i, j} \neq i

A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

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

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day 1: Player 1 vs Player 2, Player 3 vs Player 4

Day 2: Player 1 vs Player 3

Day 3: Player 1 vs Player 4, Player 2 vs Player 3

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.


M,D=map(x->parse(Int,x),split(readline()))
ans=0
for i=22:D
  ans+=i%10>1&&div(i,10)*(i%10)<=M
end
println(ans)

Score : 200 points

Problem Statement

Today is August 24, one of the five Product Days in a year.

A date m-d (m is the month, d is the date) is called a Product Day when d is a two-digit number, and all of the following conditions are satisfied (here d_{10} is the tens digit of the day and d_1 is the ones digit of the day):

d_1 \geq 2

d_{10} \geq 2

d_1 \times d_{10} = m

Takahashi wants more Product Days, and he made a new calendar called Takahashi Calendar where a year consists of M month from Month 1 to Month M, and each month consists of D days from Day 1 to Day D.

In Takahashi Calendar, how many Product Days does a year have?

Constraints

All values in input are integers.

1 \leq M \leq 100

1 \leq D \leq 99

Input

Input is given from Standard Input in the following format:

M D

Output

Print the number of Product Days in a year in Takahashi Calender.

Sample Input 1

15 40

Sample Output 1

10

There are 10 Product Days in a year, as follows (m-d denotes Month m, Day d):

4-22

6-23

6-32

8-24

9-33

10-25

12-26

12-34

14-27

15-35

Sample Input 2

12 31

Sample Output 2

5

Sample Input 3

1 1

Sample Output 3

0


const MOD = 1000000007

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

    p = 0
    for i in 1:length(a)-1
        @views p += count(x->x<a[i], a[i+1:end])
    end

    q = 0
    for i in 1:length(a)
        q += count(x->x<a[i], a)
    end

    @show p
    @show q

    ans = mod(p*k, MOD)
    ans += mod(q*mod(k*(k-1), MOD)/2, MOD)
    ans = mod(ans, MOD)

    println(Int(ans))
end

main()

Score : 300 points

Problem Statement

We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}.

Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.

Find the inversion number of B, modulo 10^9 + 7.

Here the inversion number of B is defined as the number of ordered pairs of integers (i,~j)~(0 \leq i < j \leq K \times N - 1) such that B_i > B_j.

Constraints

All values in input are integers.

1 \leq N \leq 2000

1 \leq K \leq 10^9

1 \leq A_i \leq 2000

Input

Input is given from Standard Input in the following format:

N K
A_0 A_1 ... A_{N - 1}

Output

Print the inversion number of B, modulo 10^9 + 7.

Sample Input 1

2 2
2 1

Sample Output 1

3

In this case, B~=~2,~1,~2,~1. We have:

B_0 > B_1

B_0 > B_3

B_2 > B_3

Thus, the inversion number of B is 3.

Sample Input 2

3 5
1 1 1

Sample Output 2

0

A may contain multiple occurrences of the same number.

Sample Input 3

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

Sample Output 3

185297239

Be sure to print the output modulo 10^9 + 7.


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

function main()
    n,k=parseMap(split(readline()))
    a=parseMap(split(readline()))
    mod=10^9+7
    cnt1=[0 for i in 1:n]
    cnt2=[0 for i in 1:n]
    for i in 1:n
        for j in 1:n
            if a[i]>a[j]
                if i<j
                    cnt1[i]+=1
                else
                    cnt2[i]+=1
                end
            end
        end
    end
    ans=0
    num1=(k+1)k÷2
    num2=(k-1)k÷2
    for i in 1:n
        ans=(ans+num1*cnt1[i]+num2*cnt2[i])%mod
    end
    println(ans%mod)
end
main()


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

function main()
	mod = 10^9+7
	n,k = readline() |> split |> parseMap
	a = readline() |> split |> parseMap
	x = zeros(Int,n)
	y = zeros(Int,n)
	for i in 1:n
		for j in 1:n
			if j<i
				if a[i]>a[j]
					x[i]+=1
				end
			elseif i<j
				if a[i]>a[j]
					y[i]+=1
				end
			end
		end
	end
	z = 0
	for i in 1:n
		z = (z+(k*y[i])%mod+div(k*(k-1),2)%mod*(x[i]+y[i])%mod)%mod
	end
	println(z)
end

main()


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

function main()
	n = readline() |> parseInt
	r = 0
	while 2^r<n
		r += 1
	end
	for i in 1:n-1
		for j in i+1:n-1
			x = i$j
			for k in 0:r
				if (x>>k)%2==1
					print(k+1," ")
					break
				end
			end
		end
		x = i$n
		for k in 0:r
			if (x>>k)%2==1
				println(k+1)
				break
			end
		end
	end
end
main()

Score: 600 points

Problem Statement

AtCoder's head office consists of N rooms numbered 1 to N. For any two rooms, there is a direct passage connecting these rooms.

For security reasons, Takahashi the president asked you to set a level for every passage, which is a positive integer and must satisfy the following condition:

For each room i\ (1 \leq i \leq N), if we leave Room i, pass through some passages whose levels are all equal and get back to Room i, the number of times we pass through a passage is always even.

Your task is to set levels to the passages so that the highest level of a passage is minimized.

Constraints

N is an integer between 2 and 500 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print one way to set levels to the passages so that the objective is achieved, as follows:

a_{1,2} a_{1,3} ... a_{1,N}
a_{2,3} ... a_{2,N}
.
.
.
a_{N-1,N}

Here a_{i,j} is the level of the passage connecting Room i and Room j.

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

Sample Input 1

3

Sample Output 1

1 2
1

The following image describes this output:

For example, if we leave Room 2, traverse the path 2 \to 3 \to 2 \to 3 \to 2 \to 1 \to 2 while only passing passages of level 1 and get back to Room 2, we pass through a passage six times.


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

function main()
	n = readline() |> parseInt
	k = 0
	if n==3
		println("1 2")
		println("1")
	else
		a = zeros(Int,n-1,n)
		for i in 1:n-1
			for j in i+1:n
				if abs(i-j)%2==0
					a[i,j] = 2
				else
					a[i,j] = 1
				end
			end
		end
	end
	for i in 1:n-1
		for j in i+1:n-1
			print(a[i,j], " ")
		end
		println(a[i,n])
	end
end

main()


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

function main()
	n = readline() |> parseInt
	a = readline() |> split |> parseMap
	k = 0.0
	for i in 1:n
		k += 1/a[i]
	end
	println(1/k)
end

main()

Score : 200 points

Problem Statement

Given is a sequence of N integers A_1, \ldots, A_N.

Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Constraints

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print a decimal number (or an integer) representing the value of \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
10 30

Sample Output 1

7.5

\frac{1}{\frac{1}{10} + \frac{1}{30}} = \frac{1}{\frac{4}{30}} = \frac{30}{4} = 7.5.

Printing 7.50001, 7.49999, and so on will also be accepted.

Sample Input 2

3
200 200 200

Sample Output 2

66.66666666666667

\frac{1}{\frac{1}{200} + \frac{1}{200} + \frac{1}{200}} = \frac{1}{\frac{3}{200}} = \frac{200}{3} = 66.6666....

Printing 6.66666e+1 and so on will also be accepted.

Sample Input 3

1
1000

Sample Output 3

1000

\frac{1}{\frac{1}{1000}} = 1000.

Printing +1000.0 and so on will also be accepted.


readline()
v = parse.(split(readline(), " "))

sorted = sort(v)
ans = foldl((x,y)->(x+y)/2, sorted)
println(ans)

Score : 300 points

Problem Statement

You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i.

When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where x and y are the values of the ingredients consumed, and you can put this ingredient again in the pot.

After you compose ingredients in this way N-1 times, you will end up with one ingredient. Find the maximum possible value of this ingredient.

Constraints

2 \leq N \leq 50

1 \leq v_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
v_1 v_2 \ldots v_N

Output

Print a decimal number (or an integer) representing the maximum possible value of the last ingredient remaining.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
3 4

Sample Output 1

3.5

If you start with two ingredients, the only choice is to put both of them in the pot. The value of the ingredient resulting from the ingredients of values 3 and 4 is (3 + 4) / 2 = 3.5.

Printing 3.50001, 3.49999, and so on will also be accepted.

Sample Input 2

3
500 300 200

Sample Output 2

375

You start with three ingredients this time, and you can choose what to use in the first composition. There are three possible choices:

Use the ingredients of values 500 and 300 to produce an ingredient of value (500 + 300) / 2 = 400. The next composition will use this ingredient and the ingredient of value 200, resulting in an ingredient of value (400 + 200) / 2 = 300.

Use the ingredients of values 500 and 200 to produce an ingredient of value (500 + 200) / 2 = 350. The next composition will use this ingredient and the ingredient of value 300, resulting in an ingredient of value (350 + 300) / 2 = 325.

Use the ingredients of values 300 and 200 to produce an ingredient of value (300 + 200) / 2 = 250. The next composition will use this ingredient and the ingredient of value 500, resulting in an ingredient of value (250 + 500) / 2 = 375.

Thus, the maximum possible value of the last ingredient remaining is 375.

Printing 375.0 and so on will also be accepted.

Sample Input 3

5
138 138 138 138 138

Sample Output 3

138


N=parse(readline())
KACHI=parse.(split(readline()))
KACHI=sort!(KACHI)
other=min(KACHI...)
global min_count=0
global new_g=0
for i in KACHI
    if i==other
       global base_g=i
       min_count+=1
    else
       global new_g=(base_g+i)/2
       base_g=new_g
    end
end
    if min_count==N
        println(other)
    else
        println(new_g)
    end


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

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

  ss = s * s
  i_ch = [Int[] for _ in 1:23]
  for i in 1:length(ss)
    append!(i_ch[Int(ss[i]) - 97], i)
  end

  ans = 0
  for i in 1:length(t)
    ix = i_ch[Int(t[i]) - 97]
    if isempty(ix)
      ans = -1
      break
    end

    j = ans % length(s)
    ans += (ix[ix .> j] |> first) - j
  end

  println(ans)
end

main()

Score : 500 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.

Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').

Notes

A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net, c, and contest.

Constraints

1 \leq |s| \leq 10^5

1 \leq |t| \leq 10^5

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print -1.

Sample Input 1

contest
son

Sample Output 1

10

t = son is a subsequence of the string contestcon (the first 10 characters in s' = contestcontestcontest...), so i = 10 satisfies the condition.

On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s'), so i = 9 does not satisfy the condition.

Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition is 10.

Sample Input 2

contest
programming

Sample Output 2

-1

t = programming is not a substring of s' = contestcontestcontest.... Thus, there is no integer i satisfying the condition.

Sample Input 3

contest
sentence

Sample Output 3

33

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


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

function main()
	ss = readline() |> chomp
	tt = readline() |> chomp
	s = Int[Int(ss[i])-96 for i in 1:length(ss)]
	t = Int[Int(tt[i])-96 for i in 1:length(tt)]
	n = length(s)
	d = Dict{Int,Array{Int,1}}()
	dp = -ones(Int,n+1,26)
	for i in 1:n
		if haskey(d,s[i])
			push!(d[s[i]],i)
		else
			d[s[i]] = Int[i]
		end
	end
	for i in 1:n
		push!(d[s[i]],n+i)
	end
	for i in 1:n
		for j in keys(d)
			dp[i,j]=d[j][bsearch(d[j],i)]
		end
	end
	k = 0
	now = 0
	for i in 1:length(t)
		if dp[now+1,t[i]]<0
			k = -1
			break
		else
			now = dp[now+1,t[i]]
			if now>=n
				k += n
				now = now%n
			end
		end
	end
	println(k+now)
end

main()


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

function main()
	s = readline() |> chomp
	t = readline() |> chomp
	l = length(s)
	alf = Array{Int}(26,l)
	d = Dict{Char,Array{Int,1}}()
	for i in 1:l
		if haskey(d,s[i])
			push!(d[s[i]],i)
		else
			d[s[i]] = [i]
		end
	end
	for i in 1:26
		if haskey(d,Char(i+96))
			now = 1
			for j in 1:length(d[Char(i+96)])
				while now<d[Char(i+96)][j]
					alf[i,now] = d[Char(i+96)][j]
					now += 1
				end
			end
			while now <= l
				alf[i,now] = d[Char(i+96)][1]
				now += 1
			end
		end
	end
	k = 0
	f = 0
	z = length(t)
	now = l
	for i in 1:z
		if alf[Int(t[i])-96,now] == 0
			f = 1
			break
		elseif alf[Int(t[i])-96,now]<=now
			k += l-now+alf[Int(t[i])-96,now]
			now = alf[Int(t[i])-96,now]
		else
			k += alf[Int(t[i])-96,now]-now
			now = alf[Int(t[i])-96,now]
		end
	end
	println(f==1?-1:k)

end

main()