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

function main()
	n = readline() |> parseInt
	b = readline() |> split |> parseMap
	flg = 0
	ans = Int[]
	for i in 1:n
		if b[i] > i
			flg = 1
			break
		end
	end
	for i in 1:n
		t = length(b)
		for j in 0:t-1
			if b[t-j] == t-j
				t = t-j
				break
			end
		end
		if t == 0
			flg = 1
			break
		else
			push!(ans,t)
			deleteat!(b,t)
		end
	end
	if flg == 1
		println(-1)
	else
		for i in 0:n-1
			println(ans[n-i])
		end
	end
end
main()

Score : 400 points

Problem Statement

Snuke has an empty sequence a.

He will perform N operations on this sequence.

In the i-th operation, he chooses an integer j satisfying 1 \leq j \leq i, and insert j at position j in a (the beginning is position 1).

You are given a sequence b of length N. Determine if it is possible that a is equal to b after N operations. If it is, show one possible sequence of operations that achieves it.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq b_i \leq N

Input

Input is given from Standard Input in the following format:

N
b_1 \dots b_N

Output

If there is no sequence of N operations after which a would be equal to b, print -1.
If there is, print N lines. In the i-th line, the integer chosen in the i-th operation should be printed. If there are multiple solutions, any of them is accepted.

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

In this sequence of operations, the sequence a changes as follows:

After the first operation: (1)

After the second operation: (1,1)

After the third operation: (1,2,1)

Sample Input 2

2
2 2

Sample Output 2

-1

2 cannot be inserted at the beginning of the sequence, so this is impossible.

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1


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

function main()
	n = readline() |> parseInt
	t = div(n*(n+1),2)
	if n%2 == 1
		println(div((n-1)*(n-1),2))
		s = t-n
		for i in 1:n
			for j in i+1:n
				if t-i-j != s
					println(i, " ", j)
				end
			end
		end
	else
		println(div((n-1)*(n-1)-1,2))
		s = t-n-1
		for i in 1:n
			for j in i+1:n
				if t-i-j != s
					println(i, " ", j)
				end
			end
		end
	end
end
main()

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

Score : 700 points

Problem Statement

You are given an integer N.
Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:

The graph is simple and connected.

There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.

It can be proved that at least one such graph exists under the constraints of this problem.

Constraints

All values in input are integers.

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.

The output will be judged correct if the graph satisfies the conditions.

Sample Input 1

3

Sample Output 1

2
1 3
2 3

For every vertex, the sum of the indices of the vertices adjacent to that vertex is 3.

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.


N=parse(Int,readline())
cnt=zeros(Int,26)
for c=chomp(readline())
	cnt[Int(c)-96]+=1
end
ans=1
for i=1:26
	ans=ans*(cnt[i]+1)%(10^9+7)
end
println(ans-1)

Score : 200 points

Problem Statement

You are given a string S of length N.
Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of the subsequences such that all characters are different, modulo 10^9+7.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in S itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17


H,W = parse.(split(readline()))
h,w = parse.(split(readline()))
println((H - h + W - w))

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


function main()

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

  println((H-h)*(W-w))

end

main()


const lines=readlines(open("/dev/fd/0"))
input()=shift!(lines)
int(s::String)=parse(Int32,s)
intSub(s::SubString{String})=parse(Int32,s)
intLine()=map(intSub,split(input()))
function main()
    H,W=intLine()
    h,w=intLine()
    println((H-h)*(W-w))
end
main()


parseInt(x) = parse(Int,x)
function main()
	H,W = map(parseInt, split(readline()))
  	h,w = map(parseInt, split(readline()))
  println(Int64(H*W - h*W - H*w + h*w))
end
main()


parseInt(x) = parse(Int, x)
n,m,c = readline() |> split .|> parseInt
b = readline() |> split .|> parseInt |> Vector
A = fill(0,n,m)
for i = 1:n
    A[i,:] .= readline() |> split .|> parseInt
end
ans = A*b .+ c
ret = 0
for i in ans
    if i > 0
    	global ret += 1
    end
end
println(ret)

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


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


parseInt(x) = parse(Int,x)

function main()
	N,M,C = map(parseInt, split(readline()))
  	b = map(parseInt, split(readline()))
  ans = 0
  	for i = 1:N
  		a = map(parseInt, split(readline()))
    	if sum(a.*b) + C > 0
      		ans += 1
    end
  end
  println(Int64(ans))
end
main()


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

function main()
	n,m,c = readline() |> split |> parseMap
	b = readline() |> split |> parseMap
	k = 0
	for i in 1:n
		a = readline() |> split |> parseMap
		t = c
		for j in 1:m
			t += a[j]*b[j]
		end
		if t > 0
			k += 1
		end
	end
	println(k)
end
main()


inpl() = map(parse,split(readline()))
(N,M) = inpl()
A = Array{Int}(N)
B = Array{Int}(N)
for i = 1:N
  (A[i],B[i]) = inpl()
end
order = sortperm(A)
ans = 0
for i = 1:N
  if B[order[i]] >= M
    ans += M*A[order[i]]
    break
  else
    M -= B[order[i]]
    ans += B[order[i]]*A[order[i]]
  end
end
println(ans)

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

The output may not fit into a 32-bit integer type.


function mkdivisor(n::Int)
  divisors=Int[]
  for i=1:div(n^0.5,1)
    if n%i==0
      push!(divisors,i)
      if i!= fld(n,i); push!(divisors,fld(n,i));end
    end
  end
  sort!(divisors)
  return divisors
end

macro p(z);:((x->parse(Int,x)).(split($z)));end
a,b,k=@p(readline())
print([i for i=mkdivisor(a) if i in mkdivisor(b)][end-k+1])

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


function main()
  global s = readline()
  so = s[:]
  while length(s) >1 && s != "1"^length(s) && s != "0"^length(s)
    i = length(s)
    while i >1
      if i == 2
        if s[1:2] == "00" || s[1:2] =="11"

        elseif length(s) >=3
          global  s = s[3:end]
        else
         global s = ""
        end
      elseif i != length(s)
        if (parse(Int, s[i]) $ parse(Int, s[i-1])) == 1
           s = s[1:i-2] * s[i+1:end]
          i -=1
        end
      else
        if (parse(Int, s[i]) $ parse(Int, s[i-1])) == 1
          global s = s[1:i-2]
          i -=1
        end
      end
      i -=1
    end
  end
  println(Int64(length(so) - length(s)))
end
main()

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.

You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

All four cubes can be removed, by performing the operation as follows:

Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    s=parseMap(split(readline(),'/'))
    if s[1]<2019 || (s[2]<=4 && s[3]<=30)
        println("Heisei")
    else
        println("TBD")
    end
end
main()

Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


parseInt(x) = parse(Int,x)
function main()
  s = readline()
  y,m,d = map(parseInt,split(a))
  if y<2019
    println("heisei")
  elseif y>2019
    println("TBD")
  elseif m<=4
    println("heisei")
  else
    println("TBD")
  end
end
main()


macro p(z);:((x->parse(Int,x)).(split($z)));end
f(s) = s == "BTC" ? 380000 : 1
function main()
  sum_money=0
  for i=1:parse(Int,readline())
    a,b=split(readline())
    sum_money+=parse(Float64,a)*f(b)
  end
  print(sum_money)
end
main()

Score : 200 points

Problem Statement

