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

function eval(p::Tuple{Int,Int},c::Tuple{Int,Int})
	if (p[1]+p[2])%2==(c[1]+c[2])%2
		false
	elseif p[1]+p[2]+1<c[1]-c[2]||c[1]+c[2]+1<p[1]-p[2]
		false
	else
		true
	end
end

function calc(p::Tuple{Int,Int},c::Tuple{Int,Int})
	l = max(p[1]-p[2],c[1]-c[2]-1)
	r = min(p[1]+p[2],c[1]+c[2]+1)
	((r+l)>>1,(r-l)>>1)
end

function main()
	n = readline() |> parseInt
	e = [Int[] for i in 1:n]
	for i in 1:n-1
		a,b = readline() |> split |> parseMap
		push!(e[a],b)
		push!(e[b],a)
	end
	k = readline() |> parseInt
	num = Tuple{Int,Int}[(-10^18,10^18) for i in 1:n]
	nx = zeros(Int,n)
	for i in 1:k
		v,p = readline() |> split |> parseMap
		num[v]=(p,p)
		nx[v]=1
	end
	rt = 0
	for i in 1:n
		if nx[i]==1
			rt = i
			break
		end
	end
	stack = Int[rt]
	t = -ones(Int,n)
	layer = Tuple{Int,Int}[(0,i) for i in 1:n]
	t[rt] = rt
	while !isempty(stack)
		now = pop!(stack)
		for i in e[now]
			if t[i]<0
				push!(stack,i)
				t[i] = now
				layer[i] = (layer[now][1]+1,i)
			end
		end
		layer = sort(layer,by=x->x[1],rev=true)
	end
	f = 0
	x = num[rt][1]%2
	for iter in 1:n
		i = layer[iter][2]
		cl = num[i][1]
		cr = num[i][2]
		pl = num[t[i]][1]
		pr = num[t[i]][2]
		if cl==cr&&(cl+layer[iter][1])%2!=x
			f = 1
		elseif pr+1<cl||cr+1<pl
			f = 1
		else
			num[t[i]] = (max(pl,cl-1),min(pr,cr+1))
		end
	end
	if f == 1
		println("No")
	else
		println("Yes")
		ans = -10^18*ones(Int,n)
		ans[rt] = num[rt][1]
		stack = Int[rt]
		while !isempty(stack)
			now = pop!(stack)
			for i in e[now]
				if ans[i]==-10^18
					push!(stack,i)
					if num[i][1]<=ans[now]+1<=num[i][2]
						ans[i] = ans[now]+1
					else
						ans[i] = ans[now]-1
					end
				end
			end
		end
		for i in 1:n
			println(ans[i])
		end
	end
end

main()

Score : 800 points

Problem Statement

We have a tree with N vertices. The vertices are numbered 1, 2, ..., N. The i-th (1 ≦ i ≦ N - 1) edge connects the two vertices A_i and B_i.

Takahashi wrote integers into K of the vertices. Specifically, for each 1 ≦ j ≦ K, he wrote the integer P_j into vertex V_j. The remaining vertices are left empty. After that, he got tired and fell asleep.

Then, Aoki appeared. He is trying to surprise Takahashi by writing integers into all empty vertices so that the following condition is satisfied:

Condition: For any two vertices directly connected by an edge, the integers written into these vertices differ by exactly 1.

Determine if it is possible to write integers into all empty vertices so that the condition is satisfied. If the answer is positive, find one specific way to satisfy the condition.

Constraints

1 ≦ N ≦ 10^5

1 ≦ K ≦ N

1 ≦ A_i, B_i ≦ N (1 ≦ i ≦ N - 1)

1 ≦ V_j ≦ N (1 ≦ j ≦ K) (21:18, a mistake in this constraint was corrected)

0 ≦ P_j ≦ 10^5 (1 ≦ j ≦ K)

The given graph is a tree.

All v_j are distinct.

Input

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

N
A_1 B_1
A_2 B_2
:
A_{N-1} B_{N-1}
K
V_1 P_1
V_2 P_2
:
V_K P_K

