N=parse(Int,readline())
s=chomp(readline())
function f(a,b)
	A=Bool[a,b]
	for i=2:N-1
		if A[i]
			if s[i]=='o'
				push!(A,A[i-1])
			else
				push!(A,!A[i-1])
			end
		else
			if s[i]=='o'
				push!(A,!A[i-1])
			else
				push!(A,A[i-1])
			end
		end
	end
	if (s[1]=='o')$A[1]$(A[2]==A[N])&&(s[N]=='o')$A[N]$(A[1]==A[N-1])
		for i=1:N
			print(A[i]?'S':'W')
		end
		println()
		true
	else
		false
	end
end
f(true,true)||f(true,false)||f(false,true)||f(false,false)||println(-1)

Score : 500 points

Problem Statement

Snuke, who loves animals, built a zoo.

There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle.
The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.

There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.

Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is o, the animal said that the two neighboring animals are of the same species, and if s_i is x, the animal said that the two neighboring animals are of different species.

More formally, a sheep answered o if the two neighboring animals are both sheep or both wolves, and answered x otherwise.
Similarly, a wolf answered x if the two neighboring animals are both sheep or both wolves, and answered o otherwise.

Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print -1.

Constraints

3 ≤ N ≤ 10^{5}

s is a string of length N consisting of o and x.

Input

The input is given from Standard Input in the following format:

N
s

Output

If there does not exist an valid assignment that is consistent with s, print -1.
Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.

t is a string of length N consisting of S and W.

If t_i is S, it indicates that the animal numbered i is a sheep. If t_i is W, it indicates that the animal numbered i is a wolf.

Sample Input 1

6
ooxoox

Sample Output 1

SSSWWS

For example, if the animals numbered 1, 2, 3, 4, 5 and 6 are respectively a sheep, sheep, sheep, wolf, wolf, and sheep, it is consistent with their responses. Besides, there is another valid assignment of species: a wolf, sheep, wolf, sheep, wolf and wolf.

Let us remind you: if the neiboring animals are of the same species, a sheep answers o and a wolf answers x. If the neiboring animals are of different species, a sheep answers x and a wolf answers o.

Sample Input 2

3
oox

Sample Output 2

-1

Print -1 if there is no valid assignment of species.

Sample Input 3

10
oxooxoxoox

Sample Output 3

SSWWSSSWWS


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

function main()
	n,m = readline() |> split |> parseMap
	if n*2>=m
		println(m>>1)
	else
		println(n+div(m-2n,4))
	end
end

main()

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

Score : 300 points

Problem Statement

Snuke loves puzzles.

Today, he is working on a puzzle using S- and c-shaped pieces.
In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below:

Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped pieces.

Find the maximum number of Scc groups that can be created when Snuke has N S-shaped pieces and M c-shaped pieces.

Constraints

1 ≤ N,M ≤ 10^{12}

Input

The input is given from Standard Input in the following format:

N M

Output

Print the answer.

Sample Input 1

1 6

Sample Output 1

2

Two Scc groups can be created as follows:

Combine two c-shaped pieces into one S-shaped piece

Create two Scc groups, each from one S-shaped piece and two c-shaped pieces

Sample Input 2

12345 678901

Sample Output 2

175897

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 = split(readline())
A,B=parse(Int,N[1]),parse(Int,N[2])
if A == 1;A = 14;end
if B == 1;B = 14;end
if A > B
    println("Alice")
elseif A < B
    println("Bob")
else
    println("Draw")
end

Score : 100 points

Problem Statement

Alice and Bob are playing One Card Poker.

One Card Poker is a two-player game using playing cards.

Each card in this game shows an integer between 1 and 13, inclusive.

The strength of a card is determined by the number written on it, as follows:

Weak 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 < 10 < 11 < 12 < 13 < 1 Strong

One Card Poker is played as follows:

Each player picks one card from the deck. The chosen card becomes the player's hand.

The players reveal their hands to each other. The player with the stronger card wins the game.

If their cards are equally strong, the game is drawn.

You are watching Alice and Bob playing the game, and can see their hands.

The number written on Alice's card is A, and the number written on Bob's card is B.

Write a program to determine the outcome of the game.

Constraints

1≦A≦13

1≦B≦13

A and B are integers.

Input

The input is given from Standard Input in the following format:

A B

Output

Print Alice if Alice will win. Print Bob if Bob will win. Print Draw if the game will be drawn.

Sample Input 1

8 6

Sample Output 1

Alice

8 is written on Alice's card, and 6 is written on Bob's card.
Alice has the stronger card, and thus the output should be Alice.

Sample Input 2

1 1

Sample Output 2

Draw

Since their cards have the same number, the game will be drawn.

Sample Input 3

13 1

Sample Output 3

Bob


function solve()
    N, M = parse.(Int, split(readline()))
    A = zeros(Int, N, N)
    B = zeros(Int, M, M)

    for i = 1:N
        s = readline()
        for j = 1:N
            if s[j] == '#' A[i, j] = 1 end
        end
    end

    for i = 1:M
        s = readline()
        for j = 1:M
            if s[j] == '#' B[i, j] = 1 end
        end
    end

    res = false

    for i = 1:N for j = 1:N
        if i + M > N || j + M > N continue end

        match = true
        for k = 1:M for l = 1:M
            if A[i+k, j+l] != B[k, l] match = false end
        end end

        if match res = true end
    end end

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

solve()

Score : 200 points

Problem Statement

You are given an image A composed of N rows and N columns of pixels, and a template image B composed of M rows and M columns of pixels.

A pixel is the smallest element of an image, and in this problem it is a square of size 1×1.

Also, the given images are binary images, and the color of each pixel is either white or black.

In the input, every pixel is represented by a character: . corresponds to a white pixel, and # corresponds to a black pixel.

The image A is given as N strings A_1,...,A_N.

The j-th character in the string A_i corresponds to the pixel at the i-th row and j-th column of the image A (1≦i,j≦N).

Similarly, the template image B is given as M strings B_1,...,B_M.

The j-th character in the string B_i corresponds to the pixel at the i-th row and j-th column of the template image B (1≦i,j≦M).

Determine whether the template image B is contained in the image A when only parallel shifts can be applied to the images.

Constraints

1≦M≦N≦50

A_i is a string of length N consisting of # and ..

B_i is a string of length M consisting of # and ..

Input

The input is given from Standard Input in the following format:

N M
A_1
A_2
:
A_N
B_1
B_2
:
B_M

Output

Print Yes if the template image B is contained in the image A. Print No otherwise.

Sample Input 1

3 2
#.#
.#.
#.#
#.
.#

Sample Output 1

Yes

The template image B is identical to the upper-left 2 × 2 subimage and the lower-right 2 × 2 subimage of A. Thus, the output should be Yes.

Sample Input 2

4 1
....
....
....
....
#

Sample Output 2

No

The template image B, composed of a black pixel, is not contained in the image A composed of white pixels.


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()
    x=parseInt(readline())
    if x<1200
        println("ABC")
    else
        println("ARC")
    end
end
main()

Score : 100 points

Problem Statement

Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.

You are given Smeke's current rating, x. Print ABC if Smeke will participate in ABC, and print ARC otherwise.

Constraints

1 ≦ x ≦ 3{,}000

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

1000

Sample Output 1

ABC

Smeke's current rating is less than 1200, thus the output should be ABC.

Sample Input 2

2000

Sample Output 2

ARC

Smeke's current rating is not less than 1200, thus the output should be ARC.


function main(x)

  if x < 1200
    println("ABC")
  else
    println("ARC")
  end

end

x = parse(Int, readline())

main(x)


function main()

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

  if A*B > C*D
    println(A*B)
  else
    println(C*D)
  end

end

main()

Score : 100 points

Problem Statement

There are two rectangles.
The lengths of the vertical sides of the first rectangle are A, and the lengths of the horizontal sides of the first rectangle are B.
The lengths of the vertical sides of the second rectangle are C, and the lengths of the horizontal sides of the second rectangle are D.

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Constraints

All input values are integers.

1≤A≤10^4

1≤B≤10^4

1≤C≤10^4

1≤D≤10^4

Input

The input is given from Standard Input in the following format:

A B C D

Output

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Sample Input 1

3 5 2 7

Sample Output 1

15

The first rectangle has an area of 3×5=15, and the second rectangle has an area of 2×7=14.
Thus, the output should be 15, the larger area.

Sample Input 2

100 600 200 300

Sample Output 2

60000


function main()
	n = parse(Int, readline())
	s = chomp(readline())
	a = Array{Int}(n)
    if s[1] == 'I'
    	a[1] = 1
    else
    	a[1] = -1
    end
	for i in 2:n
		if s[i] == 'I'
			a[i] = a[i-1] += 1
		else
			a[i] = a[i-1] -= 1
		end
	end
	println(max(maximum(a),0))
end

main()

Score : 200 points

Problem Statement

You have an integer variable x.
Initially, x=0.

Some person gave you a string S of length N, and using the string you performed the following operation N times.
In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D.

Find the maximum value taken by x during the operations (including before the first operation, and after the last operation).

Constraints

1≤N≤100

|S|=N

No characters except I and D occur in S.

Input

The input is given from Standard Input in the following format:

N
S

Output

Print the maximum value taken by x during the operations.

Sample Input 1

5
IIDID

Sample Output 1

2

After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.

Sample Input 2

7
DDIDDII

Sample Output 2

0

The initial value x=0 is the maximum value taken by x, thus the output should be 0.