Takahashi received otoshidama (New Year's money gifts) from N of his relatives.

You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either JPY or BTC, and x_i and u_i represent the content of the otoshidama from the i-th relative.

For example, if x_1 = 10000 and u_1 = JPY, the otoshidama from the first relative is 10000 Japanese yen; if x_2 = 0.10000000 and u_2 = BTC, the otoshidama from the second relative is 0.1 bitcoins.

If we convert the bitcoins into yen at the rate of 380000.0 JPY per 1.0 BTC, how much are the gifts worth in total?

Constraints

2 \leq N \leq 10

u_i = JPY or BTC.

If u_i = JPY, x_i is an integer such that 1 \leq x_i \leq 10^8.

If u_i = BTC, x_i is a decimal with 8 decimal digits, such that 0.00000001 \leq x_i \leq 100.00000000.

Input

Input is given from Standard Input in the following format:

N
x_1 u_1
x_2 u_2
:
x_N u_N

Output

If the gifts are worth Y yen in total, print the value Y (not necessarily an integer).

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

Sample Input 1

2
10000 JPY
0.10000000 BTC

Sample Output 1

48000.0

The otoshidama from the first relative is 10000 yen. The otoshidama from the second relative is 0.1 bitcoins, which is worth 38000.0 yen if converted at the rate of 380000.0 JPY per 1.0 BTC. The sum of these is 48000.0 yen.

Outputs such as 48000 and 48000.1 will also be judged correct.

Sample Input 2

3
100000000 JPY
100.00000000 BTC
0.00000001 BTC

Sample Output 2

138000000.0038

In this case, outputs such as 138001000 and 1.38e8 will also be judged correct.


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

n,a,b,c=parseMap(split(readline()))
l=[parseInt(readline()) for i in 1:n]
ans=10^9

function dfs(cnt,one,two,three,mp)
    global ans
    if cnt==n+1
        if 0 in [one,two,three]
            return 0
        end
        ans=min(ans,mp+abs(one-a)+abs(two-b)+abs(three-c)-30)
    else
        dfs(cnt+1,one+l[cnt],two,three,mp+10)
        dfs(cnt+1,one,two+l[cnt],three,mp+10)
        dfs(cnt+1,one,two,three+l[cnt],mp+10)
        dfs(cnt+1,one,two,three,mp)
    end
end

function main()
    global ans
    dfs(1,0,0,0,0)
    println(ans)
end
main()

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


function main()
    const lines=readlines()
    state=0
    input()=lines[state+=1]
    int(s::String)=parse(Int,s)
    intSub(s::SubString{String})=parse(Int,s)
    intLine(s::Array{SubString{String},1})=map(intSub,s)
    const INF=2^60
    a,b,q=input()|>split|>intLine
    s=Array{Int}(a+2)
    s[1],s[a+2]=-INF,INF
    for i in 2:a+1
        s[i]=int(input())
    end
    t=Array{Int}(b+2)
    t[1],t[b+2]=-INF,INF
    for i in 2:b+1
        t[i]=int(input())
    end
    for _ in 1:q
        x=int(input())
        m=INF
        i=searchsortedlast(s,x)
        j=searchsortedlast(t,x)
        for v in view(s,i:i+1)
            for w in view(t,j:j+1)
                m=min(m,abs(x-v)+abs(v-w),abs(x-w)+abs(w-v))
            end
        end
        println(m)
    end
end
main()

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


function main()

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

  if B % A == 0
    println(A+B)
  else
    println(B-A)
  end

end

main()

Score : 100 points

Problem Statement

You are given positive integers A and B.

If A is a divisor of B, print A + B; otherwise, print B - A.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

If A is a divisor of B, print A + B; otherwise, print B - A.

Sample Input 1

4 12

Sample Output 1

16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


a,b=map(x->parse(x),split(readline()))
if b%a==0
  println(a+b)
else
  println(b-a)
end


parseInt(x) = parse(Int, x)
parseFloat(x) = parse(Float64, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    n,m=parseMap(split(readline()))
    food=[0 for i in 1:m]
    for i in 1:n
        a=parseMap(split(readline()))
        for j in 2:a[1]+1
            food[a[j]]+=1
        end
    end
    println(sum([div(i,n) for i in food]))
end
main()

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.

The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.

Find the number of the foods liked by all the N people.

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

Constraints

Input is given from Standard Input in the following format:

N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

Output

Print the number of the foods liked by all the N people.

Sample Input 1

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

Sample Output 1

1

As only the third food is liked by all the three people, 1 should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3


parseInt(x) = parse(Int,x)
parseMap(x::Array{SubString{String}, 1}) = map(parseInt, x)
function main()
  n,m = map(parseInt, split(readline()))
  temp = 1:m
  for i in 1:N
    a = readline() |> split |> parseMap
    temp = filter(x->(x in a[2:end]),temp)
  end
  println(Int64(length(temp)))
end
main()


function main()

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

  println(gcd(a))

end

main()

Score : 300 points

Problem Statement

There are N monsters, numbered 1, 2, ..., N.

Initially, the health of Monster i is A_i.

Below, a monster with at least 1 health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


function GCD(a,b)# a>b

  check = false

  while check == false

    if a % b != 0
      r = a % b
      a = b
      b = r
    else
      check = true
      return b
    end

  end

end

function main()

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

  sort!(A)

  println(GCD(A[1],A[2]))

end

main()


parseInt(x) = parse(Int,x)
parseMap(x::Array{SubString{String}, 1}) = map(parseInt, x)
function main()
  N = map(parseInt, split(readline()))[1]
  a = map(parseInt, split(readline()))
  g  = a[1]
  for i = 1:N-1
    g = gcd(g,a[i+1])
  end
  println(Int64(g))
end
main()


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

function main()
	v = [2,5,5,4,5,6,3,7,6]
	n,m = readline() |> split |> parseMap
	a = readline() |> split |> parseMap
	a = sort(a,rev=true)
	dp = -ones(Int,n+1)
	dp[1] = 0
	for i in 1:n+1
		if dp[i]>=0
			for j in a
				if i+v[j]<=n+1
					dp[i+v[j]]=max(dp[i+v[j]],dp[i]+1)
				end
			end
		end
	end
	k = n+1
	while k>1
		for j in a
			if k-v[j]>0
				if dp[k-v[j]]==dp[k]-1
					print(j)
					k -= v[j]
					break
				end
			end
		end
	end
	println("")
end

main()

Score : 400 points

Problem Statement

Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:

Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).

The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectively.

Constraints

All values in input are integers.

2 \leq N \leq 10^4

1 \leq M \leq 9

1 \leq A_i \leq 9

A_i are all different.

There exists an integer that can be formed by exactly N matchsticks under the conditions.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

Print the largest integer that can be formed with exactly N matchsticks under the conditions in the problem statement.

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

The integer 777773 can be formed with 3 + 3 + 3 + 3 + 3 + 5 = 20 matchsticks, and this is the largest integer that can be formed by 20 matchsticks under the conditions.

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

The output may not fit into a 64-bit integer type.

Sample Input 3

15 3
5 4 6

Sample Output 3

654


import Base.readline
function readint
    parse(Int, strip(readline()))
end

L = readint()

started = 0
notstarted = 0

for _ in 1:L
    a = readint()
    notstarted, started = notstarted + a, min(started + mod(a + 1, 2), notstarted)
end

println(min(notstarted, started))

Score : 100 points

Problem Statement

Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1.

Constraints

1\leq N,K\leq 100

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

If we can choose K integers as above, print YES; otherwise, print NO.

Sample Input 1

3 2

Sample Output 1

YES

We can choose 1 and 3.

Sample Input 2

5 5

Sample Output 2

NO

Sample Input 3

31 10

Sample Output 3

YES

Sample Input 4

10 90

Sample Output 4

NO


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

function main()
	d = zeros(Int,4)
	for i in 1:3
		a,b = readline() |> split |> parseMap
		d[a]+=1
		d[b]+=1
	end
	println(maximum(d)==2?"YES":"NO")
end

main()

Score : 200 points

Problem Statement

There are four towns, numbered 1,2,3 and 4.
Also, there are three roads. The i-th road connects different towns a_i and b_i bidirectionally.
No two roads connect the same pair of towns. Other than these roads, there is no way to travel between these towns, but any town can be reached from any other town using these roads.

Determine if we can visit all the towns by traversing each of the roads exactly once.

Constraints

1 \leq a_i,b_i \leq 4(1\leq i\leq 3)

a_i and b_i are different. (1\leq i\leq 3)

No two roads connect the same pair of towns.

Any town can be reached from any other town using the roads.

Input

Input is given from Standard Input in the following format:

a_1 b_1
a_2 b_2
a_3 b_3

Output

If we can visit all the towns by traversing each of the roads exactly once, print YES; otherwise, print NO.

Sample Input 1

4 2
1 3
2 3

Sample Output 1

YES

We can visit all the towns in the order 1,3,2,4.

Sample Input 2

3 2
2 4
1 2

Sample Output 2

NO

Sample Input 3

2 1
3 2
4 3

Sample Output 3

YES


import Base.readline
function readline(T)
    map(x->parse(T, x), split(readline()))
end

L = readline(Int)[1]
A = map(_->readline(Int)[1], 1:L)

started = 0
notstarted = 0

for a in A
    notstarted, started = notstarted + a, min(started + mod(a + 1, 2), notstarted)
end

println(min(notstarted, started))

Score : 600 points

Problem Statement

Snuke stands on a number line. He has L ears, and he will walk along the line continuously under the following conditions:

He never visits a point with coordinate less than 0, or a point with coordinate greater than L.

He starts walking at a point with integer coordinate, and also finishes walking at a point with integer coordinate.

He only changes direction at a point with integer coordinate.

Each time when Snuke passes a point with coordinate i-0.5, where i is an integer, he put a stone in his i-th ear.

After Snuke finishes walking, Ringo will repeat the following operations in some order so that, for each i, Snuke's i-th ear contains A_i stones:

Put a stone in one of Snuke's ears.

Remove a stone from one of Snuke's ears.

Find the minimum number of operations required when Ringo can freely decide how Snuke walks.

Constraints

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

0 \leq A_i \leq 10^9(1\leq i\leq L)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

L
A_1
:
A_L

Output

Print the minimum number of operations required when Ringo can freely decide how Snuke walks.

Sample Input 1

4
1
0
2
3

Sample Output 1

1

Assume that Snuke walks as follows:

He starts walking at coordinate 3 and finishes walking at coordinate 4, visiting coordinates 3,4,3,2,3,4 in this order.

Then, Snuke's four ears will contain 0,0,2,3 stones, respectively.
Ringo can satisfy the requirement by putting one stone in the first ear.

Sample Input 2

8
2
0
0
2
1
3
4
1

Sample Output 2

3

Sample Input 3

7
314159265
358979323
846264338
327950288
419716939
937510582
0

Sample Output 3

1


function reader(pos::Int)
    global membuff
    val = 0
    sign = 1
    @inbounds r = membuff[pos]
    pos += 1
    while r < 0x30 || 0x39 < r
        sign = r == '-' ? -1 : sign
        @inbounds r = membuff[pos]
        pos += 1
    end
    while 0x30 <= r <= 0x39
        val = val * 10 + r - 0x30
        @inbounds r = membuff[pos]
        pos += 1
    end
    return val*sign, pos
end

const io = VERSION > v"1.0" ? stdin : STDIN
const membuff = read(io,1145141919)

#using LinearAlgebra: rank
function main()
    pos = 1
    N, pos = reader(pos)
    M, pos = reader(pos)
    a = zeros(Int,(M,N))
    for i=1:N, j=1:M
        @inbounds a[j,i], pos = reader(pos)
    end
    r = rank(a)
    mod = 998244353
    ans = powermod(2, N+M-1, mod) - powermod(2, N+M-r-1, mod)
    println( ans < 0 ? ans + mod : ans )
end

main()

Score : 800 points

Problem Statement

There is a square grid with N rows and M columns.
Each square contains an integer: 0 or 1. The square at the i-th row from the top and the j-th column from the left contains a_{ij}.

Among the 2^{N+M} possible pairs of a subset A of the rows and a subset B of the columns, find the number of the pairs that satisfy the following condition, modulo 998244353:

The sum of the |A||B| numbers contained in the intersection of the rows belonging to A and the columns belonging to B, is odd.

Constraints

1 \leq N,M \leq 300

0 \leq a_{i,j} \leq 1(1\leq i\leq N,1\leq j\leq M)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
a_{11} ... a_{1M}
:
a_{N1} ... a_{NM}

Output

Print the number of the pairs of a subset of the rows and a subset of the columns that satisfy the condition, modulo 998244353.

Sample Input 1

2 2
0 1
1 0

Sample Output 1

6

For example, if A consists of the first row and B consists of both columns, the sum of the numbers contained in the intersection is 0+1=1.

Sample Input 2

2 3
0 0 0
0 1 0

Sample Output 2

8


function f()
    n = parse(Int, readline())
    l = map(x->parse(Int, x), split(chomp(readline()), " "))
    l_max = findmax(l)[1]
    l[findmax(l)[2]] = 0
    l_sum = sum(l)
    if l_max < l_sum
        print("Yes")
    else
        print("No")
    end
end
f()

Score : 200 points

Problem Statement

Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.

You can use the following theorem:

Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths of the other N-1 sides.

Constraints

All values in input are integers.

3 \leq N \leq 10

1 \leq L_i \leq 100

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Output

If an N-sided polygon satisfying the condition can be drawn, print Yes; otherwise, print No.

Sample Input 1

4
3 8 5 1

Sample Output 1

Yes

Since 8 < 9 = 3 + 5 + 1, it follows from the theorem that such a polygon can be drawn on a plane.

Sample Input 2

4
3 8 4 1

Sample Output 2

No

Since 8 \geq 8 = 3 + 4 + 1, it follows from the theorem that such a polygon cannot be drawn on a plane.

Sample Input 3

10
1 8 10 5 8 12 34 100 11 3

Sample Output 3

No


N,M=map(x->parse(Int,x),split(readline()))
X=sort(map(x->parse(Int,x),split(readline())))
L=Array{Int}(0)
for i=2:M
	push!(L,X[i]-X[i-1])
end
sort!(L)
ans=X[end]-X[1]
for i=1:N-1
	if i<=length(L)
		ans-=L[end-i+1]
	end
end
println(ans)

Score : 300 points

Problem Statement

We will play a one-player game using a number line and N pieces.

First, we place each of these pieces at some integer coordinate.

Here, multiple pieces can be placed at the same coordinate.

Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:

Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.

Note that the coordinates where we initially place the pieces are already regarded as visited.

Find the minimum number of moves required to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

-10^5 \leq X_i \leq 10^5

X_1, X_2, ..., X_M are all different.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_M

Output

Find the minimum number of moves required to achieve the objective.

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.

Initially, put the two pieces at coordinates 1 and 10.

Move the piece at coordinate 1 to 2.

Move the piece at coordinate 10 to 11.

Move the piece at coordinate 11 to 12.

Move the piece at coordinate 12 to 13.

Move the piece at coordinate 13 to 14.

Sample Input 2

3 7
-10 -3 0 9 -100 2 17

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function tsort(e::Array{Int,2},n,m)
	g = [Int[] for i in 1:n]
	d = zeros(Int,n)
	v = zeros(Int,n)
	for i in 1:m
		push!(g[e[1,i]],e[2,i])
		d[e[2,i]] += 1
	end
	s = Int[]
	for i in 1:n
		if d[i] == 0
			push!(s,i)
		end
	end
	l = Int[]
	while !isempty(s)
		t = pop!(s)
		push!(l,t)
		for i in 1:length(g[t])
			d[g[t][i]] -= 1
			if d[g[t][i]] == 0
				push!(s,g[t][i])
			end
		end
	end
	if length(l) == n
		l
	else
		false
	end
end

function main()
	n,m = readline() |> split |> parseMap
	e = zeros(Int,2,n-1+m)
	g = [Int[] for i in 1:n]
	for i in 1:n-1+m
		e[:,i] = readline() |> split |> parseMap
		push!(g[e[2,i]],e[1,i])
	end
	ts = tsort(e,n,n+m-1)
	nm = zeros(Int,n)
	for i in 1:n
		nm[ts[i]] = i
	end
	t = zeros(Int,n)
	for i in n:-1:1
		mx = 0
		mi = 0
		for j in g[ts[i]]
			if nm[j]>mx
				mx = nm[j]
				mi = j
			end
		end
		t[ts[i]]=mi
	end
	for i in 1:n
		println(t[i])
	end
end

main()

Score : 500 points

Problem Statement

There is a rooted tree (see Notes) with N vertices numbered 1 to N.
Each of the vertices, except the root, has a directed edge coming from its parent.
Note that the root may not be Vertex 1.

Takahashi has added M new directed edges to this graph.
Each of these M edges, u \rightarrow v, extends from some vertex u to its descendant v.

You are given the directed graph with N vertices and N-1+M edges after Takahashi added edges.
More specifically, you are given N-1+M pairs of integers, (A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M}), which represent that the i-th edge extends from Vertex A_i to Vertex B_i.