Output

If it is possible to write integers into all empty vertices so that the condition is satisfied, print Yes. Otherwise, print No.

If it is possible to satisfy the condition, print N lines in addition. The v-th (1 ≦ v ≦ N) of these N lines should contain the integer that should be written into vertex v. If there are multiple ways to satisfy the condition, any of those is accepted.

Sample Input 1

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

Sample Output 1

Yes
5
6
6
5
7

The figure below shows the tree when Takahashi fell asleep. For each vertex, the integer written beside it represents the index of the vertex, and the integer written into the vertex is the integer written by Takahashi.

Aoki can, for example, satisfy the condition by writing integers into the remaining vertices as follows:

This corresponds to Sample Output 1. Note that other outputs that satisfy the condition will also be accepted, such as:

Yes
7
6
8
7
7

Sample Input 2

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

Sample Output 2

No

Sample Input 3

4
1 2
2 3
3 4
1
1 0

Sample Output 3

Yes
0
-1
-2
-3

The integers written by Aoki may be negative or exceed 10^6.


N=parse(Int,readline())
s=chomp(readline())
t=chomp(readline())
ans=0
for i=1:N
  flag=true
  for j=1:i
    if s[N-i+j]!=t[j]
      flag=false
    end
  end
  if flag
    ans=i
  end
end
println(2N-ans)

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

Score : 200 points

Problem Statement

Snuke is interested in strings that satisfy the following conditions:

The length of the string is at least N.

The first N characters equal to the string s.

The last N characters equal to the string t.

Find the length of the shortest string that satisfies the conditions.

Constraints

1≤N≤100

The lengths of s and t are both N.

s and t consist of lowercase English letters.

Input

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

N
s
t

Output

Print the length of the shortest string that satisfies the conditions.

Sample Input 1

3
abc
cde

Sample Output 1

5

The shortest string is abcde.

Sample Input 2

1
a
z

Sample Output 2

2

The shortest string is az.

Sample Input 3

4
expr
expr

Sample Output 3

4

The shortest string is expr.

Submitted source-code file size, in bytes.

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

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


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

function main()
	n = readline() |> parseInt
	s = readline() |> chomp
	t = readline() |> chomp
	flg = n
	for i in 0:n
		f = 0
		for j in 1:n-i
			if s[j+i]!=t[j]
				f = 1
				break
			end
		end
		if f == 0
			flg = i
			break
		end
	end
	println(flg+n)
end
main()


s=readline()

hantei1=false
hantei2=false
let
for i in 1:length(s)
    hantei1=hantei1?true:is(s[i],'C')
    hantei2=hantei1?(hantei2||is(s[i],'F')):false
end
end
answer=hantei2?"Yes":"No"
println(answer)

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.


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

function main()
    k,t=parseMap(split(readline()))
    a=sort(parseMap(split(readline())),rev=true)[1]
    ans=0
    if a>k÷2
        ans=a-k÷2
    end
    if t==1
        ans=a-1
    end
    println(ans)
end
main()

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.


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

function main()
	a = readline() |> split |> parseMap
	println(length(Set(a)))
end

main()

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

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

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


ls = parse.([Int], split(readline(STDIN)))
println(length(unique(sort(ls))))


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()
  m,k=pM(split(readline()))
  println(k*(k-1)^(m-1))
end
main()
if isdefined(Base, :mystdin);close(mystdin);end

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.


Q = split(readline())
N,K=parse(Int,Q[1]),parse(Int,Q[2])
println(K * (K-1)^(N-1))


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()
    n=parseInt(readline())
    one,two=parseMap(split(readline()))
    one,two=BigInt(one),BigInt(two)
    for i in 2:n
        t,a=parseMap(split(readline()))
        m=BigInt(max(ceil(one/t),ceil(two/a)))
        one,two=m*t,m*a
    end
    println(one+two)
end
main()

Score : 300 points

Problem Statement