readline()
s=readline()
a=0
t=0
for i=1:length(s)
	if s[i]=='I'
		t+=1
	else
		t-=1
	end
	a=max(a,t)
end
print(a)


n,a,b=map(x->parse(Int,x),split(readline()))
A=map(x->parse(Int,x),split(readline()))
ans=0
for i=2:n
	ans+=min(a*(A[i]-A[i-1]),b)
end
println(ans)

Score : 500 points

Problem Statement

There are N towns on a line running east-west.
The towns are numbered 1 through N, in order from west to east.
Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value.
The coordinate of town i is X_i.

You are now at town 1, and you want to visit all the other towns.
You have two ways to travel:

Walk on the line.
Your fatigue level increases by A each time you travel a distance of 1, regardless of direction.

Teleport to any location of your choice.
Your fatigue level increases by B, regardless of the distance covered.

Find the minimum possible total increase of your fatigue level when you visit all the towns in these two ways.

Constraints

All input values are integers.

2≤N≤10^5

1≤X_i≤10^9

For all i(1≤i≤N-1), X_i<X_{i+1}.

1≤A≤10^9

1≤B≤10^9

Input

The input is given from Standard Input in the following format:

N A B
X_1 X_2 ... X_N

Output

Print the minimum possible total increase of your fatigue level when you visit all the towns.

Sample Input 1

4 2 5
1 2 5 7

Sample Output 1

11

From town 1, walk a distance of 1 to town 2, then teleport to town 3, then walk a distance of 2 to town 4.
The total increase of your fatigue level in this case is 2×1+5+2×2=11, which is the minimum possible value.

Sample Input 2

7 1 100
40 43 45 105 108 115 124

Sample Output 2

84

From town 1, walk all the way to town 7.
The total increase of your fatigue level in this case is 84, which is the minimum possible value.

Sample Input 3

7 1 2
24 35 40 68 72 99 103

Sample Output 3

12

Visit all the towns in any order by teleporting six times.
The total increase of your fatigue level in this case is 12, which is the minimum possible value.


s = readline()
arr = split(s)
println(arr[1]+" "+arr[2]+" "+arr[3])

Score : 100 points

Problem Statement

As a New Year's gift, Dolphin received a string s of length 19.

The string s has the following format: [five lowercase English letters],[seven lowercase English letters],[five lowercase English letters].

Dolphin wants to convert the comma-separated string s into a space-separated string.

Write a program to perform the conversion for him.

Constraints

The length of s is 19.

The sixth and fourteenth characters in s are ,.

The other characters in s are lowercase English letters.

Input

The input is given from Standard Input in the following format:

s

Output

Print the string after the conversion.

Sample Input 1

happy,newyear,enjoy

Sample Output 1

happy newyear enjoy

Replace all the commas in happy,newyear,enjoy with spaces to obtain happy newyear enjoy.

Sample Input 2

haiku,atcoder,tasks

Sample Output 2

haiku atcoder tasks

Sample Input 3

abcde,fghihgf,edcba

Sample Output 3

abcde fghihgf edcba


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

function main()
	n,m = readline() |> split |> parseMap
	g = zeros(Int,n,n)
	d = 10000000*ones(Int,n,n)
	for i in 1:n
		d[i,i] = 0
	end
	x = 0
	for i in 1:m
		a,b,c = readline() |> split |> parseMap
		g[a,b] = c
		g[b,a] = c
		d[a,b] = c
		d[b,a] = c
	end
	for k in 1:n
		for i in 1:n
			for j in 1:n
				d[i,j] = min(d[i,j],d[i,k]+d[k,j])
			end
		end
	end
	for i in 1:n-1
		for j in i+1:n
			if g[i,j] > 0
				f = 0
				for s in 1:n
					if d[s,i] + g[i,j] == d[s,j]
						f = 1
						break
					end
				end
				if f == 0
					x += 1
				end
			end
		end
	end
	println(x)
end

main()

Score : 400 points

Problem Statement

You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.

The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

A connected graph is a graph where there is a path between every pair of different vertices.

Find the number of the edges that are not contained in any shortest path between any pair of different vertices.

Constraints

2≤N≤100

N-1≤M≤min(N(N-1)/2,1000)

1≤a_i,b_i≤N

1≤c_i≤1000

c_i is an integer.

The given graph contains neither self-loops nor double edges.

The given graph is connected.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M

Output

Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.

Sample Input 1

3 3
1 2 1
1 3 1
2 3 3

Sample Output 1

1

In the given graph, the shortest paths between all pairs of different vertices are as follows:

The shortest path from vertex 1 to vertex 2 is: vertex 1 → vertex 2, with the length of 1.

The shortest path from vertex 1 to vertex 3 is: vertex 1 → vertex 3, with the length of 1.

The shortest path from vertex 2 to vertex 1 is: vertex 2 → vertex 1, with the length of 1.

The shortest path from vertex 2 to vertex 3 is: vertex 2 → vertex 1 → vertex 3, with the length of 2.

The shortest path from vertex 3 to vertex 1 is: vertex 3 → vertex 1, with the length of 1.

The shortest path from vertex 3 to vertex 2 is: vertex 3 → vertex 1 → vertex 2, with the length of 2.

Thus, the only edge that is not contained in any shortest path, is the edge of length 3 connecting vertex 2 and vertex 3, hence the output should be 1.

Sample Input 2

3 2
1 2 1
2 3 1

Sample Output 2

0

Every edge is contained in some shortest path between some pair of different vertices.


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

function main()
	x,y = readline() |> split |> parseMap
	if 0<=x<=y||x<=y<=0
		println(y-x)
	elseif 0<=y<=x||y<=x<=0
		println(min(x-y+2,x+y))
	else
		println(abs(x+y)+1)
	end
end

main()

Score : 300 points

Problem Statement

Snuke has a calculator. It has a display and two buttons.

Initially, the display shows an integer x.
Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:

Button A: When pressed, the value on the display is incremented by 1.

Button B: When pressed, the sign of the value on the display is reversed.

Find the minimum number of times Snuke needs to press the buttons to achieve his objective.
It can be shown that the objective is always achievable regardless of the values of the integers x and y.

Constraints

x and y are integers.

|x|, |y| ≤ 10^9

x and y are different.

Input

The input is given from Standard Input in the following format:

x y

Output

Print the minimum number of times Snuke needs to press the buttons to achieve his objective.

Sample Input 1

10 20

Sample Output 1

10

Press button A ten times.

Sample Input 2

10 -10

Sample Output 2

1

Press button B once.

Sample Input 3

-10 -20

Sample Output 3

12

Press the buttons as follows:

Press button B once.

Press button A ten times.

Press button B once.


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

function main()
	x,y = readline() |> split |> parseMap
	if 0<x<y||x<y<0
		println(y-x)
	elseif 0<y<x||y<x<0
		println(x-y+2)
	else
		println(abs(x+y)+1)
	end
end

main()


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

function main()
	x,y = readline() |> split |> parseMap
	if x*y<0
		println(abs(x+y)+1)
	elseif x<=y
		println(y-x)
	elseif y == 0 || x == 0
		println(x-y+1)
	else
		println(x-y+2)
	end
end

main()


str = split(readline())
a = parse(Int, str[1])
b = parse(Int, str[3])
println(str[2]=="+" ? (a+b) : (a-b))

Score : 100 points

Problem Statement

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

The input is given from Standard Input in the following format:

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


parseInt(x) = parse(Int,x)

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

function main()
    A, op , B = readline() |> split
    A = parseInt(A)
    B = parseInt(B)

    if op=="+":
        println(A+B)
    else
        println(A-B)
    end
end

main()


function f()
    input = split(chomp(readline()), " ")
    A = parse(Int, input[1])
    op = input[2]
    B = parse(Int, input[3])

    if op == "+"
        ret = A + B
    else
        ret = A - B
    end

    print(ret)
end
f()


parseInt(x) = parse(Int, x)

function main()
	n = parseInt(readline())
	a = map(parseInt, split(readline()))
	d = zeros(Int, n)
	for i in 1:n
		d[a[i]+1] += 1
	end
	flg = 0
	if n%2 == 0
		for i in 1:n
			if i%2 == 0 && d[i] != 2
				flg = 1
			elseif i%2 == 1 && d[i] != 0
				flg = 1
			end
		end
	else
		d[1] += 1
		for i in 1:n
			if i%2 == 0 && d[i] != 0
				flg = 1
			elseif i%2 == 1 && d[i] != 2
				flg = 1
			end
		end
	end

	if flg == 1
		print(0)
	else
		print((2^(div(n,2))%1000000007))
	end
end

main()

Score : 300 points

Problem Statement

There are N people, conveniently numbered 1 through N.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person i is A_i.

Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo 10^9+7.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print 0.

Constraints

1≦N≦10^5

0≦A_i≦N-1

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the number of the possible orders in which they were standing, modulo 10^9+7.

Sample Input 1

5
2 4 4 0 2

Sample Output 1

4

There are four possible orders, as follows:

2,1,4,5,3

2,5,4,1,3

3,1,4,5,2

3,5,4,1,2

Sample Input 2

7
6 4 0 2 4 0 2

Sample Output 2

0

Any order would be inconsistent with the reports, thus the answer is 0.

Sample Input 3

8
7 5 1 1 7 3 5 3

Sample Output 3

16


c=readline()
if c[1] == 'a' || c[1] == 'i' || c[1] == 'u' || c[1] == 'e' || c[1] == 'o'
  println("vowel")
else
  println("constant")
end

Score : 100 points