Restore the original rooted tree.

Notes

For "tree" and other related terms in graph theory, see the article in Wikipedia, for example.

Constraints

3 \leq N

1 \leq M

N + M \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

If i \neq j, (A_i, B_i) \neq (A_j, B_j).

The graph in input can be obtained by adding M edges satisfying the condition in the problem statement to a rooted tree with N vertices.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_{N-1+M} B_{N-1+M}

Output

Print N lines.
In the i-th line, print 0 if Vertex i is the root of the original tree, and otherwise print the integer representing the parent of Vertex i in the original tree.

Note that it can be shown that the original tree is uniquely determined.

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

It can be seen that this graph is obtained by adding the edge 1 \rightarrow 3 to the rooted tree 1 \rightarrow 2 \rightarrow 3.

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2


Score : 100 points

Problem Statement

There is a right triangle ABC with ∠ABC=90°.

Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC.

It is guaranteed that the area of the triangle ABC is an integer.

Constraints

1 \leq |AB|,|BC|,|CA| \leq 100

All values in input are integers.

The area of the triangle ABC is an integer.

Input

Input is given from Standard Input in the following format:

|AB| |BC| |CA|

Output

Print the area of the triangle ABC.

Sample Input 1

3 4 5

Sample Output 1

6

This triangle has an area of 6.

Sample Input 2

5 12 13

Sample Output 2

30

This triangle has an area of 30.

Sample Input 3

45 28 53

Sample Output 3

630

This triangle has an area of 630.


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