AtCoDeer the deer is seeing a quick report of election results on TV.
Two candidates are standing for the election: Takahashi and Aoki.
The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes.
AtCoDeer has checked the report N times, and when he checked it for the i-th (1≦i≦N) time, the ratio was T_i:A_i.
It is known that each candidate had at least one vote when he checked the report for the first time.

Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the N-th time.
It can be assumed that the number of votes obtained by each candidate never decreases.

Constraints

1≦N≦1000

1≦T_i,A_i≦1000 (1≦i≦N)

T_i and A_i (1≦i≦N) are coprime.

It is guaranteed that the correct answer is at most 10^{18}.

Input

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

N
T_1 A_1
T_2 A_2
:
T_N A_N

Output

Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the N-th time.

Sample Input 1

3
2 3
1 1
3 2

Sample Output 1

10

When the numbers of votes obtained by the two candidates change as 2,3 → 3,3 → 6,4, the total number of votes at the end is 10, which is the minimum possible number.

Sample Input 2

4
1 1
1 1
1 5
1 100

Sample Output 2

101

It is possible that neither candidate obtained a vote between the moment when he checked the report, and the moment when he checked it for the next time.

Sample Input 3

5
3 10
48 17
31 199
231 23
3 2

Sample Output 3

6930


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())
    ans="CODEFESTIVAL2016"
    cnt=0
    for i in 1:16
        if s[i]!=ans[i]
            cnt+=1
        end
    end
    println(cnt)
end
main()

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


N, A, B = map(x->parse(Int,x), split(readline(STDIN)))
S = rstrip(readline(STDIN), '\n')
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

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(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


function main()

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

  for i in 1:12

    if i == 4
      print(s[i]," ")
    else
      print(s[i])
    end

  end

end

main()

Score : 100 points

Problem Statement

This contest is CODE FESTIVAL.
However, Mr. Takahashi always writes it CODEFESTIVAL, omitting the single space between CODE and FESTIVAL.

So he has decided to make a program that puts the single space he omitted.

You are given a string s with 12 letters.
Output the string putting a single space between the first 4 letters and last 8 letters in the string s.

Constraints

s contains exactly 12 letters.

All letters in s are uppercase English letters.

Input

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

s

Output

Print the string putting a single space between the first 4 letters and last 8 letters in the string s.
Put a line break at the end.

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE FESTIVAL

Putting a single space between the first 4 letters and last 8 letters in CODEFESTIVAL makes it CODE FESTIVAL.

Sample Input 2

POSTGRADUATE

Sample Output 2

POST GRADUATE

Sample Input 3

ABCDEFGHIJKL

Sample Output 3

ABCD EFGHIJKL


parseLine() = parse.(Int,split(readline()))
function main()
    N=parse.(Int64,readline())
    A=parseLine()
    ans=0
    for i=1:N
        if A[A[i]]==i
            ans+=1
            global A[i]=-1
        end
    end
    println(ans)
end

main()

Score : 200 points

Problem Statement

There are N rabbits, numbered 1 through N.

The i-th (1≤i≤N) rabbit likes rabbit a_i.
Note that no rabbit can like itself, that is, a_i≠i.

For a pair of rabbits i and j (i＜j), we call the pair (i，j) a friendly pair if the following condition is met.

Rabbit i likes rabbit j and rabbit j likes rabbit i.

Calculate the number of the friendly pairs.

Constraints

2≤N≤10^5

1≤a_i≤N

a_i≠i

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 friendly pairs.

Sample Input 1

4
2 1 4 3

Sample Output 1

2

There are two friendly pairs: (1，2) and (3，4).

Sample Input 2

3
2 3 1

Sample Output 2

0

There are no friendly pairs.

Sample Input 3

5
5 5 5 5 1

Sample Output 3

1

There is one friendly pair: (1，5).


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=Dict{Char,Int}()
    for i in 'a':'z'
        push!(res,i=>'z'-i+1)
    end
    res['a']=0
    for i in 1:n
        if res[s[i]]<=k
            k-=res[s[i]]
            tmp='a'
        else
            tmp=s[i]
        end
        if i==n
            k%=26
            for i in 1:k
                tmp+=1
                if tmp>'z'
                    tmp='a'
                end
            end
            println(tmp)
        else
            print(tmp)
        end
    end
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) = 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())
    for i in 1:n
        if 'z'-s[i]+1<=k
            k-='z'-s[i]+1
            s=s[1:i-1]*"a"*s[i+1:end]
        end
    end
    s=s[1:end-1]*string(s[end]+k%26)
    println(s)
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.


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