Problem Statement

Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: a, e, i, o and u.

Constraints

c is a lowercase English letter.

Input

The input is given from Standard Input in the following format:

c

Output

If c is a vowel, print vowel. Otherwise, print consonant.

Sample Input 1

a

Sample Output 1

vowel

Since a is a vowel, print vowel.

Sample Input 2

z

Sample Output 2

consonant

Sample Input 3

s

Sample Output 3

consonant


N = split(readline())
H,W = parse(Int,N[1]),parse(Int,N[2])
list = []
for i in 1:H
    S = chomp(readline())
    list = push!(list,S)
    list = push!(list,S)
end
for i in 1:2H
    println(list[i])
end


lines=readlines()
function find(u,p)
	if u==p[u]
		u
	else
		p[u]=find(p[u],p)
	end
end
function f(N,S)
	parent=collect(1:N)
	size=ones(Int,N)
	for s=S
		a,b=map(x->find(parse(Int,x),parent),split(s))
		if a!=b
			if size[a]>size[b]
				parent[b]=a
				size[a]+=size[b]
			else
				parent[a]=b
				size[b]+=size[a]
			end
		end
	end
	[find(i,parent) for i=1:N]
end
function main()
	N,K,L=map(x->parse(Int,x),split(lines[1]))
	E=Pair{Int,Int}[]
  for (a,b)=zip(f(N,lines[2:K+1]),f(N,lines[K+2:end]))
		push!(E,a=>b)
	end
	D=Dict{Pair{Int,Int},Int}()
	for v=E
		D[v]=get(D,v,0)+1
	end
	for v=E
		println(D[v])
	end
end
main()

Score : 400 points

Problem Statement

There are N cities. There are also K roads and L railways, extending between the cities.
The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities.
No two roads connect the same pair of cities. Similarly, no two railways connect the same pair of cities.

We will say city A and B are connected by roads if city B is reachable from city A by traversing some number of roads. Here, any city is considered to be connected to itself by roads.
We will also define connectivity by railways similarly.

For each city, find the number of the cities connected to that city by both roads and railways.

Constraints

2 ≦ N ≦ 2*10^5

1 ≦ K, L≦ 10^5

1 ≦ p_i, q_i, r_i, s_i ≦ N

p_i < q_i

r_i < s_i

When i ≠ j, (p_i, q_i) ≠ (p_j, q_j)

When i ≠ j, (r_i, s_i) ≠ (r_j, s_j)

Input

The input is given from Standard Input in the following format:

N K L
p_1 q_1
:
p_K q_K
r_1 s_1
:
r_L s_L

Output

Print N integers. The i-th of them should represent the number of the cities connected to the i-th city by both roads and railways.

Sample Input 1

4 3 1
1 2
2 3
3 4
2 3

Sample Output 1

1 2 2 1

All the four cities are connected to each other by roads.

By railways, only the second and third cities are connected. Thus, the answers for the cities are 1, 2, 2 and 1, respectively.

Sample Input 2

4 2 2
1 2
2 3
1 4
2 3

Sample Output 2

1 2 2 1

Sample Input 3

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

Sample Output 3

1 1 2 1 2 2 2


lines=readlines()
function find(u,p)
	if u==p[u]
		u
	else
		p[u]=find(p[u],p)
	end
end
function f(N,S)
	parent=collect(1:N)
	size=ones(Int,N)
	for s=S
		a,b=map(x->find(parse(Int,x),parent),split(s))
		if a!=b
			if size[a]>size[b]
				parent[b]=a
				size[a]+=size[b]
			else
				parent[a]=b
				size[b]+=size[a]
			end
		end
	end
	parent
end
function main()
	N,K,L=map(x->parse(Int,x),split(lines[1]))
	E=Pair{Int,Int}[]
	for (a,b)=zip(f(N,lines[2:K+1]),f(N,lines[K+2:end]))
		push!(E,a=>b)
	end
	D=Dict{Pair{Int,Int},Int}()
	for v=E
		D[v]=get(D,v,0)+1
	end
	for v=E
		println(D[v])
	end
end
main()


function find(u,p)
	if u==p[u]
		u
	else
		p[u]=find(p[u],p)
	end
end
function f(N,M)
	parent=collect(1:N)
	size=ones(Int,N)
	for _=1:M
		a,b=map(x->find(parse(Int,x),parent),split(readline()))
		if a!=b
			if size[a]>size[b]
				parent[b]=a
				size[a]+=size[b]
			else
				parent[a]=b
				size[b]+=size[a]
			end
		end
	end
	parent
end
function main()
	N,K,L=map(x->parse(Int,x),split(readline()))
	E=Pair{Int,Int}[]
	for (a,b)=zip(f(N,K),f(N,L))
		push!(E,a=>b)
	end
	D=Dict{Pair{Int,Int},Int}()
	for v=E
		D[v]=get(D,v,0)+1
	end
	for v=E
		println(D[v])
	end
end
main()


Score : 100 points

Problem Statement

Snuke is going to open a contest named "AtCoder s Contest".
Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.

Snuke has decided to abbreviate the name of the contest as "AxC".
Here, x is the uppercase English letter at the beginning of s.

Given the name of the contest, print the abbreviation of the name.

Constraints

The length of s is between 1 and 100, inclusive.

The first character in s is an uppercase English letter.

The second and subsequent characters in s are lowercase English letters.

Input

The input is given from Standard Input in the following format:

AtCoder s Contest

Output

Print the abbreviation of the name of the contest.

Sample Input 1

AtCoder Beginner Contest

Sample Output 1

ABC

The contest in which you are participating now.

Sample Input 2

AtCoder Snuke Contest

Sample Output 2

ASC

This contest does not actually exist.

Sample Input 3

AtCoder X Contest

Sample Output 3

AXC


function main()
    a,b,c = readline() |> split
    println(string("A",b[1],"C"))
end

main()


function main()
    a, b, x = parse.(Int, split(readline()))
    s = a÷x*x + x
    if s >= b
        println(0)
        return
    end
    ans = (b - s)÷x + 1
    println(ans)
end

main()

Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

The input is given from Standard Input in the following format:

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


(a, b, x) = parse.([Int128], split(readline(STDIN)))
println(div(b, x) - div(a - 1, x))


parseInt(x) = parse(Int, x)

function main()
	n,x = map(parseInt, split(readline()))
	a = map(parseInt, split(readline()))
	k = 0
	if a[1] > x
		k += a[1]-x
		a[1] = x
	end
	for i in 2:2:n-1
		if a[i-1] + a[i] > x
			if a[i-1] > x
				k += a[i-1] + a[i] - x
				a[i] = 0
				a[i-1] = a[i-1] + a[i] - x
			else
				k += a[i-1] + a[i] - x
				a[i] = x - a[i-1]
			end
		end
	end
	if a[n-1] + a[n] > x
		k += a[n-1] + a[n] - x
	end
	print(k)
end

main()

Score : 300 points

Problem Statement

There are N boxes arranged in a row.
Initially, the i-th box from the left contains a_i candies.

Snuke can perform the following operation any number of times:

Choose a box containing at least one candy, and eat one of the candies in the chosen box.

His objective is as follows:

Any two neighboring boxes contain at most x candies in total.

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

Constraints

2 ≤ N ≤ 10^5

0 ≤ a_i ≤ 10^9

0 ≤ x ≤ 10^9

Input

The input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the minimum number of operations required to achieve the objective.

Sample Input 1

3 3
2 2 2

Sample Output 1

1

Eat one candy in the second box.
Then, the number of candies in each box becomes (2, 1, 2).

Sample Input 2

6 1
1 6 1 2 0 4

Sample Output 2

11

For example, eat six candies in the second box, two in the fourth box, and three in the sixth box.
Then, the number of candies in each box becomes (1, 0, 1, 0, 0, 1).

Sample Input 3

5 9
3 1 4 1 5

Sample Output 3

0

The objective is already achieved without performing operations.

Sample Input 4

2 0
5 5

Sample Output 4

10

All the candies need to be eaten.


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

function main()
	s = readline() |> chomp
	n = length(s)
	d = Dict{Char,Array{Int,1}}()
	for i in 1:n
		if haskey(d,s[i])
			push!(d[s[i]],i)
		else
			d[s[i]] = Int[i]
		end
	end
	mx = n-1
	for i in keys(d)
		for j in 2:length(d[i])
			mx = min(mx,d[i][j]-d[i][j-1]-1)
		end
	end
	println(mx%2==0?"First":"Second")
end

main()

Score : 500 points

Problem Statement

There is a string s of length 3 or greater.
No two neighboring characters in s are equal.

Takahashi and Aoki will play a game against each other.
The two players alternately performs the following operation, Takahashi going first:

Remove one of the characters in s, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in s.

The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally.

Constraints

3 ≤ |s| ≤ 10^5

s consists of lowercase English letters.

No two neighboring characters in s are equal.

Input

The input is given from Standard Input in the following format:

s

Output

If Takahashi will win, print First. If Aoki will win, print Second.

Sample Input 1

aba

Sample Output 1

Second

Takahashi, who goes first, cannot perform the operation, since removal of the b, which is the only character not at either ends of s, would result in s becoming aa, with two as neighboring.

Sample Input 2

abc

Sample Output 2

First

When Takahashi removes b from s, it becomes ac.
Then, Aoki cannot perform the operation, since there is no character in s, excluding both ends.

Sample Input 3

abcab

Sample Output 3

First


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

function eval(a::Tuple{Int,Float64},b::Tuple{Int,Float64})
	if a[2]<b[2]
		1
	elseif a[2]==b[2]
		0
	else
		-1
	end