parseInt(x) = parse(Int, x)
parseFloat(x) = parse(Float64, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    s=parseInt(readline())
    arr=Vector{Int}([s])
    res=s
    ans=1
    while true
        if res%2==0
            res=div(res,2)
        else
            res=3*res+1
        end
        ans+=1
        for i in 1:length(arr)
            if res==arr[i]
                println(ans)
                exit(0)
            end
        end
        push!(arr,res)
    end
end
main()

Score : 200 points

Problem Statement

A sequence a=\{a_1,a_2,a_3,......\} is determined as follows:

The first term s is given as input.

Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd.

a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1.

Find the minimum integer m that satisfies the following condition:

There exists an integer n such that a_m = a_n (m > n).

Constraints

1 \leq s \leq 100

All values in input are integers.

It is guaranteed that all elements in a and the minimum m that satisfies the condition are at most 1000000.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum integer m that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

a=\{8,4,2,1,4,2,1,4,2,1,......\}. As a_5=a_2, the answer is 5.

Sample Input 2

7

Sample Output 2

18

a=\{7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1,4,2,1,......\}.

Sample Input 3

54

Sample Output 3

114


function main()

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

  ans = 0
  check = 1
  save = 0

  for i in 1:N
    if N == 1
      ans = h[1]
    elseif i < N && h[i] > h[i+1]
      ans += h[i] - save
      if h[i+1] - save <= 0
        save = 0
      else
        save = h[i+1]
      end
    elseif i == N && h[i-1] < h[i]
      ans += h[i] - save
    end
  end

  println(ans)

end

main()

Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221


readline()
ans=0
pre=0
for h=map(x->parse(Int,x),split(readline()))
	ans+=max(h-pre,0)
	pre=h
end
println(ans)


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

pointSum(pointD, typeNum) = pointD + (typeNum * typeNum)

function main()
    n, k = readline() |> split |> parseMap
    sushi = zeros(Int, n, 2)
    for i in 1:n
        sushi[i,2], sushi[i,1] = readline() |> split |> parseMap
        # 種類が後の方が都合がよいので
    end
    sushi = sortslices(sushi, dims=1, rev=true)

    pointD = 0
    typeNum = 0
    types = zeros(Int, n)
    for i in 1:k
        pointD += sushi[i, 1]
        types[sushi[i, 2]] += 1
        if types[sushi[i, 2]] == 1
            typeNum += 1
        end
    end

    ans = pointSum(pointD, typeNum)

    iRemove = k
    iAdd = k + 1

    while typeNum < k
        while iRemove > 1
            if types[sushi[iRemove, 2]] > 1
                pointD -= sushi[iRemove, 1]
                types[sushi[iRemove, 2]] -= 1
                break
            end
            iRemove -= 1
        end
        if iRemove == 1 break end
        iRemove -= 1

        while iAdd <= n
            if types[sushi[iAdd, 2]] == 0
                pointD += sushi[iAdd, 1]
                types[sushi[iAdd, 2]] += 1
                typeNum += 1
                break
            end
            iAdd += 1
        end
        if iAdd > n break end
        iAdd += 1

        ans = max(ans, pointSum(pointD, typeNum))
    end
    println(ans)
end

main()

Score : 400 points

Problem Statement

There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i.
You are choosing K among these N pieces to eat.
Your "satisfaction" here will be calculated as follows:

The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".

The base total deliciousness is the sum of the deliciousness of the pieces you eat.

The variety bonus is x*x, where x is the number of different kinds of toppings of the pieces you eat.

You want to have as much satisfaction as possible.
Find this maximum satisfaction.

Constraints

1 \leq K \leq N \leq 10^5

1 \leq t_i \leq N

1 \leq d_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
t_1 d_1
t_2 d_2
.
.
.
t_N d_N

Output

Print the maximum satisfaction that you can obtain.

Sample Input 1

5 3
1 9
1 7
2 6
2 5
3 1

Sample Output 1

26

If you eat Sushi 1,2 and 3:

The base total deliciousness is 9+7+6=22.

The variety bonus is 2*2=4.

Thus, your satisfaction will be 26, which is optimal.

Sample Input 2

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

Sample Output 2

25

It is optimal to eat Sushi 1,2,3 and 4.

Sample Input 3

6 5
5 1000000000
2 990000000
3 980000000
6 970000000
6 960000000
4 950000000

Sample Output 3

4900000016

Note that the output may not fit into a 32-bit integer type.


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

function main()
	n,k = readline() |> split |> parseMap
	a = Array{Int}(3,n)
	for i in 1:n
		a[1:2,i] = readline() |> split |> parseMap
		a[3,i] = 0
	end
	a = sortcols(a,by=x->x[2],rev=true)
	pt1 = sum(a[2,1:k])+length(Set(a[1,1:k]))^2
	pt2 = 0
	t = 0
	sp = Int[]
	for i in 1:n
		if a[1,i] in sp || t >= k
		else
			push!(sp,a[1,i])
			pt2 += a[2,i]
			a[3,i] = 1
			t += 1
		end
	end
	pt2 += t^2
	now = 2
	while t < k
		if a[3,now] == 0
			pt2 += a[2,now]
			t += 1
			now += 1
		end
	end
	println(max(pt1,pt2))
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()
    if sort(split(readline()))==["1","4","7","9"]
        println("YES")
    else
        println("NO")
    end
end
main()

Score : 100 points

Problem Statement

You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974".

Constraints

0 \leq N_1, N_2, N_3, N_4 \leq 9

N_1, N_2, N_3 and N_4 are integers.

Input

Input is given from Standard Input in the following format:

N_1 N_2 N_3 N_4

Output

If N_1, N_2, N_3 and N_4 can be arranged into the sequence of digits "1974", print YES; if they cannot, print NO.

Sample Input 1

1 7 9 4

Sample Output 1

YES

We can get 1974 by swapping N_2 and N_3.

Sample Input 2

1 9 7 4

Sample Output 2

YES

We already have 1974 before doing anything.

Sample Input 3

1 2 9 1

Sample Output 3

NO

Sample Input 4

4 9 0 8

Sample Output 4

NO


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

function main()
	a,b,c,d = readline() |> split |> parseMap
	f = zeros(Int,10)
	f[a+1]+=1
	f[b+1]+=1
	f[c+1]+=1
	f[d+1]+=1
	if f[2]==1&&f[10]==1&&f[8]==1&&f[5]==1
		println("YES")
	else
		println("NO")
	end
end

main()


A=sort(map(x->parse(Int,x),split(readline())))
n=0
for a=A
  n=n*10+a
end
println(n==1479?"YES":"NO")


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

function main()
    n,h,w=[parseInt(readline()) for _ in 1:3]
    println((n-h+1)*(n-w+1))
end
main()

Score : 100 points

Problem Statement

It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board.

The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns.

How many ways are there to choose where to put the notice so that it completely covers exactly HW squares?

Constraints

1 \leq H, W \leq N \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
H
W

Output

Print the answer.

Sample Input 1

3
2
3

Sample Output 1

2

There are two ways to put the notice, as follows:

### ...
### ###
... ###

Here, # represents a square covered by the notice, and . represents a square not covered.

Sample Input 2

100
1
1

Sample Output 2

10000

Sample Input 3

5
4
2

Sample Output 3

8


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

function main()
    n=parseInt(readline())
    a,b=parseMap(split(readline()))
    p=parseMap(split(readline()))
    cnt=zeros(Int,3)
    for i in p
        if i<=a
            cnt[1]+=1
        elseif i<=b
            cnt[2]+=1
        else
            cnt[3]+=1
        end
    end
    println(minimum(cnt))
end
main()

Score : 200 points

Problem Statement

You have written N problems to hold programming contests.
The i-th problem will have a score of P_i points if used in a contest.

With these problems, you would like to hold as many contests as possible under the following condition:

A contest has three problems. The first problem has a score not greater than A points, the second has a score between A + 1 and B points (inclusive), and the third has a score not less than B + 1 points.

The same problem should not be used in multiple contests.
At most how many contests can be held?

Constraints

3 \leq N \leq 100

1 \leq P_i \leq 20 (1 \leq i \leq N)

1 \leq A < B < 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A B
P_1 P_2 ... P_N

Output

Print the answer.

Sample Input 1

7
5 15
1 10 16 2 7 20 12

Sample Output 1

2

Two contests can be held by putting the first, second, third problems and the fourth, fifth, sixth problems together.

Sample Input 2

8
3 8
5 5 5 10 10 10 15 20

Sample Output 2

0

No contest can be held, because there is no problem with a score of A = 3 or less.

Sample Input 3

3
5 6
5 6 10

Sample Output 3

1


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function root(uf::Array{Int,1},x);s=x;while uf[s]>0;s=uf[s];end;s;end
same(uf::Array{Int,1},x,y)=root(uf,x)==root(uf,y)?true:false;
function unite(uf::Array{Int,1},x,y);l=root(uf,x);r=root(uf,y);if l!=r;if uf[l]<uf[r];uf[l]+=uf[r];uf[r]=l;else;uf[r]+=uf[l];uf[l]=r;end;end;end

function main()
	h,w = readline() |> split |> parseMap
	g = String["" for i in 1:h]
	c = zeros(Int,h*w)
	uf = -ones(Int,h*w)
	for i in 1:h
		g[i] = readline() |> chomp
	end
	for i in 1:h
		for j in 1:w
			x = (i-1)*w+j
			if g[i][j]=='#'
				c[x] = 1
			end
			if i>1
				if c[(i-2)*w+j]!=c[x]
					unite(uf,(i-2)*w+j,x)
				end
			end
			if j>1
				if c[(i-1)*w+j-1]!=c[x]
					unite(uf,(i-1)*w+j-1,x)
				end
			end
		end
	end
	bd = Dict{Int,Int}()
	wd = Dict{Int,Int}()
	for i in 1:h*w
		r = root(uf,i)
		if c[i]==0
			if haskey(wd,r)
				wd[r] += 1
			else
				wd[r] = 1
			end
		else
			if haskey(bd,r)
				bd[r] += 1
			else
				bd[r] = 1
			end
		end
	end
	ans = 0
	for i in keys(bd)
		if haskey(wd,i)
			ans += bd[i]*wd[i]
		end
	end
	println(ans)
end

main()

Score : 300 points

Problem Statement

There is a grid with H rows and W columns, where each square is painted black or white.

You are given H strings S_1, S_2, ..., S_H, each of length W.
If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is #; if that square is painted white, the j-th character in the string S_i is ..

Find the number of pairs of a black square c_1 and a white square c_2 that satisfy the following condition:

There is a path from the square c_1 to the square c_2 where we repeatedly move to a vertically or horizontally adjacent square through an alternating sequence of black and white squares: black, white, black, white...

Constraints

1 \leq H, W \leq 400

|S_i| = W (1 \leq i \leq H)

For each i (1 \leq i \leq H), the string S_i consists of characters # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

Print the answer.

Sample Input 1

3 3
.#.
..#
#..

Sample Output 1

10

Some of the pairs satisfying the condition are ((1, 2), (3, 3)) and ((3, 1), (3, 2)), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

Sample Input 2

2 4
....
....

Sample Output 2

0

Sample Input 3

4 3
###
###
...
###

Sample Output 3

6


function solve5a1()
   ma=readlines()
   ma=map(x->chomp(x),ma)
   ma=map(split,ma)
   #ma=map(x->map(y->parse(Int,y),x),ma)
   ma=map(x->parse.(x),ma)
   n=ma[1][1]
   ar=ma[2]
    dp=zeros(Int,n,n)
   for i in 1:n
       dp[1,i]=ifelse(iseven(n),-ar[i],ar[i])
   end
   for i0 in 1:n-1,j in 1:n-i0
      i=i0+1
      if iseven(n-i0)
      #     dp[i+1,j]=dp[i,j]-ar[i+j]
         dp[i,j]=min(dp[i-1,j]-ar[i0+j],dp[i-1,j+1]-ar[j])
    #        end
      else
        #     dp[i+1,j]=dp[i,j]
         dp[i,j]=max(dp[i-1,j]+ar[i0+j],dp[i-1,j+1]+ar[j])
      end
   end
   print(dp[n,1])
end
solve5a1()

Score : 100 points

Problem Statement

Taro and Jiro will play the following game against each other.

Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N).
Until a becomes empty, the two players perform the following operation alternately, starting from Taro:

Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.