function main()
	sa = readline() |> chomp
	sb = readline() |> chomp
	sc = readline() |> chomp
	la = length(sa)
	lb = length(sb)
	lc = length(sc)
	na = 1
	nb = 1
	nc = 1
	t = 1
	while na<=la&&nb<=lb&&nc<=lc
		if t==1
			if sa[na]=='a'
				t = 1
			elseif sa[na]=='b'
				t = 2
			elseif sa[na]=='c'
				t = 3
			end
			na+=1
		elseif t==2
			if sb[nb]=='a'
				t = 1
			elseif sb[nb]=='b'
				t = 2
			elseif sb[nb]=='c'
				t = 3
			end
			nb += 1
		else
			if sc[nc]=='a'
				t = 1
			elseif sc[nc]=='b'
				t = 2
			elseif sc[nc]=='c'
				t = 3
			end
			nc += 1
		end
	end
	if na==la
		println("A")
	elseif nb==lb
		println("B")
	else
		println("C")
	end
end

main()

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

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

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


s=[];
for i=1:3
	push!(s,chomp(readline()))
end
c=[1,1,1]
f=1
while c[f]<=length(s[f])
	c[f]+=1
	f=Int(s[f][c[f]-1])-96
end
print(Char(f+64))


const D=Dict{Pair{Int,Int},Int}()
function f(H,W,x,y,cnt)
	for (dx,dy)=zip([1,1,1,0,0,0,-1,-1,-1],[1,0,-1,1,0,-1,1,0,-1])
		tx,ty=x+dx,y+dy
		if 1<tx<H&&1<ty<W
			t=get(D,tx=>ty,0)
			cnt[t+1]-=1
			cnt[t+2]+=1
			D[tx=>ty]=t+1
		end
	end
end
function main()
	H,W,N=map(x->parse(Int,x),split(readline()))
	cnt=zeros(Int,10)
	cnt[1]=(H-2)*(W-2)
	for s=readlines()
		x,y=map(x->parse(Int,x),split(s))
		f(H,W,x,y,cnt)
	end
	println(join(cnt,'\n'))
end
main()

Score : 400 points

Problem Statement

We have a grid with H rows and W columns. At first, all cells were painted white.

Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.

Compute the following:

For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the grid contains exactly j black cells, after Snuke painted N cells?

Constraints

3 \leq H \leq 10^9

3 \leq W \leq 10^9

0 \leq N \leq min(10^5,H×W)

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

1 \leq b_i \leq W (1 \leq i \leq N)

(a_i, b_i) \neq (a_j, b_j) (i \neq j)

Input

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

H W N
a_1 b_1
:
a_N b_N

Output

Print 10 lines.
The (j+1)-th ( 0 \leq j \leq 9 ) line should contain the number of the subrectangles of size 3×3 of the grid that contains exactly j black cells.

Sample Input 1

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

Sample Output 1

0
0
0
2
4
0
0
0
0
0

There are six subrectangles of size 3×3. Two of them contain three black cells each, and the remaining four contain four black cells each.

Sample Input 2

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

Sample Output 2

4
26
22
10
2
0
0
0
0
0

Sample Input 3

1000000000 1000000000 0

Sample Output 3

999999996000000004
0
0
0
0
0
0
0
0
0


function main()
	n::Int, x::Int = map(x -> parse(Int, x), split(readline()))
	a::Vector{Int} = map(x -> parse(Int, x), split(readline()))
	b::Vector{Int} = copy(a)

	ans = 10^15
	for i in 1:n
		sm = 0
		for j in 1:n
			sm += b[j]
		end
		ans = min(ans, sm + x*(i-1))
		for j in 1:n
			b[j] = min(b[j], a[mod1(j-i, n)])
		end
	end

	println(ans)
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.