end

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

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

dist(xa::Int,ya::Int,xb::Int,yb::Int,ra::Int,rb::Int)=sqrt((xa-xb)^2+(ya-yb)^2)-ra-rb

function main()
	xs,ys,xt,yt = readline() |> split |> parseMap
	n = readline() |> parseInt
	a = Tuple{Int,Int,Int}[(0,0,0) for i in 1:n]
	for i in 1:n
		x,y,r = readline() |> split |> parseMap
		a[i] = (x,y,r)
	end
	e = [Tuple{Int,Float64}[] for i in 1:n+2]
	for i in 1:n
		for j in i+1:n
			v = dist(a[i][1],a[i][2],a[j][1],a[j][2],a[i][3],a[j][3])
			push!(e[i], (j,max(0,v)))
			push!(e[j], (i,max(0,v)))
		end
		v = dist(a[i][1],a[i][2],xs,ys,a[i][3],0)
		push!(e[i],(n+1,max(0,v)))
		push!(e[n+1],(i,max(0,v)))
		v = dist(a[i][1],a[i][2],xt,yt,a[i][3],0)
		push!(e[i],(n+2,max(0,v)))
		push!(e[n+2],(i,max(0,v)))
	end
	v = dist(xs,ys,xt,yt,0,0)
	push!(e[n+1],(n+2,max(0,v)))
	push!(e[n+2],(n+1,max(0,v)))

	hs = Tuple{Int,Float64}[(n+1,0.0)]
	hg = Tuple{Int,Float64}[(n+2,0.0)]
	ds = -ones(Float64,n+2)
	dg = -ones(Float64,n+2)
	vss = zeros(Int,n+2)
	vsg = zeros(Int,n+2)
	ds[n+1] = 0.0
	dg[n+2] = 0.0
	while !isempty(hs)||!isempty(hg)
		v,w = hpop(hs)
		ds[v] = ds[v]==-1.0?w:min(ds[v],w)
		vss[v] = 1
		if vss[v]+vsg[v] > 1
			break
		end
		for i in 1:length(e[v])
			if ds[e[v][i][1]]<0.0 || ds[e[v][i][1]]>w+e[v][i][2]
				ds[e[v][i][1]] = w+e[v][i][2]
				hpush(hs,(e[v][i][1],w+e[v][i][2]))
			end
		end
		vv,ww = hpop(hg)
		dg[vv] = dg[vv]==-1.0?ww:min(dg[vv],ww)
		vsg[vv] = 1
		if vss[vv]+vsg[vv] > 1
			break
		end
		for i in 1:length(e[vv])
			if dg[e[vv][i][1]]<0.0 || dg[e[vv][i][1]]>ww+e[vv][i][2]
				dg[e[vv][i][1]] = ww+e[vv][i][2]
				hpush(hg,(e[vv][i][1],ww+e[vv][i][2]))
			end
		end
	end
	minim = ds[1]+dg[1]
	for i in 2:n+2
		if ds[i]>-1.0 && dg[i]>-1.0
			minim = min(minim,ds[i]+dg[i])
		end
	end
	println(minim)
end

main()

Score : 600 points

Problem Statement

On the xy-plane, Snuke is going to travel from the point (x_s, y_s) to the point (x_t, y_t).
He can move in arbitrary directions with speed 1.
Here, we will consider him as a point without size.

There are N circular barriers deployed on the plane.
The center and the radius of the i-th barrier are (x_i, y_i) and r_i, respectively.
The barriers may overlap or contain each other.

A point on the plane is exposed to cosmic rays if the point is not within any of the barriers.

Snuke wants to avoid exposure to cosmic rays as much as possible during the travel.
Find the minimum possible duration of time he is exposed to cosmic rays during the travel.

Constraints

All input values are integers.

-10^9 ≤ x_s, y_s, x_t, y_t ≤ 10^9

(x_s, y_s) ≠ (x_t, y_t)

1≤N≤1,000

-10^9 ≤ x_i, y_i ≤ 10^9

1 ≤ r_i ≤ 10^9

Input

The input is given from Standard Input in the following format:

x_s y_s x_t y_t
N
x_1 y_1 r_1
x_2 y_2 r_2
:
x_N y_N r_N

Output

Print the minimum possible duration of time Snuke is exposed to cosmic rays during the travel.
The output is considered correct if the absolute or relative error is at most 10^{-9}.

Sample Input 1

-2 -2 2 2
1
0 0 1

Sample Output 1

3.6568542495

An optimal route is as follows:

Sample Input 2

-2 0 2 0
2
-1 0 2
1 0 2

Sample Output 2

0.0000000000

An optimal route is as follows:

Sample Input 3

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

Sample Output 3

4.0000000000

An optimal route is as follows:


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

function eval(a::Tuple{Int,Float64},b::Tuple{Int,Float64})
	if a[2]<b[2]
		1
	elseif a[2]==b[2]
		0
	else
		-1
	end
end

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

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

dist(xa::Int,ya::Int,xb::Int,yb::Int,ra::Int,rb::Int)=sqrt((xa-xb)^2+(ya-yb)^2)-ra-rb

function main()
	xs,ys,xt,yt = readline() |> split |> parseMap
	n = readline() |> parseInt
	a = Tuple{Int,Int,Int}[(0,0,0) for i in 1:n]
	for i in 1:n
		x,y,r = readline() |> split |> parseMap
		a[i] = (x,y,r)
	end
	e = [Tuple{Int,Float64}[] for i in 1:n+2]
	for i in 1:n
		for j in i+1:n
			v = dist(a[i][1],a[i][2],a[j][1],a[j][2],a[i][3],a[j][3])
			push!(e[i], (j,max(0,v)))
			push!(e[j], (i,max(0,v)))
		end
		v = dist(a[i][1],a[i][2],xs,ys,a[i][3],0)
		push!(e[i],(n+1,max(0,v)))
		push!(e[n+1],(i,max(0,v)))
		v = dist(a[i][1],a[i][2],xt,yt,a[i][3],0)
		push!(e[i],(n+2,max(0,v)))
		push!(e[n+2],(i,max(0,v)))
	end
	h = Tuple{Int,Float64}[(n+1,0.0)]
	dis = -ones(Float64,n+2)
	while !isempty(h)
		v,w = hpop(h)
		dis[v] = dis[v]<0.0?w:min(dis[v],w)
		for i in 1:length(e[v])
			if dis[e[v][i][1]]<0.0 || dis[e[v][i][1]]>w+e[v][i][2]
				dis[e[v][i][1]] = w+e[v][i][2]
				hpush(h,(e[v][i][1],w+e[v][i][2]))
			end
		end
	end
	println(dis[n+2])
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()
    h,w=parseMap(split(readline()))
    for i in 1:h
        s=split(readline())
        for j in 1:w
            if s[j]=="snuke"
                println(join(['A'+j-1,string(i)]))
                break
            end
        end
    end
end
main()

Score : 100 points

Problem Statement

There is a grid with H rows and W columns.

The square at the i-th row and j-th column contains a string S_{i,j} of length 5.

The rows are labeled with the numbers from 1 through H, and the columns are labeled with the uppercase English letters from A through the W-th letter of the alphabet.

Exactly one of the squares in the grid contains the string snuke. Find this square and report its location.

For example, the square at the 6-th row and 8-th column should be reported as H6.

Constraints

1≦H, W≦26

The length of S_{i,j} is 5.

S_{i,j} consists of lowercase English letters (a-z).

Exactly one of the given strings is equal to snuke.

Input

The input is given from Standard Input in the following format:

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

Output

Print the labels of the row and the column of the square containing the string snuke, with no space inbetween.

Sample Input 1

15 10
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snuke snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake

Sample Output 1

H6

Sample Input 2

1 1
snuke

Sample Output 2

A1


function main()

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

  S = ["" for i in 1:H, j in 1:W]

  for i in 1:H
    S[i,:] = split(chomp(readline())," ")
  end

  for i in 1:H, j in 1:W

    if S[i,j] == "snuke"
      println('A'+j-1,i)
      break
    end

  end

end

main()


N=parse(Int,readline())
p=map(x->parse(Int,x),split(readline()))
q=zeros(Int,N)
for i=1:N
	println((N+1)*i)
	q[p[i]]=i
end
for i=1:N
	println((N+1)*(N-i)+q[i])
end

Score : 400 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

You are given a permutation p of the set {1, 2, ..., N}. Please construct two sequences of positive integers a_1, a_2, ..., a_N and b_1, b_2, ..., b_N satisfying the following conditions:

1 \leq a_i, b_i \leq 10^9 for all i

a_1 < a_2 < ... < a_N

b_1 > b_2 > ... > b_N

a_{p_1}+b_{p_1} < a_{p_2}+b_{p_2} < ... < a_{p_N}+b_{p_N}

Constraints

2 \leq N \leq 20,000

p is a permutation of the set {1, 2, ..., N}

Input

The input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

The output consists of two lines. The first line contains a_1, a_2, ..., a_N seperated by a space. The second line contains b_1, b_2, ..., b_N seperated by a space.

It can be shown that there always exists a solution for any input satisfying the constraints.

Sample Input 1

2
1 2

Sample Output 1

1 4
5 4

a_1 + b_1 = 6 and a_2 + b_2 = 8. So this output satisfies all conditions.

Sample Input 2

3
3 2 1

Sample Output 2

1 2 3
5 3 1

Sample Input 3

3
2 3 1