Let X and Y be Taro's and Jiro's total score at the end of the game, respectively.
Taro tries to maximize X - Y, while Jiro tries to minimize X - Y.

Assuming that the two players play optimally, find the resulting value of X - Y.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the resulting value of X - Y, assuming that the two players play optimally.

Sample Input 1

4
10 80 90 30

Sample Output 1

10

The game proceeds as follows when the two players play optimally (the element being removed is written bold):

Taro: (10, 80, 90, 30) → (10, 80, 90)

Jiro: (10, 80, 90) → (10, 80)

Taro: (10, 80) → (10)

Jiro: (10) → ()

Here, X = 30 + 80 = 110 and Y = 90 + 10 = 100.

Sample Input 2

3
10 100 10

Sample Output 2

-80

The game proceeds, for example, as follows when the two players play optimally:

Taro: (10, 100, 10) → (100, 10)

Jiro: (100, 10) → (10)

Taro: (10) → ()

Here, X = 10 + 10 = 20 and Y = 100.

Sample Input 3

1
10

Sample Output 3

10

Sample Input 4

10
1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1

Sample Output 4

4999999995

The answer may not fit into a 32-bit integer type.

Sample Input 5

6
4 2 9 7 1 5

Sample Output 5

2

The game proceeds, for example, as follows when the two players play optimally:

Taro: (4, 2, 9, 7, 1, 5) → (4, 2, 9, 7, 1)

Jiro: (4, 2, 9, 7, 1) → (2, 9, 7, 1)

Taro: (2, 9, 7, 1) → (2, 9, 7)

Jiro: (2, 9, 7) → (2, 9)

Taro: (2, 9) → (2)

Jiro: (2) → ()

Here, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13.


function solve()
   ma=readlines()
   ma=map(x->chomp(x),ma)
   ma=map(split,ma)
   ma=map(x->parse.(x),ma)
   n=ma[1][1]
   ar=ma[2]
   function fn(cum1)
    if length(cum1)==2 return 0
    else
        p=0
        min=10^10
        for i in 2:length(cum1)-1
            z=cum1[i+1]-cum1[i-1]
            if z<min
                min=z
                p=i
            end
        end
        return min+fn(deleteat!(copy(cum1),p))
    end
  end
  cum=zeros(Int,n+1)
  for i in 2:n+1
      cum[i]=cum[i-1]+ar[i-1]
  end
  print(fn(cum))
end
solve()

Score : 100 points

Problem Statement

There are N slimes lining up in a row.
Initially, the i-th slime from the left has a size of a_i.

Taro is trying to combine all the slimes into a larger slime.
He will perform the following operation repeatedly until there is only one slime:

Choose two adjacent slimes, and combine them into a new slime. The new slime has a size of x + y, where x and y are the sizes of the slimes before combining them. Here, a cost of x + y is incurred. The positional relationship of the slimes does not change while combining slimes.

Find the minimum possible total cost incurred.

Constraints

All values in input are integers.

2 \leq N \leq 400

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 20 30 40

Sample Output 1

190

Taro should do as follows (slimes being combined are shown in bold):

(10, 20, 30, 40) → (30, 30, 40)

(30, 30, 40) → (60, 40)

(60, 40) → (100)

Sample Input 2

5
10 10 10 10 10

Sample Output 2

120

Taro should do, for example, as follows:

(10, 10, 10, 10, 10) → (20, 10, 10, 10)

(20, 10, 10, 10) → (20, 20, 10)

(20, 20, 10) → (20, 30)

(20, 30) → (50)

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 4

6
7 6 8 6 1 1

Sample Output 4

68

Taro should do, for example, as follows:

(7, 6, 8, 6, 1, 1) → (7, 6, 8, 6, 2)

(7, 6, 8, 6, 2) → (7, 6, 8, 8)

(7, 6, 8, 8) → (13, 8, 8)

(13, 8, 8) → (13, 16)

(13, 16) → (29)


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

Score : 200 points

Problem Statement

Takahashi has A untasty cookies containing antidotes, B tasty cookies containing antidotes and C tasty cookies containing poison.

Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death.
As he wants to live, he cannot eat one in such a situation.
Eating a cookie containing antidotes while having a stomachache cures it, and there is no other way to cure stomachaches.

Find the maximum number of tasty cookies that Takahashi can eat.

Constraints

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

A,B and C are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the maximum number of tasty cookies that Takahashi can eat.

Sample Input 1

3 1 4

Sample Output 1

5

We can eat all tasty cookies, in the following order:

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

A tasty cookie containing antidotes

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

Sample Input 2

5 2 9

Sample Output 2

10

Sample Input 3

8 8 1

Sample Output 3

9


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

function main()
	n = parseMap(split(chomp(readline()),""))
	k = 0
	for i in 1:4
		if n[i]==2
			k += 1
		end
	end
	println(k)
end

main()

Score : 100 points

Problem Statement

You are given an integer N that has exactly four digits in base ten.
How many times does 2 occur in the base-ten representation of N?

Constraints

1000 \leq N \leq 9999

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

1222

Sample Output 1

3

2 occurs three times in 1222. By the way, this contest is held on December 22 (JST).

Sample Input 2

3456

Sample Output 2

0

Sample Input 3

9592

Sample Output 3

1


function main()

  N = split(chomp(readline()),"")

  ans = 0

  for in 1:4

    if N[i] == "2"
      ans += 1
    end

  end

end

main()


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

function main()
	n,h,w = readline() |> split |> parseMap
	s = 0
	for i in 1:n
		a,b = readline() |> split |> parseMap
		if h<=a && w<=b
			s += 1
		end
	end
	println(s)
end

main()

Score : 200 points

Problem Statement

There are N rectangular plate materials made of special metal called AtCoder Alloy.
The dimensions of the i-th material are A_i \times B_i (A_i vertically and B_i horizontally).

Takahashi wants a rectangular plate made of AtCoder Alloy whose dimensions are exactly H \times W.
He is trying to obtain such a plate by choosing one of the N materials and cutting it if necessary.
When cutting a material, the cuts must be parallel to one of the sides of the material.
Also, the materials have fixed directions and cannot be rotated.
For example, a 5 \times 3 material cannot be used as a 3 \times 5 plate.

Out of the N materials, how many can produce an H \times W plate if properly cut?

Constraints

1 \leq N \leq 1000

1 \leq H \leq 10^9

1 \leq W \leq 10^9

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N H W
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the answer.

Sample Input 1

3 5 2
10 3
5 2
2 5

Sample Output 1

2

Takahashi wants a 5 \times 2 plate.

The dimensions of the first material are 10 \times 3. We can obtain a 5 \times 2 plate by properly cutting it.

The dimensions of the second material are 5 \times 2. We can obtain a 5 \times 2 plate without cutting it.

The dimensions of the third material are 2 \times 5. We cannot obtain a 5 \times 2 plate, whatever cuts are made. Note that the material cannot be rotated and used as a 5 \times 2 plate.

Sample Input 2

10 587586158 185430194
894597290 708587790
680395892 306946994
590262034 785368612
922328576 106880540
847058850 326169610
936315062 193149191
702035777 223363392
11672949 146832978
779291680 334178158
615808191 701464268

Sample Output 2

8


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,p=parseMap(split(readline()))
    if n==1
        println(p)
    else
        lim=trunc(Int,ceil(p^(1/n)))
        res=1
        for i in 1:lim
            if p%i^n==0
                res=i
            end
        end
        println(res)
    end
end
main()

Score : 300 points

Problem Statement

There are N integers a_1, a_2, ..., a_N not less than 1.
The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P.

Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N.

Constraints

1 \leq N \leq 10^{12}

1 \leq P \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N P

Output

Print the answer.

Sample Input 1

3 24

Sample Output 1

2

The greatest common divisor would be 2 when, for example, a_1=2, a_2=6 and a_3=2.

Sample Input 2

5 1

Sample Output 2

1

As a_i are positive integers, the only possible case is a_1 = a_2 = a_3 = a_4 = a_5 = 1.

Sample Input 3

1 111

Sample Output 3

111

Sample Input 4

4 972439611840

Sample Output 4

206


N = parse(Int64, readline(STDIN))
data = [parse(Int64,readline(STDIN)) for _ in 1:N]
println(length(filter(isodd, data)) > 0 ? "first" : "second")

Score : 500 points

Problem Statement

There is an apple tree that bears apples of N colors. The N colors of these apples are numbered 1 to N, and there are a_i apples of Color i.

You and Lunlun the dachshund alternately perform the following operation (starting from you):

Choose one or more apples from the tree and eat them. Here, the apples chosen at the same time must all have different colors.

The one who eats the last apple from the tree will be declared winner. If both you and Lunlun play optimally, which will win?

Constraints

1 \leq N \leq 10^5

1 \leq a_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

If you will win, print first; if Lunlun will win, print second.

Sample Input 1

2
1
2

Sample Output 1

first

Let Color 1 be red, and Color 2 be blue. In this case, the tree bears one red apple and two blue apples.