p(x)=parse(Int,x)
function main()
  n = p(readline())
  k = p(readline())
  x = p(readline())
  y = p(readline())
  if n<=k
    print($(n*x)|>Int)
  else
    print($(n*x + (n-k)*y)|> Int)
  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


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()
  w=chomp(readline())
  flag=true
  for i='a':'z'
    if count(x->x==i,w)%2!=0; flag=false; end
  end
  println(flag ? "Yes" : "No")
end
main()
if isdefined(Base, :mystdin);close(mystdin);end

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


function main()

  w = split(readline(),"")

  a2z = [string(i) for i in 'a':'z']

  count = 0

  for i in a2z
    for j in 1:length(S)

      if S[j] == i
        count += 1
      end

    end

    if count % 2 == 0
      count = 0
    else
      break
    end

  end

  if count == 0
    println("Yes")
  else
    println("No")
  end

end

main()


n,s=map(x->parse(Int,x),readlines())
A=3n
f(b,n)=n<b?n:f(b,div(n,b))+n%b
g(b)=b>1&&f(b,n)==s?min(A,b):A
A=g(n+1)
for b=1:isqrt(n);A=g(b);A=g(div(n-s,b)+1);end
println(A>2n?-1:A)

Score : 500 points

Problem Statement

For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:

f(b,n) = n, when n < b

f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b

Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b,
and n \ {\rm mod} \ b denotes the remainder of n divided by b.

Less formally, f(b,n) is equal to the sum of the digits of n written in base b.
For example, the following hold:

f(10,\,87654)=8+7+6+5+4=30

f(100,\,87654)=8+76+54=138

You are given integers n and s.
Determine if there exists an integer b (b \geq 2) such that f(b,n)=s.
If the answer is positive, also find the smallest such b.

Constraints

1 \leq n \leq 10^{11}

1 \leq s \leq 10^{11}

n,\,s are integers.

Input

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

n
s

Output

If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b.
If such b does not exist, print -1 instead.

Sample Input 1

87654
30

Sample Output 1

10

Sample Input 2

87654
138

Sample Output 2

100

Sample Input 3

87654
45678

Sample Output 3

-1

Sample Input 4

31415926535
1

Sample Output 4

31415926535

Sample Input 5

1
31415926535

Sample Output 5

-1


n,s=map(x->parse(Int,x),readlines())
m=isqrt(n)
f(b,n)=1<b ? n<b ? n : f(b,div(n,b))+n%b : 0
A=[]
f(n+1,n)==s&&push!(A,n+1)
for b=1:m
	f(b,n)==s&&push!(A,b)
	z=div(n-s,b)
	f(z,n)==s&&push!(A,z)
end
println(isempty(A) ? -1 : minimum(A))


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())
    no,we,so,ea=0,0,0,0
    for i=s
        if i=='N'
            no+=1
        elseif i=='W'
            we+=1
        elseif i=='S'
            so+=1
        else
            ea+=1
        end
    end
    if ((no>0 && so>0) || no==so==0) && ((we>0 && ea>0) || we==ea==0)
        println("Yes")
    else
        println("No")
    end
end
main()

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


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

function main()
	s = readline() |> chomp
	cn = 0
	cw = 0
	cs = 0
	ce = 0
	for i in 1:length(s)
		if s[i] == 'N'
			cn = 1
		elseif s[i] == 'W'
			cw = 1
		elseif s[i] == 'S'
			cs = 1
		elseif s[i] === 'E'
			ce = 1
		end
	end
	println(cn==cs&&cw==ce?"Yes":"No")