Sample Output 3

5 10 100
100 10 1


W,H,N=map(int,input().split())
# Wはx軸、Hはy軸
x_s=0
x_g=W
y_s=0
y_g=H

for i in range(N):
  x,y,a=map(int,input().split())
  # aが1ならxの始点がxiになる
  # aが2ならxの終点がxiになる
  # aが3ならyの始点がyiになる
  # aが4ならyの始点がyiになる
  if a==1:
    if x_s<x:x_s=x
  elif a==2:
    if x_g>x:x_g=x
  elif a==3:
    if y_s<y:y_s=y
  else:
    if y_g>y:y_g=y
print((x_g-x_s)*(y_g-y_s))

Score : 200 points

Problem Statement

There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.

Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) point was (x_i, y_i).

Then, he created an integer sequence a of length N, and for each 1 ≦ i ≦ N, he painted some region within the rectangle black, as follows:

If a_i = 1, he painted the region satisfying x < x_i within the rectangle.

If a_i = 2, he painted the region satisfying x > x_i within the rectangle.

If a_i = 3, he painted the region satisfying y < y_i within the rectangle.

If a_i = 4, he painted the region satisfying y > y_i within the rectangle.

Find the area of the white region within the rectangle after he finished painting.

Constraints

1 ≦ W, H ≦ 100

1 ≦ N ≦ 100

0 ≦ x_i ≦ W (1 ≦ i ≦ N)

0 ≦ y_i ≦ H (1 ≦ i ≦ N)

W, H (21:32, added), x_i and y_i are integers.

a_i (1 ≦ i ≦ N) is 1, 2, 3 or 4.

Input

The input is given from Standard Input in the following format:

W H N
x_1 y_1 a_1
x_2 y_2 a_2
:
x_N y_N a_N

Output

Print the area of the white region within the rectangle after Snuke finished painting.

Sample Input 1

5 4 2
2 1 1
3 3 4

Sample Output 1

9

The figure below shows the rectangle before Snuke starts painting.

First, as (x_1, y_1) = (2, 1) and a_1 = 1, he paints the region satisfying x < 2 within the rectangle:

Then, as (x_2, y_2) = (3, 3) and a_2 = 4, he paints the region satisfying y > 3 within the rectangle:

Now, the area of the white region within the rectangle is 9.

Sample Input 2

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

Sample Output 2

0

It is possible that the whole region within the rectangle is painted black.

Sample Input 3

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

Sample Output 3

64


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

function main()
	w,h,n = readline() |> split |> parseMap
	lx = 0
	rx = w
	ly = 0
	ry = h
	for i in 1:n
		x,y,a = readline() |> split |> parseMap
		if a==1
			lx = max(lx,x)
		elseif a==2
			rx = min(rx,x)
		elseif a==3
			ly = max(ly,y)
		else
			ly = min(ry,y)
		end
	end
	println(max((rx-lx)*(ry-ly),0))
end

main()


X,Y,n=map(x->parse(Int,x),split(readline()))
x=y=0
for i=1:n
	a,b,c=map(x->parse(Int,x),split(readline()))
	if c==1&&x<a
		x=a
	elseif c==2&&X>a
		X=a
	elseif c==3&&y<b
		y=b
	elseif c==4&&Y>b
		Y=b
	end
end
print(max(X-x,0)*max(Y-y,0))


function main()

  S = chomp(readline())

  check1 = false
  check2 = false

  for i in S
    if i == 'C'
      check1 = true
    elseif check1 && i == 'F'
      check2 = true
    end
  end

  if check1 && check2
    println("Yes")
  else
    println("No")
  end

end

main()

Score : 100 points

Problem Statement

This contest is CODEFESTIVAL, which can be shortened to the string CF by deleting some characters.

Mr. Takahashi, full of curiosity, wondered if he could obtain CF from other strings in the same way.

You are given a string s consisting of uppercase English letters.
Determine whether the string CF can be obtained from the string s by deleting some characters.

Constraints

2 ≤ |s| ≤ 100

All characters in s are uppercase English letters (A-Z).

Input

The input is given from Standard Input in the following format:

s

Output

Print Yes if the string CF can be obtained from the string s by deleting some characters.
Otherwise print No.

Sample Input 1

CODEFESTIVAL

Sample Output 1

Yes

CF is obtained by deleting characters other than the first character C and the fifth character F.

Sample Input 2

FESTIVALCODE

Sample Output 2

No

FC can be obtained but CF cannot be obtained because you cannot change the order of the characters.

Sample Input 3

CF

Sample Output 3

Yes

It is also possible not to delete any characters.

Sample Input 4

FCF

Sample Output 4

Yes

CF is obtained by deleting the first character.


(K,T)=map(parse,split(readline()))
a=zeros(Int64,T)
a=map(parse,split(readline()))
answer=0
let
(maxa,maxind)=findmax(a)
if maxa-1>K-maxa
    answer=maxa*2-K-1
end
end
println(answer)

Score : 200 points

Problem Statement

There are K pieces of cakes.
Mr. Takahashi would like to eat one cake per day, taking K days to eat them all.

There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i.

Eating the same type of cake two days in a row would be no fun,
so Mr. Takahashi would like to decide the order for eating cakes that minimizes the number of days on which he has to eat the same type of cake as the day before.

Compute the minimum number of days on which the same type of cake as the previous day will be eaten.

Constraints

1 ≤ K ≤ 10000

1 ≤ T ≤ 100

1 ≤ a_i ≤ 100

a_1 + a_2 + ... + a_T = K

Input

The input is given from Standard Input in the following format:

K T
a_1 a_2 ... a_T

Output

Print the minimum number of days on which the same type of cake as the previous day will be eaten.

Sample Input 1

7 3
3 2 2

Sample Output 1

0

For example, if Mr. Takahashi eats cakes in the order of 2, 1, 2, 3, 1, 3, 1, he can avoid eating the same type of cake as the previous day.

Sample Input 2

6 3
1 4 1

Sample Output 2

1

There are 6 cakes.
For example, if Mr. Takahashi eats cakes in the order of 2, 3, 2, 2, 1, 2, he has to eat the same type of cake (i.e., type 2) as the previous day only on the fourth day.
Since this is the minimum number, the answer is 1.

Sample Input 3

100 1
100

Sample Output 3

99

Since Mr. Takahashi has only one type of cake, he has no choice but to eat the same type of cake as the previous day from the second day and after.


function update(dp,i,k)
  for j=1:k,l=1:k
    if j==l;continue;end
    dp[i,j]+=dp[i-1,l]
  end
  true
end
function main()
  n,k=parse.(split(readline()))
  dp=zeros(Int,n,k)
  for j=1:k;dp[1,j]=1;end
  for i=2:n
    update(dp,i,k)
  end
  print(sum(dp[n,:]))
end
main()

Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

The input is given from Standard Input in the following format:

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


S = readline(STDIN)
T = "CODEFESTIVAL2016"

res = 0
for i in 1:16
    if S[i] != T[i]
        res += 1
    end
end

print(res)

Score : 100 points

Problem Statement

CODE FESTIVAL 2016 is going to be held. For the occasion, Mr. Takahashi decided to make a signboard.

He intended to write CODEFESTIVAL2016 on it, but he mistakenly wrote a different string S. Fortunately, the string he wrote was the correct length.

So Mr. Takahashi decided to perform an operation that replaces a certain character with another in the minimum number of iterations, changing the string to CODEFESTIVAL2016.

Find the minimum number of iterations for the rewrite operation.

Constraints

S is 16 characters long.

S consists of uppercase and lowercase alphabet letters and numerals.

Input

Inputs are provided from Standard Input in the following form.

S

Output

Output an integer representing the minimum number of iterations needed for the rewrite operation.

Sample Input 1

C0DEFESTIVAL2O16

Sample Output 1

2

The second character 0 must be changed to O and the 14th character O changed to 0.

Sample Input 2

FESTIVAL2016CODE

Sample Output 2

16


if isfile("mystdin.txt");mystdin=open("mystdin.txt","r");redirect_stdin(mystdin);end
pI(x)=parse(Int,x)
pM(x::Array{SubString{String},1})=map(pI,x)
function main()
  n,a,b=pM(split(readline()))
  s=chomp(readline())
  tuuka=0
  kaigai=0
  for i in s
    if i=='a' && tuuka<a+b
      println("Yes")
      tuuka+=1
    elseif i=='b' && tuuka<a+b && kaigai<b
      println("Yes")
      tuuka+=1
      kaigai+=1
    else
      println("No")
    end
  end
end
main()
if isdefined(Base, :mystdin);close(mystdin);end

Score : 200 points

Problem Statement

There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these.

Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from the top rank down. Participants who are not students cannot pass the Qualification contests.

A Japanese student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B.

An overseas student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B and the student ranks B-th or above among all overseas students.

A string S is assigned indicating attributes of all participants. If the i-th character of string S is a, this means the participant ranked i-th in the Qualification contests is a Japanese student; b means the participant ranked i-th is an overseas student; and c means the participant ranked i-th is neither of these.

Write a program that outputs for all the participants in descending rank either Yes if they passed the Qualification contests or No if they did not pass.

Constraints

1≦N,A,B≦100000

A+B≦N

S is N characters long.

S consists only of the letters a, b and c.

Input

Inputs are provided from Standard Input in the following form.

N A B
S

Output

Output N lines. On the i-th line, output Yes if the i-th participant passed the Qualification contests or No if that participant did not pass.

Sample Input 1

10 2 3
abccabaabb