You should eat the red apple in your first turn. Lunlun is then forced to eat one of the blue apples, and you can win by eating the other in your next turn.

Note that you are also allowed to eat two apples in your first turn, one red and one blue (not a winning move, though).

Sample Input 2

3
100000
30000
20000

Sample Output 2

second


parseInt(x) = parse(Int, x)

function main()
	n,p=map(parseInt,split(readline()))
	y = Int[]
	x = p
	i = 2
	if n*log(i) > log(x)
		print(1)
	else
		while x > 1 && i <= x^(1/n)
			if x%(i^n) == 0
				push!(y,i)
				x = div(x, i^n)
			else
				i += 1
			end
		end
		k = 1
		for i in 1:length(y)
			k *= y[i]
		end
		print(k)
	end
end

main()


parseInt(x) = parse(Int, x)

function main()
	n = parseInt(readline())
	a = Array{Int}(n)
	for i in 1:n
		a[i] = readline() |> parseInt
	end
	a = sort(a)
	sum = a[1]
	for i in 2:n-1
		if a[i] != a[i-1]
			sum += a[i]
		end
	end
	if sum%2 == 1
		print("first")
	else
		print("second")
	end
end

main()


parseInt(x) = parse(Int, x)

function main()
	n,p=map(parseInt,split(readline()))
	y = Int[]
	x = p
	i = 2
	if n*log(i) > log(x)
		print(1)
	elseif n == 1
		print(p)
	else
		while i^n <= x
			if x%(i^n) == 0
				push!(y,i)
				x = div(x, i^n)
			else
				i += 1
			end
		end
		k = 1
		for i in 1:length(y)
			k *= y[i]
		end
		print(k)
	end
end

main()


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

function main()
    s=chomp(readline())
    n=length(s)
    ans=0
    for _ in 1:5
        for i in n-1:-1:1
            if s[i:i+1]=="BW"
                s=s[1:i-1]*"WB"*s[i+2:end]
                ans+=1
            end
        end
    end
    println(ans)
end
main()

Score : 300 points

Problem Statement

There are N Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.)
The state of each piece is represented by a string S of length N.
If S_i=B, the i-th piece from the left is showing black;
If S_i=W, the i-th piece from the left is showing white.

Consider performing the following operation:

Choose i (1 \leq i < N) such that the i-th piece from the left is showing black and the (i+1)-th piece from the left is showing white, then flip both of those pieces. That is, the i-th piece from the left is now showing white and the (i+1)-th piece from the left is now showing black.

Find the maximum possible number of times this operation can be performed.

Constraints

1 \leq |S| \leq 2\times 10^5

S_i=B or W

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum possible number of times the operation can be performed.

Sample Input 1

BBW

Sample Output 1

2

The operation can be performed twice, as follows:

Flip the second and third pieces from the left.

Flip the first and second pieces from the left.

Sample Input 2

BWBWBW

Sample Output 2

6


function rank(s)
    rankB = [i for (i, c) = enumerate(s) if c == 'B']
    rankW = [i for (i, c) = enumerate(s) if c == 'W']
    return rankB, rankW
end

function main()
    s = chomp(readline())
    n = length(s)

    rankB, rankW = rank(s)
    nb = length(rankB)
    nw = n - nb

    if length(rankB) < length(rankW)
        rank_given = rankB
        rank_desired = Vector{Int}(nw+1:n)
    else
        rank_given = rankW
        rank_desired = Vector{Int}(1:nw)
    end

    rank_given - rank_desired |> sum |> print
end

main()


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

function main()
    n = readline() |> parseInt
    a = readline() |> split |> parseMap |> sort
    d = Dict{Int,Int}()
    for i in 1:n
        if haskey(d,a[i])
            d[a[i]]+=1
        else
            d[a[i]]=1
        end
    end
    x = 0
    for i in n:-1:1
        r = 0
        while 2^r<=a[i]
            r+=1
        end
        t = bsearch(a,2^r-a[i])
        if 0<t<=n
            if a[t]+a[i]==2^r
             if d[a[t]]>0&&d[a[i]]>0
                 x+=1
                 d[a[t]]-=1
                 d[a[i]]-=1
             end
            end
         end
     end

    println(x)
end

main()

Score : 600 points

Problem Statement

Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i.
He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2.
Note that a ball cannot belong to multiple pairs.
Find the maximum possible number of pairs that can be formed.

Here, a positive integer is said to be a power of 2 when it can be written as 2^t using some non-negative integer t.

Constraints

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

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of pairs such that the sum of the integers written on each pair of balls is a power of 2.

Sample Input 1

3
1 2 3

Sample Output 1

1

We can form one pair whose sum of the written numbers is 4 by pairing the first and third balls.
Note that we cannot pair the second ball with itself.

Sample Input 2

5
3 11 14 5 13

Sample Output 2

2


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

function main()
	h,w,n = readline() |> split |> parseMap
	a = Array{Int}(2,n)
	for i in 1:n
		a[:,i] = readline() |> split |> parseMap
	end
	a = sortcols(a,by=x->(x[1],x[2]))
	count = 0
	stack = 0
	flg = 0
	for i in 1:n
		if a[1,i] == a[2,i]+stack
			stack += 1
			count = a[1,i]
		elseif a[1,i] > a[2,i]+stack
			count = a[1,i]
			flg = 1
			break
		end
	end
	if flg == 0
		count = h+1
	end
	println(count-1)
end

main()

Score : 800 points

Problem Statement

Takahashi and Aoki will play a game using a grid with H rows and W columns of square cells.
There are N obstacles on this grid; the i-th obstacle is at (X_i,Y_i).
Here, we represent the cell at the i-th row and j-th column (1 \leq i \leq H, 1 \leq j \leq W) by (i,j).
There is no obstacle at (1,1), and there is a piece placed there at (1,1).

Starting from Takahashi, he and Aoki alternately perform one of the following actions:

Move the piece to an adjacent cell.
Here, let the position of the piece be (x,y). Then Takahashi can only move the piece to (x+1,y), and Aoki can only move the piece to (x,y+1).
If the destination cell does not exist or it is occupied by an obstacle, this action cannot be taken.

Do not move the piece, and end his turn without affecting the grid.

The game ends when the piece does not move twice in a row.

Takahashi would like to perform as many actions (including not moving the piece) as possible before the game ends, while Aoki would like to perform as few actions as possible before the game ends.
How many actions will Takahashi end up performing?

Constraints

1 \leq H,W \leq 2\times 10^5

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

1 \leq X_i \leq H

1 \leq Y_i \leq W

If i \neq j, (X_i,Y_i) \neq (X_j,Y_j)

(X_i,Y_i) \neq (1,1)

X_i and Y_i are integers.

Input

Input is given from Standard Input in the following format:

H W N
X_1 Y_1
:
X_N Y_N

Output

Print the number of actions Takahashi will end up performing.

Sample Input 1

3 3 1
3 2

Sample Output 1

2

For example, the game proceeds as follows:

Takahashi moves the piece to (2,1).

Aoki does not move the piece.

Takahashi moves the piece to (3,1).

Aoki does not move the piece.

Takahashi does not move the piece.

Takahashi performs three actions in this case, but if both players play optimally, Takahashi will perform only two actions before the game ends.

Sample Input 2

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

Sample Output 2

6

Sample Input 3

100000 100000 0

Sample Output 3

100000


n=parse(Int,readline())
s=0
m=0
for i in 1..n
  x=parse(Int,readline())
  s+=x
  if m<x
    m=x
  end
end
print(s-div(m,2))

Score : 200 points

Problem Statement

In some other world, today is the day before Christmas Eve.

Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).

He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 items cost their regular prices. What is the total amount he will pay?

Constraints

2 \leq N \leq 10

100 \leq p_i \leq 10000

p_i is an even number.

Input

Input is given from Standard Input in the following format:

N
p_1
p_2
:
p_N

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

The 7980-yen item gets the discount and the total is 4980 + 7980 / 2 + 6980 = 15950 yen.

Note that outputs such as 15950.0 will be judged as Wrong Answer.

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

Only one of the four items gets the discount and the total is 4320 / 2 + 4320 + 4320 + 4320 = 15120 yen.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
N,K = parseMap(split(readline()))
H = []
for i in 1:N
    h = parseInt(readline())
    push!(H,h)
end
sort!(H)

min_s = 10^10
for i in 1:N-K+1
    s = H[i+K-1] - H[i]
    if s < min_s
        min_s = s
    end
end
println(min_s)

Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.

He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.

More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

Print the minimum possible value of h_{max} - h_{min}.

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

If we decorate the second, fourth and fifth trees, h_{max} = 7, h_{min} = 7 so h_{max} - h_{min} = 0. This is optimal.

There are not too many trees in these sample inputs, but note that there can be at most one hundred thousand trees (we just can't put a sample with a hundred thousand lines here).


#include<bits/stdc++.h>
using namespace std;
int main(){
    int n,k,l = 1e9;
    cin >> n >> k;
    vector<int> a(n);
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }
    for(int i = 0; i < n; i++){
        for(int j = i + 1; j < n; j++){
            for(int k = j + 1; k < n; k++){
                int d = max({a[i],a[j],a[k]}) - min({a[i],a[j],a[k]});
                if(d < l)
                l = d;
            }
        }
    }
    cout << l << endl;
}


N,X=map(x->parse(Int,x),split(readline()))
S=0
while N>=0
	T=2<<N
	N-=1
	if X>T-2
		S+=div(T,2)
		X-=T-1
	else
		X-=1
	end
end
println(S)

Score : 400 points