end
main()


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(modpower(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())

  ans = replace(string((1/2)*N*(N+1)),".0","")

  println(ans)

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()

  s = split(readline(),"")
  ans = ""

  for i in 1:length(s)-1

    if s[i] == "B"
      continue
    elseif s[i+1] != "B"
      ans *= s[i]
    end

  end

  if s[end] != "B"
    ans *= s[end]
  end

  println(ans)

end

main()

Score : 200 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 several times. You are given a string s, which is a record of his keystrokes in order. In this string, the letter 0 stands for the 0 key, the letter 1 stands for the 1 key and the letter B stands for the backspace key. What string is displayed in the editor now?

Constraints

1 ≦ |s| ≦ 10 (|s| denotes the length of s)

s consists of the letters 0, 1 and B.

The correct answer is not an empty string.

Input

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

s

Output

Print the string displayed in the editor in the end.

Sample Input 1

01B0

Sample Output 1

00

Each time the key is pressed, the string in the editor will change as follows: 0, 01, 0, 00.

Sample Input 2

0BB1

Sample Output 2

1

Each time the key is pressed, the string in the editor will change as follows: 0, (empty), (empty), 1.


function main()
	s = chomp(readline())
	k = []
	for i in 1:length(s)
		if s[i] == '1'
			push!(k,"1")
		elseif s[i] == '0'
			push!(k,"0")
		elseif length(k) > 0
			pop!(k)
		end
	end
	for i in 1:length(k)
		print(k[i])
	end
end

main()


s=chomp(readline())
t=length(s)
for i=1:t-1
	if s[i]==s[i+1]
		println("$i $(i+1)")
		exit()
	end
end
for i=1:t-2
	if s[i]==s[i+2]
		println("$i $(i+2)")
		exit()
	end
end
println("-1 -1")

Score : 400 points

Problem Statement

Given a string t, we will call it unbalanced if and only if the length of t is at least 2, and more than half of the letters in t are the same. For example, both voodoo and melee are unbalanced, while neither noon nor a is.

You are given a string s consisting of lowercase letters. Determine if there exists a (contiguous) substring of s that is unbalanced. If the answer is positive, show a position where such a substring occurs in s.

Constraints

2 ≦ |s| ≦ 10^5

s consists of lowercase letters.

Partial Score

200 points will be awarded for passing the test set satisfying 2 ≦ N ≦ 100.

Input

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

s

Output

If there exists no unbalanced substring of s, print -1 -1.

If there exists an unbalanced substring of s, let one such substring be s_a s_{a+1} ... s_{b} (1 ≦ a < b ≦ |s|), and print a b. If there exists more than one such substring, any of them will be accepted.

Sample Input 1

needed

Sample Output 1

2 5

The string s_2 s_3 s_4 s_5 = eede is unbalanced. There are also other unbalanced substrings. For example, the output 2 6 will also be accepted.

Sample Input 2

atcoder

Sample Output 2

-1 -1

The string atcoder contains no unbalanced substring.


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()
    parse_int(x) = parse(Int, x)
    min_num, exclude = split(readline())
    excludes = parse_int.(split(readline()))

    can_use = sort([string(x) for x in 0:9 if !(x in excludes)])

    ans_str = []
    for (i, revi) in enumerate(reverse(range(1, length=length(min_num) + 1, step=1)))
        try
            append!(ans_str, [x for x in can_use if parse_int(x) >= parse_int(min_num[revi])][1])
        catch BoundsError
            append!(ans_str, can_use[1])
            min_num = string(parse_int(min_num) + 10^i)
        end
    end
    return join(reverse(ans_str))
end

println(main())

Score : 300 points

Problem Statement

Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.

She is shopping, and now paying at the cashier.
Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}

Input

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

N K
D_1 D_2 … D_K

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

The smallest integer equal to or greater than N=1000 whose decimal notation contains only 0 and 2, is 2000.

Sample Input 2

9999 1
0

Sample Output 2

9999


n,k = map(x -> parse(Int64, x), split(readline()))

d = map(x -> parse(Int64, x), split(readline()))

while n>=1
  m = map(x -> parse(Int64, x), split(string(n),""))
  p = 0
  for i in 1:k
  	if in(d[i] , m)
      p += 1
      break
    end
  end
  if p == 0
    print(n)
    global n=0
  else
  global n += 1
  end
end


N=parse(Int,readline())
L=sort(map(x->parse(Int,x),split(readline())))
ans=0
for i=1:N
  ans+=L[i*2-1]
end
println(ans)

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
println(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.