Sample Output 1

Yes
Yes
No
No
Yes
Yes
Yes
No
No
No

The first, second, fifth, sixth, and seventh participants pass the Qualification contests.

Sample Input 2

12 5 2
cabbabaacaba

Sample Output 2

No
Yes
Yes
Yes
Yes
No
Yes
Yes
No
Yes
No
No

The sixth participant is third among overseas students and thus does not pass the Qualification contests.

Sample Input 3

5 2 2
ccccc

Sample Output 3

No
No
No
No
No


N,A,B=map(x->parse(Int,x),split(readline()))
K=T=0
for c=chomp(readline())
  flag=0
  if c=='a'
    if K<A+B
      flag=1
    end
  elseif c=='b'
    if T<B
      T+=1
      flag=1
    end
  end
  K+=flag
  println(flag==1 ? "Yes" : "No")
end


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

function main()
	n,a,b = readline() |> split |> parseMap
	s = readline() |> chomp
	d = 0
	f = 0
	for i in 1:n
		flg = 0
		if s[i] == 'a'
			if d+f<a+b
				flg = 1
				d += 1
			end
		elseif s[i] == 'b'
			if d+f<a+b && f<b
				flg = 1
				f += 1
			end
		end
		println(flg==1?"Yes":"No")
	end
end
main()


N, A, B = map(x->parse(Int,x), split(readuntil(STDIN, '\n')))
S = readuntil(STDIN, '\n')

for i in 1:length(S)
    println("No")
end


N, A, B = map(x->parse(Int,x), split(readline(STDIN)))
S = readline(STDIN)
c1 = 0
c2 = 0
for i in 1:length(S)
    if c1 < A+B && S[i] == 'a'
        c1 += 1
        println("Yes")
    elseif c1 < A+B && c2 < B && S[i] == 'b'
        c1 += 1
        c2 += 1
        print("Yes")
    else
        print("No")
    end
end


N, A, B = map(x->parse(Int,x), split(readline(STDIN)))
S = readline(STDIN)
c1 = 0
c2 = 0
for i in 1:length(S)
    if c1 < A+B && S[i] == 'a'
        c1 += 1
        println("Yes")
    elseif c1 < A+B && c2 < B && S[i] == 'b'
        c1 += 1
        c2 += 1
        println("Yes")
    else
        println("No")
    end
end


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

function main()
    s=chomp(readline())
    n=length(s)
    k=parseInt(readline())
    ans=""
    res=[]
    for i in 'a':'z'
        push!(res,'z'-i+1)
    end
    for i in s
        if res[i-'a'+1]<=k
            k-=res[i-'a'+1]
            ans*="a"
        else
            ans*=string(i)
        end
    end
    ans=ans[1:end-1]*string(ans[end]+k%26)
    println(ans)
end
main()

Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap


parseInt(x::Union{AbstractString,AbstractChar}) = parse(Int, x)
parseInt(x::Real) = trunc(Int, x)
parseBigInt(x::Union{AbstractString,AbstractChar}) = parse(BigInt, x)
parseBigInt(x::Real) = trunc(BigInt, x)
parseFloat(x::Union{AbstractString,AbstractChar}) = parse(Float64, x)
parseFloat(x::Real) = trunc(Float64, x)
parseBigFloat(x::Union{AbstractString,AbstractChar}) = parse(BigFloat, x)
parseBigFloat(x::Real) = trunc(BigFloat, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
parseMapBig(x::Array{SubString{String},1}) = map(parseBigInt, x)

function main()
    println((parseInt(readline())+parseInt(readline()))*parseInt(readline())÷2)
end
main()

Score : 100 points

Problem Statement

You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.

An example of a trapezoid

Find the area of this trapezoid.

Constraints

1≦a≦100

1≦b≦100

1≦h≦100

All input values are integers.

h is even.

Input

The input is given from Standard Input in the following format:

a
b
h

Output

Print the area of the given trapezoid. It is guaranteed that the area is an integer.

Sample Input 1

3
4
2

Sample Output 1

7

When the lengths of the upper base, lower base, and height are 3, 4, and 2, respectively, the area of the trapezoid is (3+4)×2/2 = 7.

Sample Input 2

4
4
4

Sample Output 2

16

In this case, a parallelogram is given, which is also a trapezoid.


s = parse.(split(readline(),""))
total = 0
p = length(s)
for i in 1:p
  for j in 0:p-i
    total += s[i]*2^(i-1)*2^max(p-i-j-1,0)*10^j
  end
end
println(total)

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

The input is given from Standard Input in the following format:

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944


parseInt(x) = parse(Int,x)

function main()
  S = chomp(readline())
  n = length(S)
  N = n-1
  a = 0
  for bit = 0:((1<<N)-1)
    l = []
    for i = 0:(N-1)
      if (bit >>> i) & 1 == 1
        push!(l,i+1)
      end
    end
    m = length(l)
    s = []
    if m > 0
      push!(s,parseInt(S[1:l[1]]))
      if m > 1
        for i = 2:m
          push!(s,parseInt(S[(l[i-1]+1):l[i]]))
        end
      end
      l[m] != n ? push!(s,parseInt(S[(l[m]+1):n])): tmp = 0
    else
      s = parseInt(S)
    end
    a += sum(s)
  end
  println(a)
end

main()


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

function main()
	n,x = readline() |> split |> parseMap
	a = readline() |> split |> parseMap
	d = zeros(Int,n,n)
	t = Int[i for i in 1:n]
	for i in 1:n
		d[i,i] = a[i]
		l = 1
		for j in i+1:n
			if a[i]+l*x<a[j]
				l = 1
				d[i,j] = a[i]+l*x
			else
				l += 1
				d[i,j] = a[j]
			end
		end
		for j in 1:i-1
			if a[i]+l*x<a[j]
				l = 1
				d[i,j] = a[i]+l*x
			else
				l += 1
				d[i,j] = a[j]
			end
		end
	end
	m = 0
	for i in 1:n
		m += minimum(d[:,i])
	end
	println(m)
end

main()

Score : 400 points

Problem Statement

Snuke lives in another world, where slimes are real creatures and kept by some people.
Slimes come in N colors. Those colors are conveniently numbered 1 through N.
Snuke currently has no slime. His objective is to have slimes of all the colors together.

Snuke can perform the following two actions:

Select a color i (1≤i≤N), such that he does not currently have a slime in color i, and catch a slime in color i. This action takes him a_i seconds.

Cast a spell, which changes the color of all the slimes that he currently has. The color of a slime in color i (1≤i≤N-1) will become color i+1, and the color of a slime in color N will become color 1. This action takes him x seconds.

Find the minimum time that Snuke needs to have slimes in all N colors.

Constraints

2≤N≤2,000

a_i are integers.

1≤a_i≤10^9

x is an integer.

1≤x≤10^9

Input

The input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Find the minimum time that Snuke needs to have slimes in all N colors.

Sample Input 1

2 10
1 100

Sample Output 1

12

Snuke can act as follows:

Catch a slime in color 1. This takes 1 second.

Cast the spell. The color of the slime changes: 1 → 2. This takes 10 seconds.

Catch a slime in color 1. This takes 1 second.

Sample Input 2

3 10
100 1 100

Sample Output 2

23

Snuke can act as follows:

Catch a slime in color 2. This takes 1 second.

Cast the spell. The color of the slime changes: 2 → 3. This takes 10 seconds.

Catch a slime in color 2. This takes 1 second.

Cast the soell. The color of each slime changes: 3 → 1, 2 → 3. This takes 10 seconds.

Catch a slime in color 2. This takes 1 second.

Sample Input 3

4 10
1 2 3 4

Sample Output 3

10

Snuke can act as follows:

Catch a slime in color 1. This takes 1 second.

Catch a slime in color 2. This takes 2 seconds.

Catch a slime in color 3. This takes 3 seconds.

Catch a slime in color 4. This takes 4 seconds.


MyString=Union{String,SubString{String},Char}
MyStringArray=Union{Array{String,1},Array{SubString{String},1},Array{Char,1}}
parseInt(x::MyString) = parse(Int, x)
parseInt(x::Real) = trunc(Int, x)
parseBigInt(x::MyString) = parse(BigInt, x)
parseBigInt(x::Real) = trunc(BigInt, x)
parseFloat(x::MyString) = parse(Float64, x)
parseFloat(x::Real) = trunc(Float64, x)
parseBigFloat(x::MyString) = parse(BigFloat, x)
parseBigFloat(x::Real) = trunc(BigFloat, x)
parseMap(x::MyStringArray) = map(parseInt, x)
parseMapBig(x::MyStringArray) = map(parseBigInt, x)

function main()
    n,k,x,y=[parseInt(readline()) for i in 1:4]
    if k<n
        println(k*x+(n-k)*y)
    else
        println(n*x)
    end
end
main()

Score : 100 points

Problem Statement

There is a hotel with the following accommodation fee:

X yen (the currency of Japan) per night, for the first K nights

Y yen per night, for the (K+1)-th and subsequent nights

Tak is staying at this hotel for N consecutive nights.
Find his total accommodation fee.

Constraints

1 \leq N, K \leq 10000

1 \leq Y < X \leq 10000

N,\,K,\,X,\,Y are integers.

Input

The input is given from Standard Input in the following format:

N
K
X
Y

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

10000 yen for the 1-st night

10000 yen for the 2-nd night

10000 yen for the 3-rd night

9000 yen for the 4-th night

9000 yen for the 5-th night

Thus, the total is 48000 yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000


Score : 200 points

Problem Statement

Let w be a string consisting of lowercase letters.
We will call w beautiful if the following condition is satisfied:

Each lowercase letter of the English alphabet occurs even number of times in w.

You are given the string w. Determine if w is beautiful.

Constraints

1 \leq |w| \leq 100

w consists of lowercase letters (a-z).

Input

The input is given from Standard Input in the following format:

w

Output

Print Yes if w is beautiful. Print No otherwise.

Sample Input 1

abaccaba

Sample Output 1

Yes

a occurs four times, b occurs twice, c occurs twice and the other letters occur zero times.

Sample Input 2

hthth

Sample Output 2

No


parseInt(x)=parse(Int,x)
d(x,a)=x%a==0?a:x%a
function main()
    n,a = map(parseInt,split(readline()))
    x = map(parseInt,split(readline()))
    z = zeros(Int,n,2500)
    count = 0
    ms = x[1]
    z[1,x[1]] += 1
    for i in 2:n
        z[i,x[i]] += 1
        for j in 1:ms
            z[i,j] += z[i-1,j]
            z[i,j+x[i]] += z[i-1,j]
        end
        ms += x[i]
    end
    k = 1
    while a*k<=2500
        count+=z[n,a*k]
        k+=1
    end
    println(count)
end
main()

Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

The input is given from Standard Input in the following format:

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

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


function inI()
    a = Ref{Int64}(0)
    ccall(:scanf, Int32, (Ptr{UInt8}, Ref{Int64},), "%lld", a)
    a[]
end

function outI(x::Int64)
    ccall(:printf, Void, (Ptr{UInt8}, Int64), "%lld\n", x)
end

@inbounds let
    n = inI()
    x = [inI() for _ in 1:n]
    l = inI()
    q = inI()
    const lg = 20
    F = Array(Int, lg, n)
    B = Array(Int, lg, n)
    for i = 1:n
        F[1,i] = searchsortedlast(x, x[i]+l)
        B[1,i] = searchsortedfirst(x, x[i]-l)
    end

    for fe = 2:lg
        for i = 1:n
            F[fe,i] = F[fe-1,F[fe-1,i]]
            B[fe,i] = B[fe-1,B[fe-1,i]]
        end
    end

    for i = 1:q
        a = inI()
        b = inI()

        ans = 1
        if a < b
            for fe = lg:-1:1
                if F[fe,a] < b
                    a = F[fe,a]
                    ans += 2^(fe-1)
                end
            end
        else
            for fe = lg:-1:1
                if B[fe,a] > b
                    a = B[fe,a]
                    ans += 2^(fe-1)
                end
            end
        end
        outI(ans)
    end
end

Score : 700 points

Problem Statement

N hotels are located on a straight line. The coordinate of the i-th hotel (1 \leq i \leq N) is x_i.

Tak the traveler has the following two personal principles:

He never travels a distance of more than L in a single day.

He never sleeps in the open. That is, he must stay at a hotel at the end of a day.

You are given Q queries. The j-th (1 \leq j \leq Q) query is described by two distinct integers a_j and b_j.
For each query, find the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel following his principles.
It is guaranteed that he can always travel from the a_j-th hotel to the b_j-th hotel, in any given input.

Constraints

2 \leq N \leq 10^5

1 \leq L \leq 10^9

1 \leq Q \leq 10^5

1 \leq x_i < x_2 < ... < x_N \leq 10^9

x_{i+1} - x_i \leq L

1 \leq a_j,b_j \leq N

a_j \neq b_j

N,\,L,\,Q,\,x_i,\,a_j,\,b_j are integers.

Partial Score

200 points will be awarded for passing the test set satisfying N \leq 10^3 and Q \leq 10^3.

Input

The input is given from Standard Input in the following format:

N
x_1 x_2 ... x_N
L
Q
a_1 b_1
a_2 b_2
:
a_Q b_Q

Output

Print Q lines.
The j-th line (1 \leq j \leq Q) should contain the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel.

Sample Input 1

9
1 3 6 13 15 18 19 29 31
10
4
1 8
7 3
6 7
8 5

Sample Output 1

4
2
1
2

For the 1-st query, he can travel from the 1-st hotel to the 8-th hotel in 4 days, as follows:

Day 1: Travel from the 1-st hotel to the 2-nd hotel. The distance traveled is 2.

Day 2: Travel from the 2-nd hotel to the 4-th hotel. The distance traveled is 10.

Day 3: Travel from the 4-th hotel to the 7-th hotel. The distance traveled is 6.

Day 4: Travel from the 7-th hotel to the 8-th hotel. The distance traveled is 10.


function inI()
    a = Ref{Int64}(0)
    ccall(:scanf, Int32, (Ptr{UInt8}, Ref{Int64},), "%lld", a)
    Int(a[])
end

function outI(x::Int64)
    ccall(:printf, Void, (Ptr{UInt8}, Int64), "%lld\n", x)
end

@inbounds let
    n = inI()
    x = Int[inI() for _ in 1:n]
    l = inI()
    q = inI()
    const lg = 20
    F = Array(Int, lg, n)
    B = Array(Int, lg, n)
    for i = 1:n
        F[1,i] = searchsortedlast(x, x[i]+l)
        B[1,i] = searchsortedfirst(x, x[i]-l)
    end

    for fe = 2:lg
        for i = 1:n
            F[fe,i] = F[fe-1,F[fe-1,i]]
            B[fe,i] = B[fe-1,B[fe-1,i]]
        end
    end

    for i = 1:q
        a = inI()
        b = inI()

        ans = 1
        if a < b
            for fe = lg:-1:1
                if F[fe,a] < b
                    a = F[fe,a]
                    ans += 2^(fe-1)
                end
            end
        else
            for fe = lg:-1:1
                if B[fe,a] > b
                    a = B[fe,a]
                    ans += 2^(fe-1)
                end
            end
        end
        outI(ans)
    end
end


if isfile("mystdin.txt");mystdin=open("mystdin.txt","r");redirect_stdin(mystdin);end
pI(x)=parse(Int,x)
pM(x::Array{SubString{String},1})=map(pI,x)
function main()
  s=chomp(readline())
  x=0
  y=0
  flag=false
  for i=s
    if i=='N'
      y+=1
    elseif i=='S'
      y-=1
    elseif i=='W'
      x-=1
    else
      x+=1
    end
    flag=flag || x==y==0
  end
  println(flag ? "Yes" : "No")
end
main()
if isdefined(Base, :mystdin);close(mystdin);end

Score : 200 points

Problem Statement

Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip.
At the beginning of Day 1, he is at home. His plan is described in a string S of length N.
On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction:

North if the i-th letter of S is N

West if the i-th letter of S is W

South if the i-th letter of S is S

East if the i-th letter of S is E

He has not decided each day's travel distance. Determine whether it is possible to set each day's travel distance so that he will be back at home at the end of Day N.

Constraints

1 ≦ | S | ≦ 1000

S consists of the letters N, W, S, E.

Input

The input is given from Standard Input in the following format:

S

Output

Print Yes if it is possible to set each day's travel distance so that he will be back at home at the end of Day N. Otherwise, print No.

Sample Input 1

SENW

Sample Output 1

Yes

If Snuke travels a distance of 1 on each day, he will be back at home at the end of day 4.

Sample Input 2

NSNNSNSN

Sample Output 2

Yes

Sample Input 3

NNEW

Sample Output 3

No

Sample Input 4

W

Sample Output 4

No


const N=parse(Int,readline())
const M=length(readline())-1
const O=10^9+7
function f(D)
	[(D[i>0?i:1]*(i>0?2:1)+(i<N?D[i+2]:0))%O for i=0:N]
end
function main()
	D=zeros(Int,N+1)
	D[1]=1
	for _=1:N
		D=f(D)
	end
	println(D[M+1]*invmod(powermod(2,M,O),O)%O)
end
main()

Score : 800 points

Problem Statement

Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.

To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:

The 0 key: a letter 0 will be inserted to the right of the string.

The 1 key: a letter 1 will be inserted to the right of the string.

The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.

Sig has launched the editor, and pressed these keys N times in total. As a result, the editor displays a string s. Find the number of such ways to press the keys, modulo 10^9 + 7.

Constraints

1 ≦ N ≦ 5000

1 ≦ |s| ≦ N

s consists of the letters 0 and 1.

Partial Score

400 points will be awarded for passing the test set satisfying 1 ≦ N ≦ 300.

Input

The input is given from Standard Input in the following format:

N
s

Output

Print the number of the ways to press the keys N times in total such that the editor displays the string s in the end, modulo 10^9+7.

Sample Input 1

3
0

Sample Output 1

5

We will denote the backspace key by B. The following 5 ways to press the keys will cause the editor to display the string 0 in the end: 00B, 01B, 0B0, 1B0, BB0. In the last way, nothing will happen when the backspace key is pressed.

Sample Input 2

300
1100100

Sample Output 2

519054663

Sample Input 3

5000
01000001011101000100001101101111011001000110010101110010000

Sample Output 3

500886057


function main()
	N=parse(Int,readline())
	M=length(chomp(readline()))
	D=zeros(Int,N+1)
	O=10^9+7
	D[1]=1
	for _=1:N
		D=[(D[i>0?i:1]*(i>0?2:1)+(i<N?D[i+2]:0))%O for i=0:N]
	end
	println(D[M+1]*invmod(2^M,O)%O)
end
main()


function main()

  N = parse(Int, readline())

  println((1/2)*N*(N+1))

end

main()

Score : 100 points

Problem Statement

There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?

Constraints

1≦N≦100

Input

The input is given from Standard Input in the following format:

N

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is 1+2+3=6.

Sample Input 2

10

Sample Output 2

55

The sum of the integers from 1 to 10 is 55.

Sample Input 3

1

Sample Output 3

1

Only one child. The answer is 1 in this case.


function main()
  a=parse(Int,readline())
  print((a*(a+1)/2))
end

main()


function main()
  a=parse(Int,readline())
  return a(a+1)/2
end

main()


function main()

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

  ans = 10^5
  max_num = maximum(a)
  min_num = minimum(a)

  for i in min_num:max_num
    check = 0
    for j in a
      check += (i - j)^2
    end
    ans = min(ans, check)
  end

  println(ans)

end

main()

Score : 200 points

Problem Statement

Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.

He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).