Problem Statement

In some other world, today is Christmas.

Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:

A level-0 burger is a patty.

A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) burger and another bun, stacked vertically in this order from the bottom.

For example, a level-1 burger and a level-2 burger look like BPPPB and BBPPPBPBPPPBB (rotated 90 degrees), where B and P stands for a bun and a patty.

The burger Mr. Takaha will make is a level-N burger. Lunlun the Dachshund will eat X layers from the bottom of this burger (a layer is a patty or a bun). How many patties will she eat?

Constraints

1 \leq N \leq 50

1 \leq X \leq ( the total number of layers in a level-N burger )

N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

Print the number of patties in the bottom-most X layers from the bottom of a level-N burger.

Sample Input 1

2 7

Sample Output 1

4

There are 4 patties in the bottom-most 7 layers of a level-2 burger (BBPPPBPBPPPBB).

Sample Input 2

1 1

Sample Output 2

0

The bottom-most layer of a level-1 burger is a bun.

Sample Input 3

50 4321098765432109

Sample Output 3

2160549382716056

A level-50 burger is rather thick, to the extent that the number of its layers does not fit into a 32-bit integer.


N,X=map(x->parse(Int,x),split(readline()))
S=0
while X>0
	T=2<<N
	N-=1
	if X>T-2>=0
		S+=div(T,2)
		X-=T-1
	else
		X-=1
	end
end
println(S)


N,X=map(x->parse(Int,x),split(readline()))
S=0
while X>0
	T=2<<N
	N-=1
	if T-2>=0&&X>T-2
		S+=div(T,2)
		X-=T-1
	else
		X-=1
	end
end
println(S)


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()
  s=chomp(readline())
  println(minimum([abs(753-pI(s[i-2:i])) for i=3:length(s)]))
end
main()
if isdefined(Base, :mystdin);close(mystdin);end

Score : 200 points

Problem Statement

There is a string S consisting of digits 1, 2, ..., 9.
Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)

The master's favorite number is 753. The closer to this number, the better.
What is the minimum possible (absolute) difference between X and 753?

Constraints

S is a string of length between 4 and 10 (inclusive).

Each character in S is 1, 2, ..., or 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum possible difference between X and 753.

Sample Input 1

1234567876

Sample Output 1

34

Taking out the seventh to ninth characters results in X = 787, and the difference between this and 753 is 787 - 753 = 34. The difference cannot be made smaller, no matter where X is taken from.

Note that the digits cannot be rearranged. For example, taking out 567 and rearranging it to 765 is not allowed.

We cannot take out three digits that are not consecutive from S, either. For example, taking out the seventh digit 7, the ninth digit 7 and the tenth digit 6 to obtain 776 is not allowed.

Sample Input 2

35753

Sample Output 2

0

If 753 itself can be taken out, the answer is 0.

Sample Input 3

1111111111

Sample Output 3

642

No matter where X is taken from, X = 111, with the difference 753 - 111 = 642.


Score : 300 points

Problem Statement

You are given an integer N. Among the integers between 1 and N (inclusive), how many Shichi-Go-San numbers (literally "Seven-Five-Three numbers") are there?

Here, a Shichi-Go-San number is a positive integer that satisfies the following condition:

When the number is written in base ten, each of the digits 7, 5 and 3 appears at least once, and the other digits never appear.

Constraints

1 \leq N < 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go-San numbers between 1 and N (inclusive).

Sample Input 1

575

Sample Output 1

4

There are four Shichi-Go-San numbers not greater than 575: 357, 375, 537 and 573.

Sample Input 2

3600

Sample Output 2

13

There are 13 Shichi-Go-San numbers not greater than 3600: the above four numbers, 735, 753, 3357, 3375, 3537, 3557, 3573, 3575 and 3577.

Sample Input 3

999999999

Sample Output 3

26484


Score : 400 points

Problem Statement

You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there?

Here, a Shichi-Go number is a positive integer that has exactly 75 divisors.

Note

When a positive integer A divides a positive integer B, A is said to a divisor of B.
For example, 6 has four divisors: 1, 2, 3 and 6.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go numbers that are divisors of N!.

Sample Input 1

9

Sample Output 1

0

There are no Shichi-Go numbers among the divisors of 9! = 1 \times 2 \times ... \times 9 = 362880.

Sample Input 2

10

Sample Output 2

1

There is one Shichi-Go number among the divisors of 10! = 3628800: 32400.

Sample Input 3

100

Sample Output 3

543


parseInt(x) = parse(Int, x)

function main()
	n = parseInt(readline())
	a = map(parseInt, split(readline()))
	avg = sum(a)/n
	b = abs(a-avg)
	l = 1
	for i in 2:n
		if b[i] < b[l]
			l = i
		end
	end
	println(l-1)
end

main()

Score : 200 points

Problem Statement

Niwango-kun is an employee of Dwango Co., Ltd.

One day, he is asked to generate a thumbnail from a video a user submitted.

To generate a thumbnail, he needs to select a frame of the video according to the following procedure:

Get an integer N and N integers a_0, a_1, ..., a_{N-1} as inputs. N denotes the number of the frames of the video, and each a_i denotes the representation of the i-th frame of the video.

Select t-th frame whose representation a_t is nearest to the average of all frame representations.

If there are multiple such frames, select the frame with the smallest index.

Find the index t of the frame he should select to generate a thumbnail.

Constraints

1 \leq N \leq 100

1 \leq a_i \leq 100

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N
a_{0} a_{1} ... a_{N-1}

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

1

Since the average of frame representations is 2, Niwango-kun needs to select the index 1, whose representation is 2, that is, the nearest value to the average.

Sample Input 2

4
2 5 2 5

Sample Output 2

0

The average of frame representations is 3.5.

In this case, every frame has the same distance from its representation to the average.

Therefore, Niwango-kun should select index 0, the smallest index among them.


parseInt(x) = parse(Int, x)

function main()
	n, m = parseInt(split(readline()))
	x = Array{Int}(2,m)
	for i in 1:m
	  x[:,i] = parseInt(split(readline()))
	end
	print("G")
end

main()

Score: 100 points

Problem Statement

There is a train going from Station A to Station B that costs X yen (the currency of Japan).

Also, there is a bus going from Station B to Station C that costs Y yen.

Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.

How much does it cost to travel from Station A to Station C if she uses this ticket?

Constraints

1 \leq X,Y \leq 100

Y is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If it costs x yen to travel from Station A to Station C, print x.

Sample Input 1

81 58

Sample Output 1

110

The train fare is 81 yen.

The train fare is 58 ⁄ 2=29 yen with the 50% discount.

Thus, it costs 110 yen to travel from Station A to Station C.

Sample Input 2

4 54

Sample Output 2

31


parseInt(x) = parse(Int, x)
function main()
	n = parseInt(readline())
	t,a = map(parseInt, split(readline()))
	h = map(parseInt, split(readline()))
	min = 1000
	num = 0
	l = Array{Float64}(n)
	for i in 1:n
		l[i] = abs(a-t+0.006*h[i])
		if l[i] <= min
			min = l[i]
			num = i
		end
	end
	print(num)
end
main()

Score: 200 points

Problem Statement

A country decides to build a palace.

In this country, the average temperature of a point at an elevation of x meters is T-x \times 0.006 degrees Celsius.

There are N places proposed for the place. The elevation of Place i is H_i meters.

Among them, Princess Joisino orders you to select the place whose average temperature is the closest to A degrees Celsius, and build the palace there.

Print the index of the place where the palace should be built.

It is guaranteed that the solution is unique.

Constraints

1 \leq N \leq 1000

0 \leq T \leq 50

-60 \leq A \leq T

0 \leq H_i \leq 10^5

All values in input are integers.

The solution is unique.

Input

Input is given from Standard Input in the following format:

N
T A
H_1 H_2 ... H_N

Output

Print the index of the place where the palace should be built.

Sample Input 1

2
12 5
1000 2000

Sample Output 1

1

The average temperature of Place 1 is 12-1000 \times 0.006=6 degrees Celsius.

The average temperature of Place 2 is 12-2000 \times 0.006=0 degrees Celsius.

Thus, the palace should be built at Place 1.

Sample Input 2

3
21 -11
81234 94124 52141

Sample Output 2

3


parseInt(x) = parse(Int, x)

function main()
	n, m = parseInt.(split(readline()))
	x = Array{Int}(2,m)
	for i in 1:m
	  x[:,i] = map(parseInt, split(readline()))
	end
	print("G")
end

main()

Score: 300 points

Problem Statement

In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.

City i is established in year Y_i and belongs to Prefecture P_i.

You can assume that there are no multiple cities that are established in the same year.

It is decided to allocate a 12-digit ID number to each city.

If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.

Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.

Find the ID numbers for all the cities.

Note that there can be a prefecture with no cities.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq P_i \leq N

1 \leq Y_i \leq 10^9

Y_i are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
P_1 Y_1
:
P_M Y_M

Output

Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).

Sample Input 1

2 3
1 32
2 63
1 12

Sample Output 1

000001000002
000002000001
000001000001

As City 1 is the second established city among the cities that belong to Prefecture 1, its ID number is 000001000002.

As City 2 is the first established city among the cities that belong to Prefecture 2, its ID number is 000002000001.

As City 3 is the first established city among the cities that belong to Prefecture 1, its ID number is 000001000001.

Sample Input 2

2 3
2 55
2 77
2 99

Sample Output 2

000002000001
000002000002
000002000003


n, m = parse.(input(readline()))
for i in 1:m
  readline(STDIN)
end

print("G")


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

function pos(i,j,w)
	if w == 1
		1
	elseif j <= 2 || j >= w+1
    	if i == j
      		fib(w)
    	else
      		fib(w-1)
    	end
    elseif i <= 2 || i >= w+1
		fib(w-1)
	elseif i == j
		fib(i-1)*fib(w+2-i)
	else
		fib(min(i,j)-1)*fib(w+2-max(i,j))
	end
end

function fib(k)
	if k == 1
		1
	elseif k == 2
		1
	else
		x = Array{Int}(k)
		x[1] = 1
		x[2] = 1
		for i in 3:k
			x[i] = x[i-2]+x[i-1]
		end
		x[k]
	end
end

function main()
	h,w,k = readline() |> split |> parseMap
	dp = Array{Int}(h+1,w+2)
	count = 0
	for i in 1:w+2
		dp[1,i] = 0
	end
	for i in 1:h+1
		dp[i,1] = 0
		dp[i,w+2] = 0
	end
    dp[1,2] = 1
	for i in 2:h+1
		for j in 2:w+1
			dp[i,j] = ((dp[i-1,j-1]*pos(j-1,j,w))%1000000007 + (dp[i-1,j]*pos(j,j,w))%1000000007 + (dp[i-1,j+1]*pos(j+1,j,w))%1000000007)%1000000007
		end
	end
	println(dp[h+1,k+1]%1000000007)
end

main()

Score: 400 points

Problem Statement

Amidakuji is a traditional method of lottery in Japan.

To make an amidakuji, we first draw W parallel vertical lines, and then draw horizontal lines that connect them. The length of each vertical line is H+1 [cm], and the endpoints of the horizontal lines must be at 1, 2, 3, ..., or H [cm] from the top of a vertical line.

A valid amidakuji is an amidakuji that satisfies the following conditions:

No two horizontal lines share an endpoint.

The two endpoints of each horizontal lines must be at the same height.

A horizontal line must connect adjacent vertical lines.

Find the number of the valid amidakuji that satisfy the following condition, modulo 1\ 000\ 000\ 007: if we trace the path from the top of the leftmost vertical line to the bottom, always following horizontal lines when we encounter them, we reach the bottom of the K-th vertical line from the left.

For example, in the following amidakuji, we will reach the bottom of the fourth vertical line from the left.

Constraints

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

W is an integer between 1 and 8 (inclusive).

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

Input

Input is given from Standard Input in the following format:

H W K

Output

Print the number of the amidakuji that satisfy the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

1 3 2

Sample Output 1

1

Only the following one amidakuji satisfies the condition:

Sample Input 2

1 3 1

Sample Output 2

2

Only the following two amidakuji satisfy the condition:

Sample Input 3

2 3 3

Sample Output 3

1

Only the following one amidakuji satisfies the condition:

Sample Input 4

2 3 1

Sample Output 4

5

Only the following five amidakuji satisfy the condition:

Sample Input 5

7 1 1

Sample Output 5

1

As there is only one vertical line, we cannot draw any horizontal lines. Thus, there is only one amidakuji that satisfies the condition: the amidakuji with no horizontal lines.

Sample Input 6

15 8 5

Sample Output 6

437760187

Be sure to print the answer modulo 1\ 000\ 000\ 007.


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

function main()
    s=chomp(readline())
    if length(s)==2
        println(s)
    else
        println(reverse(s))
    end
end
main()

Score : 100 points

Problem Statement

You are given a string S of length 2 or 3 consisting of lowercase English letters. If the length of the string is 2, print it as is; if the length is 3, print the string after reversing it.

Constraints

The length of S is 2 or 3.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If the length of S is 2, print S as is; if the length is 3, print S after reversing it.

Sample Input 1

abc

Sample Output 1

cba

As the length of S is 3, we print it after reversing it.

Sample Input 2

ac

Sample Output 2

ac

As the length of S is 2, we print it as is.


function main()
	s = split(readline(), "")
	if length(s) == 2
		for i in 1:2
			print(s[i])
		end
	else
		for i in 0:2
			print(s[3-i])
		end
	end
	println()
end

main()


function parseInt(x) parse(Int, x) end
function conInt(x) convert(Int, x) end

function main()
	n = parseInt(readline())
	x = Int[]
	sum = 0
	for i in 1:n
		push!(x, parseInt(readline()))
	end
	y = sort(x)
	sum += y[n]-y[1]
	if n%2 == 1
		for i in 1:conInt((n-3)/2)
			sum += y[n-i]-y[i]
			sum += y[n+1-i]-y[i+1]
		end
		sum += max(y[conInt((n+1)/2)]-y[conInt((n-1)/2)], y[conInt((n+3)/2)]-y[conInt((n+1)/2)])
	else
		for i in 1:conInt((n-4)/2)
			sum += y[n-i]-y[i]
			sum += y[n+1-i]-y[i+1]
		end
		sum += max(y[conInt(n/2)]-y[conInt((n-2)/2)]+y[conInt((n+4)/2)]-y[conInt((n+2)/2)], y[conInt((n+2)/2)]-y[conInt((n-2)/2)]+y[conInt((n+4)/2)]-y[conInt(n/2)])
	end
	println(sum)
end
main()

Score : 400 points

Problem Statement

You are given N integers; the i-th of them is A_i.
Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like.

Constraints

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the maximum possible sum of the absolute differences between the adjacent elements after arranging the given integers in a row in any order you like.

Sample Input 1

5
6
8
1
2
3

Sample Output 1

21

When the integers are arranged as 3,8,1,6,2, the sum of the absolute differences between the adjacent elements is |3 - 8| + |8 - 1| + |1 - 6| + |6 - 2| = 21. This is the maximum possible sum.

Sample Input 2

6
3
1
4
1
5
9

Sample Output 2

25

Sample Input 3

3
5
5
1

Sample Output 3

8


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

function main()
    n,m=parseMap(split(readline()))
    s=chomp(readline())
    t=chomp(readline())
    l=BigInt(lcm(n,m))
    ans=l
    s_=[i*l÷n+1 for i in 0:n-1]
    t_=[i*l÷m+1 for i in 0:m-1]
    for i in 1:n
        num=searchsortedfirst(t_,s_[i])
        if num<=m && s_[i]==t_[num] && s[i]!=t[num]
            ans=-1
            break
        end
    end
    println(ans)
end
main()

Score : 300 points

Problem Statement

You are given a string S of length N and another string T of length M.
These strings consist of lowercase English letters.

A string X is called a good string when the following conditions are all met:

Let L be the length of X. L is divisible by both N and M.

Concatenating the 1-st, (\frac{L}{N}+1)-th, (2 \times \frac{L}{N}+1)-th, ..., ((N-1)\times\frac{L}{N}+1)-th characters of X, without changing the order, results in S.

Concatenating the 1-st, (\frac{L}{M}+1)-th, (2 \times \frac{L}{M}+1)-th, ..., ((M-1)\times\frac{L}{M}+1)-th characters of X, without changing the order, results in T.

Determine if there exists a good string. If it exists, find the length of the shortest such string.

Constraints

1 \leq N,M \leq 10^5

S and T consist of lowercase English letters.

|S|=N

|T|=M

Input

Input is given from Standard Input in the following format:

N M
S
T

Output

If a good string does not exist, print -1; if it exists, print the length of the shortest such string.

Sample Input 1

3 2
acp
ae

Sample Output 1

6

For example, the string accept is a good string.
There is no good string shorter than this, so the answer is 6.

Sample Input 2

6 3
abcdef
abc

Sample Output 2

-1

Sample Input 3

15 9
dnsusrayukuaiia
dujrunuma

Sample Output 3

45


M=10^9+7
i=s=r=big"0"
A=(x->parse(Int,x)).(split(readlines()[2]))
for a=A
s+=invmod(i+=1,M)
r+=a*~-s+A[end+1-i]s
end
print(factorial(i)r%M)

Score : 600 points

Problem Statement

There are N blocks arranged in a row, numbered 1 to N from left to right.
Each block has a weight, and the weight of Block i is A_i.
Snuke will perform the following operation on these blocks N times:

Choose one block that is still not removed, and remove it.
The cost of this operation is the sum of the weights of the blocks that are connected to the block being removed (including itself).
Here, two blocks x and y ( x \leq y ) are connected when, for all z ( x \leq z \leq y ), Block z is still not removed.

There are N! possible orders in which Snuke removes the blocks.
For all of those N! orders, find the total cost of the N operations, and calculate the sum of those N! total costs.
As the answer can be extremely large, compute the sum modulo 10^9+7.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For all of the N! orders, find the total cost of the N operations, and print the sum of those N! total costs, modulo 10^9+7.

Sample Input 1

2
1 2

Sample Output 1

9

First, we will consider the order "Block 1 -> Block 2".
In the first operation, the cost of the operation is 1+2=3, as Block 1 and 2 are connected.
In the second operation, the cost of the operation is 2, as only Block 2 remains.
Thus, the total cost of the two operations for this order is 3+2=5.

Then, we will consider the order "Block 2 -> Block 1".
In the first operation, the cost of the operation is 1+2=3, as Block 1 and 2 are connected.
In the second operation, the cost of the operation is 1, as only Block 1 remains.
Thus, the total cost of the two operations for this order is 3+1=4.

Therefore, the answer is 5+4=9.

Sample Input 2

4
1 1 1 1

Sample Output 2

212

Sample Input 3

10
1 2 4 8 16 32 64 128 256 512

Sample Output 3

880971923