Find the minimum total cost to achieve his objective.

Constraints

1≦N≦100

-100≦a_i≦100

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum total cost to achieve Evi's objective.

Sample Input 1

2
4 8

Sample Output 1

8

Transforming the both into 6s will cost (4-6)^2+(8-6)^2=8 dollars, which is the minimum.

Sample Input 2

3
1 1 3

Sample Output 2

3

Transforming the all into 2s will cost (1-2)^2+(1-2)^2+(3-2)^2=3 dollars. Note that Evi has to pay (1-2)^2 dollar separately for transforming each of the two 1s.

Sample Input 3

3
4 2 5

Sample Output 3

5

Leaving the 4 as it is and transforming the 2 and the 5 into 4s will achieve the total cost of (2-4)^2+(5-4)^2=5 dollars, which is the minimum.

Sample Input 4

4
-100 -100 -100 -100

Sample Output 4

0

Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 0.


MyString=Union{String,SubString{String},Char}
MyStringArray=Union{Array{String,1},Array{SubString{String},1},Array{Char,1}}
parseInt(x::MyString) = parse(Int, x)
parseInt(x::Real) = trunc(Int, x)
parseBigInt(x::MyString) = parse(BigInt, x)
parseBigInt(x::Real) = trunc(BigInt, x)
parseFloat(x::MyString) = parse(Float64, x)
parseFloat(x::Real) = trunc(Float64, x)
parseBigFloat(x::MyString) = parse(BigFloat, x)
parseBigFloat(x::Real) = trunc(BigFloat, x)
parseMap(x::MyStringArray) = map(parseInt, x)
parseMapBig(x::MyStringArray) = map(parseBigInt, x)

function main()
    n=parseInt(readline())
    a=sort(parseMap(split(readline())))
    ans=10^9
    for i in a[1]:a[end]
        res=0
        for j in a
            res+=(i-j)^2
        end
        ans=min(res,ans)
    end
    println(ans)
end
main()


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

function main()
	n = readline() |> parseInt
	a = readline() |> split |> parseMap
	ls = sum(a)
	ss = 0
	m1 = ceil(Int,ls/n)
	m2 = floor(Int,ls/n)
	for i in 1:n
		ss += a[i]^2
	end
	println(min(m1^2*n-2*m1*ls+ss, m2^2*n-2*m2*ls+ss))
end

main()


if isfile("mystdin.txt");mystdin=open("mystdin.txt","r");redirect_stdin(mystdin);end
pI(x)=parse(BigInt,x)
pM(x::Array{SubString{String},1})=map(pI,x)
function main()
  a,b=pM(split(readline()))
  if (a>0) != (b>0) || a==0 || b==0
    println("Zero")
  elseif a<0 && abs(a-b)%2==0
    println("Negative")
  else
    println("Positive")
  end
end
main()
if isdefined(Base, :mystdin);close(mystdin);end

Problem Statement

You are given two integers a and b (a≤b). Determine if the product of the integers a, a+1, …, b is positive, negative or zero.

Constraints

a and b are integers.

-10^9≤a≤b≤10^9

Partial Score

In test cases worth 100 points, -10≤a≤b≤10.

Input

The input is given from Standard Input in the following format:

a b

Output

If the product is positive, print Positive. If it is negative, print Negative. If it is zero, print Zero.

Sample Input 1

1 3

Sample Output 1

Positive

1×2×3=6 is positive.

Sample Input 2

-3 -1

Sample Output 2

Negative

(-3)×(-2)×(-1)=-6 is negative.

Sample Input 3

-1 1

Sample Output 3

Zero

(-1)×0×1=0.


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

function main()
    n,m = readline() |> split |> parseMap
    v = ones(Int,n)
    f = zeros(Int,n)
    f[1] = 1
    for i in 1:m
        x,y = readline() |> split |> parseMap
        v[x] -= 1
        v[y] += 1
        if f[x]==1
            f[y] = 1
            if v[x] == 0
                f[x] = 0
            end
        end
    end
    println(sum(f))
end
main()

Problem Statement

We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball.

Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i.

Find the number of boxes that may contain the red ball after all operations are performed.

Constraints

2≤N≤10^5

1≤M≤10^5

1≤x_i,y_i≤N

x_i≠y_i

Just before the i-th operation is performed, box x_i contains at least 1 ball.

Input

The input is given from Standard Input in the following format:

N M
x_1 y_1
:
x_M y_M

Output

Print the number of boxes that may contain the red ball after all operations are performed.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

2

Just after the first operation, box 1 is empty, box 2 contains one red ball and one white ball, and box 3 contains one white ball.

Now, consider the second operation. If Snuke picks the red ball from box 2, the red ball will go into box 3. If he picks the white ball instead, the red ball will stay in box 2.
Thus, the number of boxes that may contain the red ball after all operations, is 2.

Sample Input 2

3 3
1 2
2 3
2 3

Sample Output 2

1

All balls will go into box 3.

Sample Input 3

4 4
1 2
2 3
4 1
3 4

Sample Output 3

3


input = readline()
if arr == [5, 5, 7] || arr == [5, 7, 5] || arr == [7, 5, 5]
    println("YES")
else
    println("NO")
end

Score : 100 points

Problem Statement

Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.

To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.

Constraints

1≦A,B,C≦10

Input

The input is given from Standard Input in the following format:

A B C

Output

If it is possible to construct a Haiku by using each of the phrases once, print YES (case-sensitive). Otherwise, print NO.

Sample Input 1

5 5 7

Sample Output 1

YES

Using three phrases of length 5, 5 and 7, it is possible to construct a Haiku.

Sample Input 2

7 7 5

Sample Output 2

NO


function main()
  a = map(x->parse(Int,x),split(readline()))
  b = sort(a)
  if b==[5,5,7]
    print("YES")
  else
    print("NO")
  end
end
main()


a = parse(Int, readline(stdin))
bs = sort!(map((x) -> parse(Int, x), split(readline(stdin), ' ')))
sum = 0
for (i, v) in enumerate(bs)
    if i % 2 == 0
        sum += v
    end
end
println(sum)

Score : 200 points

Problem Statement

Snuke is having a barbeque party.

At the party, he will make N servings of Skewer Meal.

Example of a serving of Skewer Meal

He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i.
Also, he has an infinite supply of ingredients.

To make a serving of Skewer Meal, he picks 2 skewers and threads ingredients onto those skewers.
Let the length of the shorter skewer be x, then the serving can hold the maximum of x ingredients.

What is the maximum total number of ingredients that his N servings of Skewer Meal can hold, if he uses the skewers optimally?

Constraints

1≦N≦100

1≦L_i≦100

For each i, L_i is an integer.

Input

The input is given from Standard Input in the following format:

N
L_1 L_2 ... L_{2N}

Output

Print the maximum total number of ingredients that Snuke's N servings of Skewer Meal can hold.

Sample Input 1

2
1 3 1 2

Sample Output 1

3

If he makes a serving using the first and third skewers, and another using the second and fourth skewers, each serving will hold 1 and 2 ingredients, for the total of 3.

Sample Input 2

5
100 1 2 3 14 15 58 58 58 29

Sample Output 2

135


n, x = map((x) -> parse(Int, x), split(readline(stdin), ' '))
function a(longline, shortline)
    if shortline == 0
        return 0
    else
        return longline+shortline+a(shortline, longline-shortline)
    end
end
println(x + a(n-x, x))

Score : 500 points

Problem Statement

Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light.

Three mirrors of length N are set so that they form an equilateral triangle.
Let the vertices of the triangle be a, b and c.

Inside the triangle, the rifle is placed at the point p on segment ab such that ap = X.
(The size of the rifle is negligible.)
Now, the rifle is about to fire a ray of Mysterious Light in the direction of bc.

The ray of Mysterious Light will travel in a straight line, and will be reflected by mirrors, in the same ways as "ordinary" light.
There is one major difference, though: it will be also reflected by its own trajectory as if it is a mirror!
When the ray comes back to the rifle, the ray will be absorbed.

The following image shows the ray's trajectory where N = 5 and X = 2.

It can be shown that the ray eventually comes back to the rifle and is absorbed, regardless of the values of N and X.
Find the total length of the ray's trajectory.

Constraints

2≦N≦10^{12}

1≦X≦N-1

N and X are integers.

Partial Points

300 points will be awarded for passing the test set satisfying N≦1000.

Another 200 points will be awarded for passing the test set without additional constraints.

Input

The input is given from Standard Input in the following format:

N X

Output

Print the total length of the ray's trajectory.

Sample Input 1

5 2

Sample Output 1

12

Refer to the image in the Problem Statement section.
The total length of the trajectory is 2+3+2+2+1+1+1 = 12.