N = parse(Int64, strip(readline()))
nx = 1
pop = 1
res = zeros(Int64, N, N)
for i in 1:N
  for j in i+1:N
    res[i,j] = res[j,i] = nx
    nx,pop = nx+pop,nx
  end
end

for i in 1:N
  println(join(map(string, res[i,:]), ' '))
end

Score : 900 points

Problem Statement

Diverta City is a new city consisting of N towns numbered 1, 2, ..., N.

The mayor Ringo is planning to connect every pair of two different towns with a bidirectional road. The length of each road is undecided.

A Hamiltonian path is a path that starts at one of the towns and visits each of the other towns exactly once.
The reversal of a Hamiltonian path is considered the same as the original Hamiltonian path.

There are N! / 2 Hamiltonian paths. Ringo wants all these paths to have distinct total lengths (the sum of the lengths of the roads on a path), to make the city diverse.

Find one such set of the lengths of the roads, under the following conditions:

The length of each road must be a positive integer.

The maximum total length of a Hamiltonian path must be at most 10^{11}.

Constraints

N is a integer between 2 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print a set of the lengths of the roads that meets the objective, in the following format:

w_{1, 1} \ w_{1, 2} \ w_{1, 3} \ ... \ w_{1, N}
w_{2, 1} \ w_{2, 2} \ w_{2, 3} \ ... \ w_{2, N}
: : :
w_{N, 1} \ w_{N, 2} \ w_{N, 3} \ ... \ w_{N, N}

where w_{i, j} is the length of the road connecting Town i and Town j, which must satisfy the following conditions:

w_{i, i} = 0

w_{i, j} = w_{j, i} \ (i \neq j)

1 \leq w_{i, j} \leq 10^{11} \ (i \neq j)

If there are multiple sets of lengths of the roads that meet the objective, any of them will be accepted.

Sample Input 1

3

Sample Output 1

0 6 15
6 0 21
15 21 0

There are three Hamiltonian paths. The total lengths of these paths are as follows:

1 → 2 → 3: The total length is 6 + 21 = 27.

1 → 3 → 2: The total length is 15 + 21 = 36.

2 → 1 → 3: The total length is 6 + 15 = 21.

They are distinct, so the objective is met.

Sample Input 2

4

Sample Output 2

0 111 157 193
111 0 224 239
157 224 0 258
193 239 258 0

There are 12 Hamiltonian paths, with distinct total lengths.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    p,q,r=parseMap(split(readline()))
    println(min(p+q,q+r))
end
main()

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

Score : 100 points

Problem Statement

There are three airports A, B and C, and flights between each pair of airports in both directions.

A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.

Consider a route where we start at one of the airports, fly to another airport and then fly to the other airport.

What is the minimum possible sum of the flight times?

Constraints

1 \leq P,Q,R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

P Q R

Output

Print the minimum possible sum of the flight times.

Sample Input 1

1 3 4

Sample Output 1

4

The sum of the flight times in the route A \rightarrow B \rightarrow C: 1 + 3 = 4 hours

The sum of the flight times in the route A \rightarrow C \rightarrow C: 4 + 3 = 7 hours

The sum of the flight times in the route B \rightarrow A \rightarrow C: 1 + 4 = 5 hours

The sum of the flight times in the route B \rightarrow C \rightarrow A: 3 + 4 = 7 hours

The sum of the flight times in the route C \rightarrow A \rightarrow B: 4 + 1 = 5 hours

The sum of the flight times in the route C \rightarrow B \rightarrow A: 3 + 1 = 4 hours

The minimum of these is 4 hours.

Sample Input 2

3 2 3

Sample Output 2

5

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.


A = parse.(split(readline()))
sort!(A)
println(A[2]+A[1])


pqr = parse.([Int], split(readline()))
println(sum(pqr) - maximum(pqr))


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

function main()

N = parseInt(readline())

W = parseMap(split(readline()))

min_abs = 100000

for i in 1:N-1
    min_abs = min(min_abs, abs(sum(W[1:i]) - sum(W[i+1:N])))
end

println(min_abs)

end

main()

Score : 200 points

Problem Statement

We have N weights indexed 1 to N. The mass of the weight indexed i is W_i.

We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be the sum of the masses of the weights in the latter group.

Consider all possible such divisions and find the minimum possible absolute difference of S_1 and S_2.

Constraints

2 \leq N \leq 100

1 \leq W_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
W_1 W_2 ... W_{N-1} W_N

Output

Print the minimum possible absolute difference of S_1 and S_2.

Sample Input 1

3
1 2 3

Sample Output 1

0

If T = 2, S_1 = 1 + 2 = 3 and S_2 = 3, with the absolute difference of 0.

Sample Input 2

4
1 3 1 1

Sample Output 2

2

If T = 2, S_1 = 1 + 3 = 4 and S_2 = 1 + 1 = 2, with the absolute difference of 2. We cannot have a smaller absolute difference.

Sample Input 3

8
27 23 76 2 3 5 62 52

Sample Output 3

2


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

function main()
  N = readline() |> parseInt
  W = readline() |> split |> parseArray

  minimum(1:N) do i
    abs(sum(W[1:i]) - sum(W[i+1:end]))
  end |> println
end

main()


parseInt(x) = parse(Int,x)

function main()
  N = parseInt(readline())
  W = map(parseInt,split(readline()))
  S = zeros(Int64,N)
  for i=1:N
    S[i] = abs(sum(W[i+1:N])-sum(W[1:i]))
  end
  println(minimum(S))
end

main()


const MOD = Int(10^9+7)

function solve()
    N, M = parse.(Int, split(readline()))
    a = zeros(Int, M)
    for i = 1:M
        a[i] = parse(Int, readline())
    end

    if N == 1
        println(1)
        return 0
    end

    dp = zeros(Int, N)
    dp[1] = 1
    dp[2] = 2

    for i = 1:M dp[a[i]] = -1 end

    for i = 2:N
        println(dp)
        if dp[i] < 0 continue end

        if i + 1 <= N
            if dp[i+1] >= 0
                dp[i+1] = (dp[i+1] + dp[i])%MOD
            end
        end

        if i + 2 <= N
            if dp[i+2] >= 0
                dp[i+2] = (dp[i+2] + dp[i])%MOD
            end
        end
    end

    println(dp[N])
end

solve()

Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

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


function main()

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

  a = zeros(Int, 2M)
  for i in 1:M
    a[i] = parse(Int, readline()) + 1
  end

  ans = zeros(Int, 2N)
  num = 1

  for i in 1:N+1
    if i == 1
      ans[i] = 1
    elseif i == 2
      if a[num] == 2
        ans[i] = 0
        num += 1
      else
        ans[i] = 1
      end
    elseif a[num] == i
      num += 1
    else
      ans[i] = ans[i-1] + ans[i-2]
      ans[i] %= 1000000007
    end
  end

  println(ans[N+1])

end

main()


Score : 400 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares.

Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it.
The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and right.
In each direction, the beam will continue traveling until it hits a square occupied by an obstacle or it hits the border of the grid. It will light all the squares on the way, including the square on which the lamp is placed, but not the square occupied by an obstacle.

Snuke wants to maximize the number of squares lighted by the lamp.

You are given H strings S_i (1 \leq i \leq H), each of length W. If the j-th character (1 \leq j \leq W) of S_i is #, there is an obstacle on the square at the i-th row from the top and the j-th column from the left; if that character is ., there is no obstacle on that square.

Find the maximum possible number of squares lighted by the lamp.

Constraints

1 \leq H \leq 2,000

1 \leq W \leq 2,000

S_i is a string of length W consisting of # and ..

. occurs at least once in one of the strings S_i (1 \leq i \leq H).

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the maximum possible number of squares lighted by the lamp.

Sample Input 1

4 6
#..#..
.....#
....#.
#.#...

Sample Output 1

8

If Snuke places the lamp on the square at the second row from the top and the second column from the left, it will light the following squares: the first through fifth squares from the left in the second row, and the first through fourth squares from the top in the second column, for a total of eight squares.

Sample Input 2

8 8
..#...#.
....#...
##......
..###..#
...#..#.
##....#.
#...#...
###.#..#

Sample Output 2

13


Score : 100 points

Problem Statement

Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.

Print the answer in degrees, but do not print units.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print an integer representing the sum of the interior angles of a regular polygon with N sides.

Sample Input 1

3

Sample Output 1

180

The sum of the interior angles of a regular triangle is 180 degrees.

Sample Input 2

100

Sample Output 2

17640


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

function main()
  N = readline() |> parseInt
  a,b=zeros(Int,N-1),zeros(Int,N-1)
  for i in 1:N-1
    a[i],b[i]=readline() |> split |> parseArray
  end
  c=readline() |> split |> parseArray

  sort!(c)

  t=[[] for i in 1:N]
  for i in 1:N-1
    push!(t[a[i]], b[i])
    push!(t[b[i]], a[i])
  end

  d=zeros(Int,N)

  dfs(i, i_prev)=begin
    d[i]=pop!(c) #大きいものから取り出す
    for j in t[i]
      if j==i_prev
        continue
      end
      dfs(j, i)
    end
  end
  dfs(a[1], 0)

  M=sum(1:N-1)do i
    min(d[a[i]], d[b[i]])
  end
  println(M)

  print(d[1])
  for i in 2:N
    print(" ")
    print(d[i])
  end
  println()
end

main()

Score : 500 points

Problem Statement

You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N.
The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.

We will write a positive integer on each vertex in T and calculate our score as follows:

On each edge, write the smaller of the integers written on the two endpoints.

Let our score be the sum of the integers written on all the edges.

Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.

Constraints

1 \leq N \leq 10000

1 \leq a_i,b_i \leq N

1 \leq c_i \leq 10^5

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N

Output

Use the following format:

M
d_1 \ldots d_N

where M is the maximum possible score, and d_i is the integer to write on Vertex i.
d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N.
If there are multiple ways to achieve the maximum score, any of them will be accepted.

Sample Input 1

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

Sample Output 1

10
1 2 3 4 5

If we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written on the four edges will be 1,2,3,4, for the score of 10. This is the maximum possible score.

Sample Input 2

5
1 2
1 3
1 4
1 5
3141 59 26 53 59

Sample Output 2

197
59 26 3141 59 53

c_1,c_2,\ldots,c_N may not be pairwise distinct.


Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.

Find the maximum number of apple pies we can make with what we have now.

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

Print the maximum number of apple pies we can make with what we have.

Sample Input 1

1 3

Sample Output 1

3

We can first make one apple pie by simmering two of the three pieces of apple. Then, we can make two more by simmering the remaining piece and three more pieces obtained by cutting the whole apple.

Sample Input 2

0 1

Sample Output 2

0

We cannot make an apple pie in this case, unfortunately.

Sample Input 3

32 21

Sample Output 3

58


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

function main()
  A,P = readline() |> split |> parseMap
  A *= 3;
  result = (A + P)/2

  print(Int64(floor(result)))
end
main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    n=parseInt(readline())
    array=Tuple{String,Int,Int}[("",0,i) for i in 1:n]
    for i in 1:n
        s,p=split(readline())
        array[i]=(s,parseInt(p),i)
    end
    sort!(array,by=x->x[2],rev=true)
    sort!(array,by=x->x[1])
    for i in 1:n
        println(array[i][3])
    end
end
main()

Score : 200 points

Problem Statement

You have decided to write a book introducing good restaurants.
There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i.
No two restaurants have the same score.

You want to introduce the restaurants in the following order:

The restaurants are arranged in lexicographical order of the names of their cities.

If there are multiple restaurants in the same city, they are arranged in descending order of score.

Print the identification numbers of the restaurants in the order they are introduced in the book.

Constraints

1 ≤ N ≤ 100

S is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters.

0 ≤ P_i ≤ 100

P_i is an integer.

P_i ≠ P_j (1 ≤ i < j ≤ N)

Input

Input is given from Standard Input in the following format:

N
S_1 P_1
:
S_N P_N

Output

Print N lines. The i-th line (1 ≤ i ≤ N) should contain the identification number of the restaurant that is introduced i-th in the book.

Sample Input 1

6
khabarovsk 20
moscow 10
kazan 50
kazan 35
moscow 60
khabarovsk 40

Sample Output 1

3
4
6
1
5
2

The lexicographical order of the names of the three cities is kazan < khabarovsk < moscow. For each of these cities, the restaurants in it are introduced in descending order of score. Thus, the restaurants are introduced in the order 3,4,6,1,5,2.

Sample Input 2

10
yakutsk 10
yakutsk 20
yakutsk 30
yakutsk 40
yakutsk 50
yakutsk 60
yakutsk 70
yakutsk 80
yakutsk 90
yakutsk 100

Sample Output 2

10
9
8
7
6
5
4
3
2
1


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

function main()
	n = readline() |> parseInt
	s = String[]
	p = Int[]
	for i in 1:n
		a,b = readline() |> split
		push!(s,a)
		push!(p,parseInt(b))
	end
	t = String[]
	for i in 1:n
		if !(s[i] in t)
			push!(t,s[i])
		end
	end
	t = sort(t)
	d = Dict{String,Int}()
	for i in 1:length(t)
		d[t[i]] = i
	end
	a = Array{Int}(3,n)
	for i in 1:n
		a[1,i] = i
		a[2,i] = d[s[i]]
		a[3,i] = p[i]
	end
	a = sortcols(a,by=x->x[3],rev=true)
	a = sortcols(a,by=x->x[2])
	for i in 1:n
		println(a[1,i])
	end
end

main()


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

function main()
    n,m=parseMap(split(readline()))
    data=[parseMap(split(readline())) for i in 1:m]
    p=parseMap(split(readline()))
    ans=0
    for i in 0:(1<<n)-1
        pat=Vector{Int}()
        for j in 0:n-1
            if i & (1<<j) == 0
                # jは0-startだがJuliaの配列は1-indexedなので
                push!(pat,j+1)
            end
        end
        flg=true
        for j in 1:m
            res=0
            for k in 1:data[j][1]
                if data[j][1+k] in pat
                    res+=1
                end
            end
            if res%2!=p[j]
                flg=false
            end
        end
        if flg
            ans+=1
        end
    end
    println(ans)
end
main()

Score : 300 points

Problem Statement

We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.

Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

s_{ia} \neq s_{ib} (a \neq b)

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

Sample Input 2

2 3
2 1 2
1 1
1 2
0 0 1

Sample Output 2

0

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an even number of switches that are "on" among the following: Switch 1.

Bulb 3 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

Switch 1 has to be "off" to light Bulb 2 and Switch 2 has to be "on" to light Bulb 3, but then Bulb 1 will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print 0.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


N,M=map(x->parse(Int,x),split(readline()))
s=zeros(Int,M,N)
for i=1:M
	t=map(x->parse(Int,x),split(readline()))
	for j=t[2:end]
		s[i,j]=1
	end
end
p=map(x->parse(Int,x),split(readline()))
ans=0
for i=0:(1<<N)-1
	flag=true
	for j=1:M
		now=p[j]
		for k=1:N
			now+=(i>>(k-1))%2*s[j,k]
		end
		if now%2!=0
			flag=false
		end
	end
	ans+=flag
end
println(ans)


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

function refresh(st::Array{Int,1},lt::Array{Int,1},x,rt)
	if x<=rt
		st[x<<1] = min(st[x<<1],lt[x])
		st[x<<1+1] = min(st[x<<1+1],lt[x])
		lt[x] = 10^18
	end
end

function main()
	n,q = readline() |> split |> parseMap
	a = Tuple{Int,Int,Int}[(0,0,0) for i in 1:n]
	d = Dict{Int,Int}()
	for i in 1:n
		x,y,z = readline() |> split |> parseMap
		a[i] = (x-z,y-z-1,z)
		if y-z-1>-1
			d[max(x-z,0)]=1
			d[max(y-z-1,0)]=1
		end
	end
	b = zeros(Int,q)
	for i in 1:q
		b[i]=readline() |> parseInt
		d[b[i]]=1
	end
	m = length(d)
	tl = zeros(Int,m)
	z = 1
	for i in keys(d)
		tl[z]=i
		z += 1
	end
	tl = sort(tl)
	for i in 1:m
		d[tl[i]] = i
	end
	k = 0
	while 2^k<m
		k += 1
	end
	rt=2^k-1
	st = 10^18*ones(Int,2^(k+1)-1)
	lt = 10^18*ones(Int,2^(k+1)-1)
	for iter in 1:n
		if a[iter][2]>-1
			ll = d[max(a[iter][1],0)]
			rr = d[max(a[iter][2],0)]
			v = a[iter][3]
			rp = Int[]
			rw = Tuple{Int,Int}[]
			for i in k:-1:0
				l = (rt+ll)>>i
				r = (rt+rr)>>i
				push!(rp,l)
				if l<r
					push!(rp,r)
				end
				if r-l>1
					if l%2==0
						push!(rw,(l+1,i))
					end
					if r%2==1
						push!(rw,(r-1,i))
					end
				end
			end
			for i in rp
				refresh(st,lt,i,rt)
			end
			for i in rw
				lt[i[1]]=min(v,lt[i[1]])
				st[i[1]]=min(v,st[i[1]])
			end
			for i in length(rp):-1:1
				if rp[i]<=rt
					st[rp[i]]=min(st[rp[i]<<1],st[rp[i]<<1+1])
				else
					st[rp[i]]=min(st[rp[i]],v)
				end
			end
		end
	end
	for i in 1:2^(k+1)-1
		refresh(st,lt,i,rt)
	end

end
main()

Score : 500 points

Problem Statement

There is an infinitely long street that runs west to east, which we consider as a number line.

There are N roadworks scheduled on this street.
The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5.

Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point.

Find the distance each of the Q people will walk.

Constraints

All values in input are integers.

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

0 \leq S_i < T_i \leq 10^9

1 \leq X_i \leq 10^9

0 \leq D_1 < D_2 < ... < D_Q \leq 10^9

If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap.

Input

Input is given from Standard Input in the following format:

N Q
S_1 T_1 X_1
:
S_N T_N X_N
D_1
:
D_Q

Output

Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever.

Sample Input 1

4 6
1 3 2
7 13 10
18 20 13
3 4 2
0
1
2
3
5
8

Sample Output 1

2
2
10
-1
13
-1

The first person starts coordinate 0 at time 0 and stops walking at coordinate 2 when reaching a point blocked by the first roadwork at time 2.

The second person starts coordinate 0 at time 1 and reaches coordinate 2 at time 3. The first roadwork has ended, but the fourth roadwork has begun, so this person also stops walking at coordinate 2.

The fourth and sixth persons encounter no roadworks while walking, so they walk forever. The output for these cases is -1.


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

function main()
	n = readline() |> parseInt
	s = readline() |> split |> parseMap
	m = (n-1)>>1+1
	a = Int[]
	k = 1
	while k<=sqrt(n-m-1)
		if k*k==(n-m-1)
			push!(a,k)
		elseif (n-m-1)%k==0
			push!(a,k)
			push!(a,div(n-m-1,k))
		end
		k += 1
	end
	v = 0
	for i in a
		l = zeros(Int,n>>1)
		r = zeros(Int,n>>1)
		for j in 1+i:i:n>>1
			l[j] = l[j-i]+s[j]
			r[j] = r[j-i]+s[n-j+1]
		end
		for j in 1:i:n>>1
			v = max(v,l[j]+r[j],l[n>>1]-l[n>>1-j]+r[n>>1]-r[n>>1-j])
		end
		v = max(v,l[n>>1]+r[n>>1])
	end
	println(v)
end

main()

Score : 600 points

Problem Statement

There is an infinitely large pond, which we consider as a number line.
In this pond, there are N lotuses floating at coordinates 0, 1, 2, ..., N-2 and N-1.
On the lotus at coordinate i, an integer s_i is written.

You are standing on the lotus at coordinate 0. You will play a game that proceeds as follows:

1. Choose positive integers A and B. Your score is initially 0.

2. Let x be your current coordinate, and y = x+A. The lotus at coordinate x disappears, and you move to coordinate y.

If y = N-1, the game ends.

If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.

If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.

3. Let x be your current coordinate, and y = x-B. The lotus at coordinate x disappears, and you move to coordinate y.

If y = N-1, the game ends.

If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.

If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.

4. Go back to step 2.

You want to end the game with as high a score as possible.
What is the score obtained by the optimal choice of A and B?

Constraints

3 \leq N \leq 10^5

-10^9 \leq s_i \leq 10^9

s_0=s_{N-1}=0

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
s_0 s_1 ...... s_{N-1}

Output

Print the score obtained by the optimal choice of A and B.

Sample Input 1

5
0 2 5 1 0

Sample Output 1

3

If you choose A = 3 and B = 2, the game proceeds as follows:

Move to coordinate 0 + 3 = 3. Your score increases by s_3 = 1.

Move to coordinate 3 - 2 = 1. Your score increases by s_1 = 2.

Move to coordinate 1 + 3 = 4. The game ends with a score of 3.

There is no way to end the game with a score of 4 or higher, so the answer is 3. Note that you cannot land the lotus at coordinate 2 without drowning later.

Sample Input 2

6
0 10 -7 -4 -13 0

Sample Output 2

0

The optimal strategy here is to land the final lotus immediately by choosing A = 5 (the value of B does not matter).

Sample Input 3

11
0 -4 0 -99 31 14 -15 -39 43 18 0

Sample Output 3

59


A,B = parse.(split(readline()))

if A > 12
  println(B)
elseif  A > 5
  println(Int(B/2))
else
  println(0)
end

Score : 100 points

Problem Statement

Takahashi, who is A years old, is riding a Ferris wheel.

It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is 12 years old, and the cost of the Ferris wheel is the half of 100 yen, that is, 50 yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is 0 years old, and he can ride the Ferris wheel for free.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    a,b=parseMap(split(readline()))
    if a>=13
        println(b)
    elseif a>=6
        println(div(b,2))
    else
        println(0)
    end
end
main()


lines=readlines(open("/dev/fd/0"))
input()=shift!(lines)
int(s::String)=parse(Int,s)
intSub(s::SubString{String})=parse(Int,s)
intLine(s::Array{SubString{String},1})=map(intSub,s)
function main()
  a,b=intLine(split(input()))
  println(ifelse(a>12,b,ifelse(a>5,floor(Int,b/2),0)))
end
main()


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

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

  result = if A>=13
    B
  elseif A>=6
    div(B,2)
  else
    0
  end

  println(result)
end

main()


parseint(x) = parse(Int, x)
parseintmap(x::Array{SubString{String},1}) = map(parseint, x)

function solve(r::Int, d::Int, x::Int)
    for _ in 1:10
        x = r*x-d
        println(x)
    end
end

function main()
    r, d, x= readline() |> split |> parseintmap
    solve(r, d, x)
end

main()

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


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

function main()
	r,d,x = readline() |> split |> parseMap
	for i in 1:10
		x = r*x-d
		println(x)
	end
end

main()


parseInt(x) = parse(Int,x)

function main()
  (N,M) = map(parseInt, split(readline()))
  L = zeros(Int,M)
  R = zeros(Int,M)
  for i = 1:M
    (L[i],R[i]) = map(parseInt, split(readline()))
  end
  l = maximum(L)
  r = minimum(R)
  println(max(r-l+1,0))
end

main()

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


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

function main()
  N,M = readline() |> split |> parseArray
  L,R=zeros(M),zeros(M)
  for i in 1:M
    L[i],R[i] = readline() |> split |> parseArray
  end

  c=0
  for i in 1:M
    if L[i]==1&&R[i]>=M
      c+=1
    end
  end

  println(c)
end

main()


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

function main()
  N,M = readline() |> split |> parseArray
  A = readline() |> split |> parseArray
  sort!(A)
  D::Array{Int64} = []

  roop = 0
  for line in readlines()
    B,C = line |> split |> parseArray
    for i = 1:B
      push!(D,C)
      roop += 1
      if roop == length(A)
        break
      end
    end
    if roop == length(A)
        break
    end
  end

  if length(D) < length(A)
    for i = length(D) + 1:length(A)
      push!(D,0)
    end
  end

  sort!(D,rev=true)

  for i = 1:length(A)
    if A[i] < D[i]
      A[i] = D[i]
    else
      break
    end
  end

  print(sum(A))
end
main()

Score : 400 points

Problem Statement

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

By replacing the integer on the second card with 5, the sum of the integers written on the three cards becomes 5 + 5 + 4 = 14, which is the maximum result.

Sample Input 2

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Sample Output 4

10000000001

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


let
  N, M = map(x -> parse(Int, x), split(readline()))
  A = map(x -> parse(Int, x), split(readline()))
  change(A,term) = for i=1:term[1] if A[i] <= term[2] A[i] = term[2] else break end end
  while (M=M-1) >= 0 sort!(A); change(A, map(x -> parse(Int, x), split(readline()))) end
  print(sum(A))
end


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

function heap(a::Array{Int,1})
	h = [a[1]]
	for i in 2:length(a)
		hpush(h,a[i])
	end
	h
end

function hpush(h::Array{Int,1},x)
	push!(h,x)
	l = length(h)
	if l>1
		k = l>>1
		while h[k]>x&&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{Int,1})
	x = h[1]
	z = pop!(h)
	if !isempty(h)
		h[1] = z
		k = 1
		l = length(h)
		while k <= l
			if 2*k>l
				break
			elseif 2*k+1>l
				if h[2*k]>=z
					break
				else
					tmp = h[2*k]
					h[2*k] = z
					h[k] = tmp
					k = 2*k
				end
			else
				if h[2*k]>=z&&h[2*k+1]>=z
					break
				else
					t = h[2*k]<h[2*k+1]?2*k:2*k+1
					tmp = h[t]
					h[t] = z
					h[k] = tmp
					k = t
				end
			end
		end
	end
	x
end

function heapb(a::Array{Int,1})
	h = [a[1]]
	for i in 2:length(a)
		hpush(h,a[i])
	end
	h
end

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

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

function main()
	q = readline() |> parseInt
	l = Int[]
	ls = 0
	lt = 0
	r = Int[]
	rs = 0
	rt = 0
	y = 0
	for i in 1:q
		a = readline() |> split |> parseMap
		if a[1] == 1
			y += a[3]
			if ls == 0
				push!(l,a[2])
				ls += 1
				lt += a[2]
			elseif rs == 0
				if l[1]<a[2]
					push!(r,a[2])
				else
					push!(r,pop!(l))
					push!(l,a[2])
				end
				rs += 1
				rt += a[2]
			else
				lm = hpopb(l)
				rm = hpop(r)
				if ls==rs
					ls += 1
					if rm<a[2]
						hpush(r,a[2])
						hpushb(l,lm)
						hpushb(l,rm)
						lt += rm
						rt += a[2]-rm
					else
						hpush(r,rm)
						hpushb(l,lm)
						hpushb(l,a[2])
						lt += a[2]
					end
				else
					rs += 1
					if a[2]<lm
						hpushb(l,a[2])
						hpush(r,lm)
						hpush(r,rm)
						lt += a[2]-lm
						rt += lm
					else
						hpushb(l,lm)
						hpush(r,rm)
						hpush(r,a[2])
						rt += a[2]
					end
				end
			end
		else
			println(l[1], " ",-l[1]*ls+l[1]*rs+lt-rt+y)
		end
	end
end

main()

Score : 600 points

Problem Statement

There is a function f(x), which is initially a constant function f(x) = 0.

We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:

An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).

An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.

We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.

Constraints

All values in input are integers.

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

-10^9 \leq a, b \leq 10^9

The first query is an update query.

Input

Input is given from Standard Input in the following format:

Q
Query_1
:
Query_Q

See Sample Input 1 for an example.

Output

For each evaluation query, print a line containing the response, in the order in which the queries are given.

The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.

Sample Input 1

4
1 4 2
2
1 1 -8
2

Sample Output 1

4 2
1 -3

In the first evaluation query, f(x) = |x - 4| + 2, which attains the minimum value of 2 at x = 4.

In the second evaluation query, f(x) = |x - 1| + |x - 4| - 6, which attains the minimum value of -3 when 1 \leq x \leq 4. Among the multiple values of x that minimize f(x), we ask you to print the minimum, that is, 1.

Sample Input 2

4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2

Sample Output 2

-1000000000 3000000000


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

function main()
  N, K = readline() |> split |> parseArray
  S = readline() |> parseInt
  result = S[1:K-1] * lowercase(S[K:K]) * S[K+1:end]
  println(result)
end

main()

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


let
  N, K = map(x -> parse(Int, x), split(readline()))
  function Σ(n,K)
    sum = 0
    for i = 1:n
      if i == K break end
      sum += (1/n) * (1/2)^ceil(pow)
    end
    return sum
  end
  print(Σ(N, K))
end

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


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

function main()
  N = readline() |> parseInt
  e = [Tuple{Int, Int}[] for i in 1:N]
  for i in 1:N - 1
    u, v, w = readline() |> split |> parseArray
    push!(e[u], (v, w))
    push!(e[v], (u, w))
  end

  a = zeros(N)
  a[1] = 1

  function dfs(u)
    for (v, w) in e[u]
      if a[v] == 0
        a[v] = -((w%2)*2-1) * a[u]
        dfs(v)
      end
    end
  end

  dfs(1)

  for j in 1:N
    println(a[j] == 1 ? 1 : 0)
  end
end

main()

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

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

Sample Output 2

1
0
1
0
1


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

function main()
  N = readline() |> parseInt
  e = [Tuple{Int, Int}[] for i in 1:N]
  for i in 1:N - 1
    u, v, w = readline() |> split |> parseArray
    push!(e[u], (v, w))
    push!(e[v], (u, w))
  end

  a = zeros(N)
  ux = [1]
  a[ux[end]] = 1
  while true
    @label loop
    u = ux[end]
    for (v, w) in e[u]
      if a[v] == 0
        a[v] = -((w%2)*2-1) * a[u]
        push!(ux, v)
        @goto loop
      end
    end
    pop!(ux)
    if length(ux) == 0
      break
    end
  end

  for j in 1:N
    println(a[j] == 1 ? 1 : 0)
  end
end

main()


function main()
	lines=readlines()
	N,M=map(x->parse(Int,x),split(shift!(lines)))
	G=[Array{Int}(0) for _=1:N]
	for s=lines
		u,v,w=map(x->parse(Int,x),split(s))
		push!(G[u],v)
		push!(G[v],u)
	end
	used=[false for _=1:N]
	function dfs(u)
		used[u]=true
		for v=G[u]
			if !used[v]
				dfs(v)
			end
		end
	end
	ans=0
	for i=1:N
		if !used[i]
			dfs(i)
			ans+=1
		end
	end
	println(ans)
end
main()

Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


function main()
  RR,GG,BB,N=map(x->parse(Int,x),split(readline()))
  num=[RR,GG,BB]
  R=maximum(num)
  B=minimum(num)
  G=RR+GG+BB-R-B
  ans=0
  if R==G && G==B && N%R==0
    temp=N/R
    ans=Int(floor((temp+1)*(temp+2)/2))
  elseif R==G || G==B
    for rr=N:-R:0
      if rr%B==0
        ans+=Int(rr/B)+1
      end
    end
  else
    for rr=N:-R:0,rg=rr:-G:0
      ans+=rg%B==0
    end
  end
  println(ans)
end
main()

Score : 200 points

Problem Statement

Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:

Red boxes, each containing R red balls

Green boxes, each containing G green balls

Blue boxes, each containing B blue balls

Snuke wants to get a total of exactly N balls by buying r red boxes, g green boxes and b blue boxes.
How many triples of non-negative integers (r,g,b) achieve this?

Constraints

All values in input are integers.

1 \leq R,G,B,N \leq 3000

Input

Input is given from Standard Input in the following format:

R G B N

Output

Print the answer.

Sample Input 1

1 2 3 4

Sample Output 1

4

Four triples achieve the objective, as follows:

(4,0,0)

(2,1,0)

(1,0,1)

(0,2,0)

Sample Input 2

13 1 4 3000

Sample Output 2

87058


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

function main()
  # R, G, B, N = map(parseInt, split(readline()))
  R, G, B, N = readline() |> split |> parseArray

  # box = sort([R,G,B],rev=true)
  c = 0
  # f(i::Int, j::Int)::Bool = (N-R*i-G*j)%B==0
  f(i::Int, j::Int)::Bool = mod(N-R*i-G*j,B)==0
  # g(i::Int)::Int=div(N-box[1]*i,box[2])
  g(i::Int)::Int=floor(Int, (N-R*i)/G)
  for i=0:div(N,R)
    for j=0:g(i)
      if f(i, j)
        c += 1
      end
    end
  end
  println(c)
end

main()


parseInt(x) = parse(Int, x)

function main()
  R, G, B, N = map(parseInt, split(readline()))

  box = sort([R,G,B],rev=true)
  c = 0
  f(i::Int, j::Int)::Bool = (N-box[1]*i-box[2]*j)%box[3]==0
  g(i::Int)::Int=div(N-box[1]*i,box[2])
  for i=0:div(N,box[1])
    for j=0:g(i)
      if f(i, j)
        c += 1
      end
    end
  end
  println(c)
end

main()


stoi(s::String) = parse(Int, s)

function solve()
    R, G, B, N = map(stoi, split(readline()))

    ans = 0
    for r in 0:div(N, R), g in 0:div(N, G)
        t = N - R*r - G*g
        t < 0 && continue
        mod(t, B) == 0 && (ans += 1)
    end

    println(ans)

    return nothing
end

solve()


stoi(s) = parse(Int, s)

function solve()
    R, G, B, N = map(stoi, split(chomp(readline())))

    ans = 0
    for r in 0:div(N, R), g in 0:div(N, G)
        b =  div(N - R*r - G*g, B)
        b < 0 && continue
        if R*r + G*g + B*b == N
            ans += 1
        end
    end

    println(ans)

    return nothing
end

solve()


parseInt(x) = parse(Int, x)

function main()
  N = readline() |> parseInt
  s = Array{String}(N)
  for i=1:N
    s[i]=readline()|>strip
  end

  # w=count(b->b,map(ss->contains(ss,"AB"),s))
  w=sum(map(ss->(split(ss,"AB")|>length)-1,s))
  x=count(b->b,map(ss->ss[1]!='B'&&ss[end]=='A',s))
  y=count(b->b,map(ss->ss[1]=='B'&&ss[end]!='A',s))
  z=count(b->b,map(ss->ss[1]=='B'&&ss[end]=='A',s))
  # println([x,y,z,w])
  result=z-1+(x>=1?1:0)+(y>=1?1:0)+((x>=1&&y>=1)?min(x-1,y-1):0)+w

  println(result)
end

main()

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


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

function main()
	n = readline() |> parseInt
	s = ["" for i in 1:n]
	for i in 1:n
		s[i] = chomp(readline())
	end
	k = 0
	h = 0
	t = 0
	b = 0
	for i in 1:n
		l = length(s[i])
		for j in 2:l
			if s[i][j-1] == 'A' && s[i][j] == 'B'
				k += 1
			end
		end
		if s[i][1] == 'B' && s[i][l] == 'A'
			b += 1
		elseif s[i][1] == 'B'
			h += 1
		elseif s[i][l] == 'A'
			t += 1
		end
	end
	if b >= h && b >= t
		k += t+h+b-min(t,h)-1
	elseif b<= h && b <= t
		k += 2*b + min(t-b,h-b)
	else
		k += 2*min(t,h) + b-min(t,h)
	end
	println(k)
end
main()


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

function main()
	n = readline() |> parseInt
	s = ["" for i in 1:n]
	for i in 1:n
		s[i] = chomp(readline())
	end
	k = 0
	h = 0
	t = 0
	b = 0
	for i in 1:n
		l = length(s[i])
		for j in 2:l
			if s[i][j-1] == 'A' && s[i][j] == 'B'
				k += 1
			end
		end
		if s[i][1] == 'B' && s[i][l] == 'A'
			b += 1
		elseif s[i][1] == 'B'
			h += 1
		elseif s[i][l] == 'A'
			t += 1
		end
	end
	if h+b>t||b+t>h
		z = max(min(h+b,t),min(h,b+t))
		k += z + b-abs(h-t)
	elseif h+b<=t
		k += h+b
	elseif b+t<=h
		k += b+t
	end
	println(k)
end
main()


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

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

  result=0
  # for i in 1:N
  #   N÷i!=N%i&&continue
  #   result+=i
  # end
  for i in 1:floor(Int, sqrt(N))
    (N==i^2 || (N-i)%i!=0) && continue
    result+=(N-i)÷i
  end
  println(result)
end

main()

Score : 500 points

Problem Statement

Snuke received a positive integer N from Takahashi.
A positive integer m is called a favorite number when the following condition is satisfied:

The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: 3 and 7. Print the sum of these, 10.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


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

function main()
	h,w,n = readline() |> split |> parseMap
	y,x = readline() |> split |> parseMap
	s = chomp(readline())
	t = chomp(readline())
	sl = zeros(Int,n)
	sr = zeros(Int,n)
	su = zeros(Int,n)
	sd = zeros(Int,n)
	tl = zeros(Int,n)
	tr = zeros(Int,n)
	tu = zeros(Int,n)
	td = zeros(Int,n)
	if s[1] == 'L'
		sl[1] = 1
	elseif s[1] == 'R'
		sr[1] = 1
	elseif s[1] == 'U'
		su[1] = 1
	else
		sd[1] = 1
	end
	if t[1] == 'L' && x+sr[1]>1
		tl[1] = 1
	elseif t[1] == 'R' && x-sl[1]<w
		tr[1] = 1
	elseif t[1] == 'U' && y+sd[1]>1
		tu[1] = 1
	elseif t[1] == 'D' && y-su[1]<h
		td[1] = 1
	end
	for i in 2:n
		sl[i] = sl[i-1]
		sr[i] = sr[i-1]
		su[i] = su[i-1]
		sd[i] = sd[i-1]
		tl[i] = tl[i-1]
		tr[i] = tr[i-1]
		tu[i] = tu[i-1]
		td[i] = td[i-1]
		if s[i] == 'L'
			sl[i] += 1
		elseif s[i] == 'R'
			sr[i] += 1
		elseif s[i] == 'U'
			su[i] += 1
		else
			sd[i] += 1
		end
		if t[i] == 'L' && x+sr[i]-tl[i] > 1
			tl[i] += 1
		elseif t[i] == 'R' && x-sl[i]+tr[i] < w
			tr[i] += 1
		elseif t[i] == 'U' && y+sd[i]-tu[i] < 1
			tu[i] += 1
		elseif t[i] == 'D' && y-su[i]+td[i] < h
			td[i] += 1
		end
	end
	flg = 0
	if x-sl[1] < 1 || x+sr[1] > w || y-sd[1]<0 || y+su[1] > h
		flg = 1
	else
		for i in 2:n
			if x-sl[i]+tr[i-1] < 1 || x+sr[i]-tl[i-1] > w || y-su[i]+td[i-1] < 0 || y+sd[i]-tu[i-1]>h
				flg = 1
				break
			end
		end
	end
	println(flg == 1?"NO":"YES")
end
main()

Score : 600 points

Problem Statement

We have a rectangular grid of squares with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.
On this grid, there is a piece, which is initially placed at square (s_r,s_c).

Takahashi and Aoki will play a game, where each player has a string of length N.
Takahashi's string is S, and Aoki's string is T. S and T both consist of four kinds of letters: L, R, U and D.

The game consists of N steps. The i-th step proceeds as follows:

First, Takahashi performs a move. He either moves the piece in the direction of S_i, or does not move the piece.

Second, Aoki performs a move. He either moves the piece in the direction of T_i, or does not move the piece.

Here, to move the piece in the direction of L, R, U and D, is to move the piece from square (r,c) to square (r,c-1), (r,c+1), (r-1,c) and (r+1,c), respectively. If the destination square does not exist, the piece is removed from the grid, and the game ends, even if less than N steps are done.

Takahashi wants to remove the piece from the grid in one of the N steps.
Aoki, on the other hand, wants to finish the N steps with the piece remaining on the grid.
Determine if the piece will remain on the grid at the end of the game when both players play optimally.

Constraints

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

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

1 \leq s_r \leq H

1 \leq s_c \leq W

|S|=|T|=N

S and T consists of the four kinds of letters L, R, U and D.

Input

Input is given from Standard Input in the following format:

H W N
s_r s_c
S
T

Output

If the piece will remain on the grid at the end of the game, print YES; otherwise, print NO.

Sample Input 1

2 3 3
2 2
RRL
LUD

Sample Output 1

YES

Here is one possible progress of the game:

Takahashi moves the piece right. The piece is now at (2,3).

Aoki moves the piece left. The piece is now at (2,2).

Takahashi does not move the piece. The piece remains at (2,2).

Aoki moves the piece up. The piece is now at (1,2).

Takahashi moves the piece left. The piece is now at (1,1).

Aoki does not move the piece. The piece remains at (1,1).

Sample Input 2

4 3 5
2 2
UDRRR
LLDUD

Sample Output 2

NO

Sample Input 3

5 6 11
2 1
RLDRRUDDLRL
URRDRLLDLRD

Sample Output 3

NO


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

function main()
	h,w,n = readline() |> split |> parseMap
	y,x = readline() |> split |> parseMap
	s = chomp(readline())
	t = chomp(readline())
	sl = zeros(Int,n)
	sr = zeros(Int,n)
	su = zeros(Int,n)
	sd = zeros(Int,n)
	tl = zeros(Int,n)
	tr = zeros(Int,n)
	tu = zeros(Int,n)
	td = zeros(Int,n)
	if s[1] == 'L'
		sl[1] = 1
	elseif s[1] == 'R'
		sr[1] = 1
	elseif s[1] == 'U'
		su[1] = 1
	else
		sd[1] = 1
	end
	if t[1] == 'L' && x>1
		tl[1] = 1
	elseif t[1] == 'R' && x<w
		tr[1] = 1
	elseif t[1] == 'U' && y>1
		tu[1] = 1
	else
		td[1] = 1 && y<h
	end
	for i in 2:n
		sl[i] = sl[i-1]
		sr[i] = sr[i-1]
		su[i] = su[i-1]
		sd[i] = sd[i-1]
		tl[i] = tl[i-1]
		tr[i] = tr[i-1]
		tu[i] = tu[i-1]
		td[i] = td[i-1]
		if s[i] == 'L'
			sl[i] += 1
		elseif s[i] == 'R'
			sr[i] += 1
		elseif s[i] == 'U'
			su[i] += 1
		else
			sd[i] += 1
		end
		if t[i] == 'L' && x+sr[i]-tl[i] > 1
			tl[i] += 1
		elseif t[i] == 'R' && x-sl[i]+tr[i] < w
			tr[i] += 1
		elseif t[i] == 'U' && y+sd[i]-tu[i] < 1
			tu[i] += 1
		elseif t[i] == 'D' && y-su[i]-td[i] < h
			td[i] += 1
		end
	end
	flg = 0
	if x-sl[1] < 1 || x+sr[1] > w || y-sd[1]<0 || y+su[1] > h
		flg = 1
	else
		for i in 2:n
			if x-sl[i]+tr[i-1] < 1 || x+sr[i]-tl[i-1] > w || y-sd[i]+tu[i-1] < 0 || y+su[i]-td[i-1]>h
				flg = 1
				break
			end
		end
	end
	println(flg == 1?"NO":"YES")
end
main()


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

function bfsTree(e::Array{Array{Int,1}},p)
	n=length(e)
	vst=zeros(Int,n)
	vst.-=1
	vst[p]=0
	vc=1
	stack=Int[]
	for i in 1:length(e[p])
		push!(stack,e[p][i])
		vst[e[p][i]]=1
		vc+=1
	end
	bef=0
	now=p
	while !isempty(stack)&&vc<n
		now=shift!(stack)
		for i in 1:length(e[now])
			if vst[e[now][i]]<0
				push!(stack,e[now][i])
				vst[e[now][i]]=vst[now]+1
				vc+=1
			end
		end
	end
	vst
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
	f = bfsTree(e,1)
	u = indmax(f)
	g = bfsTree(e,u)
	d = maximum(g)
	println(d%3==1?"Second":"First")
end
main()

Score : 800 points

Problem Statement

Takahashi and Aoki will play a game on a tree.
The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.

At the beginning of the game, each vertex contains a coin.
Starting from Takahashi, he and Aoki will alternately perform the following operation:

Choose a vertex v that contains one or more coins, and remove all the coins from v.

Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.

The player who becomes unable to play, loses the game.
That is, the player who takes his turn when there is no coin remaining on the tree, loses the game.
Determine the winner of the game when both players play optimally.

Constraints

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

1 \leq a_i, b_i \leq N

a_i \neq b_i

The graph given as input is a tree.

Input

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}

Output

Print First if Takahashi will win, and print Second if Aoki will win.

Sample Input 1

3
1 2
2 3

Sample Output 1

First

Here is one possible progress of the game:

Takahashi removes the coin from Vertex 1. Now, Vertex 1 and Vertex 2 contain one coin each.

Aoki removes the coin from Vertex 2. Now, Vertex 2 contains one coin.

Takahashi removes the coin from Vertex 2. Now, there is no coin remaining on the tree.

Aoki takes his turn when there is no coin on the tree and loses.

Sample Input 2

6
1 2
2 3
2 4
4 6
5 6

Sample Output 2

Second

Sample Input 3

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

Sample Output 3

First


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

Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


parseInt(x) = parse(Int,x)
function main()
    a, b ,t = map(parseInt, split(readline()))
    #a, b ,t = [3 5 7]
    println(Int64(floor(t/a )*b))
end
main()


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

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


function main()
    readline() # skip
    input = readdlm(STDIN, Int)
    V = input[1, :]
    C = input[2, :]

    Z = (V - C)
    result = sum(Z[Z .> 0])
    println(result)
end

main()


n=parse(Int,readline())
a=map(x->parse(Int,x),split(readline()))
b=map(x->parse(Int,x),split(readline()))
s=0
for i=1:n
	if a[i]>b[i]
		s+=a[i]-b[i]
	end
end
println(s)


N=parse(Int,readline())
A=map(x->parse(Int,x),split(readline()))
sort!(A)
for i=1:2:N-1
	if A[i]+A[i+1]<0
		A[i]*=-1
		A[i+1]*=-1
	end
end
println(+(A...))

Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

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


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

function main()
	n = readline() |> parseInt
	s = chomp(readline())
	c = 0
	cc = 0
	for i in 0:n-1
		if s[n-i] == '.'
			cc = n-i
			break
		end
	end
	for i in 1:cc
		if s[i] == '.'
			c += 1
		end
	end
	if c == cc
		println(0)
	else
		println(min(c,cc-c)
	end
end
main()

Score : 300 points

Problem Statement

There are N stones arranged in a row. Every stone is painted white or black.
A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


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

function main()
    a,b,c=parseMap(split(readline()))
    if a<=c<=b
        println("Yes")
    else
        println("No")
    end
end
main()

Score : 100 points

Problem Statement

There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively.
Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Constraints

0\leq A,B,C\leq 100

A, B and C are distinct integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Sample Input 1

3 8 5

Sample Output 1

Yes

We pass the coordinate 5 on the straight way from the house at coordinate 3 to the house at coordinate 8.

Sample Input 2

7 3 1

Sample Output 2

No

Sample Input 3

10 2 4

Sample Output 3

Yes

Sample Input 4

31 41 59

Sample Output 4

No


let
  N = parse(Int, readline())
  S = readline()
  K = parse(Int, readline())

  target = S[K:K]
  ret = ""

  for s in S
    s = string(s)
    if s == target
      ret *= s
    else
      ret *= "*"
    end
  end

  println(ret)
end

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters, and an integer K.
Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Constraints

1 \leq K \leq N\leq 10

S is a string of length N consisting of lowercase English letters.

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of S is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


readline_() = readline() |> chomp
# a b c d e -> Array{SubString{String},1}
readline_array_string() = readline() |> chomp |> split
# 1 2 3 4 5 -> Array{Int64, 1}
readline_array_int() = [parse(Int, x) for x in readline() |> chomp |> split]
read_int() = parse(Int, readline() |> chomp)

function omit(str)
    count = 0
    l = length(str)
    ind = Int[]
    i = 1
    while i <= l-1
        if str[i:i+1] == "#."
            count += 1
            i += 2
        else
            push!(ind, i)
            i += 1
        end
    end

    if l >= 2
        if str[l-1:l] != "#."
            push!(ind, l)
        end
    end

    if count == 0
        return 0
    else
        count += omit(str[ind])
    end
    return count
end

n = read_int()
str = readline_()
value = omit(str)
print(value)


# abcde -> String
readline_() = readline() |> chomp
# a b c d e -> Array{SubString{String},1}
readline_array_string() = readline() |> chomp |> split
# 1 2 3 4 5 -> Array{Int64, 1}
readline_array_int() = [parse(Int, x) for x in readline() |> chomp |> split]
read_int() = parse(Int, readline() |> chomp)

function main(n, str)
    firstblack = 0
    for (i, s) in enumerate(str)
        if s == '#'
            firstblack = i
            break
        end
    end

    if firstblack == 0
        print(0)
        return
    end
    count = 0
    for i = firstblack:n
        if str[i] == '#'
            count += 1
        end
    end
    m = n - firstblack + 1
    a = m - count
    print(min(a, count))
end

n = read_int()
str = readline_()

main(n, str)


a,b=map(x->parse(Int,x),split(readline()))
if a==b
  print(a+b)
else
  print(max(a,b)*2-1)
end

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


n = parse(Int, strip(readline()))
A = map(x->parse(Int, x), split(readline()))
cnt = 0
for i in 1:length(A)
  cnt += all(A[1:i-1] .<= A[i])
end
println(cnt)

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


x=[Int(y)%2 for y=readline()|>chomp]
s=(1:length(x)).%2
min(sum.(abs.([s-x,1.-s-x]))...)|>show

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


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

function main()
	n,k = readline() |> split |> parseMap
	s = chomp(readline())
	a = Int[]
	b = Int[0]
	f = s[1]=='0'?0:1
	t = 1
	for i in 2:n
		if s[i-1] != s[i]
			push!(a,f)
			f = f==0?1:0
			push!(b,t)
			b[length(b)] += b[length(b)-1]
			t = 1
		else
			t += 1
		end
	end
	if t != 0
		push!(a,f)
		push!(b,t)
		b[length(b)] += b[length(b)-1]
	end
	l = length(a)
	if l == 1
		println(n)
	else
		m = 0
		if k%2 == 0
			for i in 1:l
				if a[i] == 1
					x = b[min(i+k+1,l+1)]-b[max(i-k,1)]
					m = max(m,x)
				end
			end
		else
			for i in 1:l
				if a[i] == 0
					x = b[min(i+k+1,l+1)]-b[max(i-k,1)]
					m = max(m,x)
				end
			end
		end
		println(m)
	end
end
main()

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

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

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

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


function calc_seq(xs)
    seq = Int[]
    count = 1
    for i = 1:length(xs)-1
        if xs[i] == xs[i+1]
            count += 1
        else
            push!(seq, count)
            count = 1
        end
    end
    push!(seq, count)
    seq
end

function main(n, k, xs)
    seq = calc_seq(xs)
    if xs[1] == 0
        seq = vcat(0, seq)
    end
    m = length(seq)
    biggest = 0
    val = sum(seq[1:min(2k+1, m)])
    for i = 3:2:m
        val += sum(seq[min(2k+i-1, m):min(2k+i, m)]) - sum(seq[max(1, i-2):max(1, i-1)])
        if biggest < val
            biggest = val
        end
    end
    print(biggest)
end

n, k = [parse(Int, x) for x in split(chomp(readline()))]
str = chomp(readline())
xs = zeros(Int, n)

for (i, s) in enumerate(str)
    xs[i] = parse(Int, s)
end

main(n, k, xs)


function calc_seq(xs)
    seq = Int[]
    count = 1
    for i = 1:length(xs)-1
        if xs[i] == xs[i+1]
            count += 1
        else
            push!(seq, count)
            count = 1
        end
    end
    push!(seq, count)
    seq
end

function main(n, k, xs)
    seq = calc_seq(xs)
    m = length(seq)
    val = Int[]
    if xs[1] == 1
        for i = 1:2:m
            push!(val, sum(seq[i:min(2k+i, m)]))
        end
    else
        push!(val, sum(seq[1:min(2k, m)]))
        for i = 2:2:m
            push!(val, sum(seq[i:min(2k+i, m)]))
        end
    end
    print(max(val...))
end

n, k = [parse(Int, x) for x in split(chomp(readline()))]
str = chomp(readline())
xs = zeros(Int, n)

for (i, s) in enumerate(str)
    xs[i] = parse(Int, s)
end

main(n, k, xs)


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

function main()
	a = readline() |> parseInt
	b = readline() |> parseInt
	c = readline() |> parseInt
	d = readline() |> parseInt
	e = readline() |> parseInt
	k = readline() |> parseInt
	println(e-a<=k?"Yay!":":(")
end
main()

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


a = int(readline())
b = int(readline())
c = int(readline())
d = int(readline())
e = int(readline())
k = int(readline())

if e-a > k
    print(":(")
else
    print("Yay!")
end


parseInt(x) = parse(Int, x)
min1=9
minsoe=1
array=[0 for i in 1:5]
for i in 1:5
    array[i]=parseInt(readline())
    if (array[i]%10)<=(min1%10) && array[i]%10>0
        min1=array[i]
        minsoe=i
    end
end
time=0
for i in 1:5
   if i != minsoe
        time+=div(array[i]+9,10)*10
    end
end
time+=array[minsoe]
println(time)

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


I()=parse.(split(readline()));k=I()[4];s=a->sort([i+j for i=I()for j=a],rev=1>0)[1:min(end,k)];println.(s(s(I())))

Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

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


xyzk = [parse(Int, x) for x in split(readline(), " ")]
K = xyzk[4]
xs = xyzk[1:3]
as = [parse(Int, x) for x in split(readline(), " ")]
bs = [parse(Int, x) for x in split(readline(), " ")]
cs = [parse(Int, x) for x in split(readline(), " ")]

as = sort(as, rev=true)
bs = sort(bs, rev=true)
cs = sort(cs, rev=true)

A = zeros(Int, xs...)
B = zeros(Int, xs...)
C = zeros(Int, xs...)

for i = 1:xs[1]
    for j = 1:xs[2]
        for k = 1:xs[3]
            A[i, j, k] = as[i]
            B[i, j, k] = bs[j]
            C[i, j, k] = cs[k]
        end
    end
end

X = A + B + C

function surround(O)
    x, y, z = size(O)
    S = zeros(Int, size(O))
    for i = 1:x
        for j = 1:y
            for k = 1:z
                if i > 1
                    if O[i - 1, j, k] == 1 && O[i, j, k] == 0
                        S[i, j, k] = 1
                    end
                end
                if j > 1
                    if O[i, j - 1, k] == 1 && O[i, j, k] == 0
                        S[i, j, k] = 1
                    end
                end
                if k > 1
                    if O[i, j, k - 1] == 1 && O[i, j, k] == 0
                        S[i, j, k] = 1
                    end
                end
            end
        end
    end
    return S
end

is = [1, 1, 1]
O = zeros(Int, xs...)
O[is] = 1

for n = 1:K
    print(X[is...])
    S = surround(O)
    SX = S .* X
    is = indmax(SX)
    O[is] = 1
    if n != K
        println()
    end
end


a,b,c=map(x->parce(int x),split(readline())
if a==b==c
    print("Yes")
else
    print("No")
end

Score : 100 points

Problem Statement

You are given three integers A, B and C.

Determine if there exists an equilateral triangle whose sides have lengths A, B and C.

Constraints

All values in input are integers.

1 \leq A,B,C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

If there exists an equilateral triangle whose sides have lengths A, B and C, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

There exists an equilateral triangle whose sides have lengths 2, 2 and 2.

Sample Input 2

3 4 5

Sample Output 2

No

There is no equilateral triangle whose sides have lengths 3, 4 and 5.


readline()
R=B=0
for c=chomp(readline())
  if c=='R'
    R+=1
  else
    B+=1
  end
end
println(R>B?"Yes":"No")

Score : 200 points

Problem Statement

There are N people numbered 1 to N. Each person wears a red hat or a blue hat.

You are given a string s representing the colors of the people. Person i wears a red hat if s_i is R, and a blue hat if s_i is B.

Determine if there are more people wearing a red hat than people wearing a blue hat.

Constraints

1 \leq N \leq 100

|s| = N

s_i is R or B.

Input

Input is given from Standard Input in the following format:

N
s

Output

If there are more people wearing a red hat than there are people wearing a blue hat, print Yes; otherwise, print No.

Sample Input 1

4
RRBR

Sample Output 1

Yes

There are three people wearing a red hat, and one person wearing a blue hat.

Since there are more people wearing a red hat than people wearing a blue hat, the answer is Yes.

Sample Input 2

4
BRBR

Sample Output 2

No

There are two people wearing a red hat, and two people wearing a blue hat.

Since there are as many people wearing a red hat as people wearing a blue hat, the answer is No.


function readline_STDIN()
    return Base.readline(Base.STDIN)
end

function exawizards2019_B()

    # STEP.01
    # read out the number of people
    num_people = Base.parse(Base.Int64, readline_STDIN())

    # STEP.02
    # read out the string which represents the colors of the people
    colors_people = readline_STDIN()

    # STEP.03
    # count up the number of hats
    num_hats_red  = Base.zero(num_people)
    num_hats_blue = num_hats_red

    for itr in Base.range(1, 1, num_people)
        if colors_people[itr] == "R"
            num_hats_red += 1
        else
            num_hats_blue += 1
        end
    end

    # STEP.04
    # output the result
    if num_hats_red > num_hats_blue
        Base.println(Base.STDOUT, "Yes")
    else
        Base.println(Base.STDOUT, "No")
    end

    # STEP.TRUE_END
    return Base.nothing

end

Main.exawizards2019_B()


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

function main()
	n = reqadline() |> parseInt
	s = chomp(readline())
	r = 0
	b = 0
	for i in 1:n
		if s[i] == 'R'
			r += 1
		else
			b += 1
		end
	end
	println(r>b?"Yes":"No")
end
main()


parseInt(x) = parse(Int,x)

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

function main()
    N,Q = readline() |> split |> parseMap
    s = readline()
    s = s[1:length(s)-1]
    order = []
    for i in 1:Q
       t,d = readline() |> split
       push!(order,[t[1],d[1]])
    end

    function judge(a,mode)
        now = a
        flag = true
        if mode=='L'
            for i in 1:Q
                if s[now]==order[i][1]
                    if order[i][2]=='L'
                        if now==1
                            flag = false
                            return flag
                        else
                            now-=1
                        end
                    else
                        if now==N
                            return flag
                        else
                            now+=1
                        end
                    end
                end
            end
        else
            for i in 1:Q
        		if s[now]==order[i][1]
                    if order[i][2]=='L'
                        if now==1
                            return flag
                        else
                            now-=1
                        end
                    else
                        if now==N
                            flag = false
                            return flag
                        else
                            now+=1
                        end
                    end
                end
            end
        end
        return true
    end

    function bisect(l,r,mode)
        if r-l==1
            if mode=='L'
                return r
            else
                return l
            end
        else
            x=Int(floor((l+r)/2))
            if judge(x,mode)
                if mode=='L'
                    return bisect(l,x,mode)
                else
                    return bisect(x,r,mode)
                end
            else
                if mode=='L'
                    return bisect(x,r,mode)
                else
                    return bisect(l,x,mode)
                end
            end
        end
    end

    if N==1
        if judge(1,'L') && judge(1,'R')
            println(1)
        else
            println(0)
        end
    else
        if judge(1,'R') && judge(N,'L')
      		if judge(N,'R')
        		R = N
      		else
        		R = bisect(1,N,'R')
      		end
      		if judge(1,'L')
        		L = 1
      		else
        		L = bisect(1,N,'L')
      		end
            println(R-L+1)
    	else
      		println(0)
    	end
    end
end

main()

Score : 500 points

Problem Statement

There are N squares numbered 1 to N from left to right.
Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.

Snuke cast Q spells to move the golems.

The i-th spell consisted of two characters t_i and d_i, where d_i is L or R.
When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is L, and moved to the square adjacent to the right if d_i is R.

However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.

Find the number of golems remaining after Snuke cast the Q spells.

Constraints

1 \leq N,Q \leq 2 \times 10^{5}

|s| = N

s_i and t_i are uppercase English letters.

d_i is L or R.

Input

Input is given from Standard Input in the following format:

N Q
s
t_1 d_1
\vdots
t_{Q} d_Q

Output

Print the answer.

Sample Input 1

3 4
ABC
A L
B L
B R
A R

Sample Output 1

2

Initially, there is one golem on each square.

In the first spell, the golem on Square 1 tries to move left and disappears.

In the second spell, the golem on Square 2 moves left.

In the third spell, no golem moves.

In the fourth spell, the golem on Square 1 moves right.

After the four spells are cast, there is one golem on Square 2 and one golem on Square 3, for a total of two golems remaining.

Sample Input 2

8 3
AABCBDBA
A L
B R
A R

Sample Output 2

5

After the three spells are cast, there is one golem on Square 2, two golems on Square 4 and two golems on Square 6, for a total of five golems remaining.

Note that a single spell may move multiple golems.

Sample Input 3

10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L

Sample Output 3

3


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    d=Dict{Char,Char}('A'=>'T','T'=>'A','C'=>'G','G'=>'C')
    println(d[chomp(readline())])
end
main()

Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

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

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


input = chomp(readline())

function isbase(c)
    if c == 'A'
        true
    elseif c == 'C'
        true
    elseif c == 'G'
        true
    elseif c == 'T'
        true
    else
        false
    end
end

xs = zeros(Int, length(input))
n = length(xs)

for (i, c) in enumerate(input)
    if isbase(c)
        xs[i] = 1
    end
end

ys = Int[]

val = 0
for i = 1:n
    if xs[i] == 1
        val += 1
        if i+1 > n || xs[i+1] == 0
            push!(ys, val)
            val = 0
        end
    end
end

print(max(ys...))


n, q = [parse(Int, x) for x in split(chomp(readline()))]
str = readline() |> chomp

ac = zeros(Int, n)
count = 0
for i = 1:n-1
    if str[i] == 'A' && str[i+1] == 'C'
        count += 1
    end
    ac[i+1] = count
end

val = zeros(Int, q)

for i = 1:q
    l, r = [parse(Int, x) for x in split(chomp(readline()))]
    val = ac[r] - ac[l]
    println(val)
end

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

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

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


n, q = [parse(Int, x) for x in split(chomp(readline()))]
str = readline() |> chomp

ac = zeros(Int, n-1)
for i = 1:n-1
    if str[i:i+1] == "AC"
        ac[i] = 1
    end
end

val = zeros(Int, q)

texts = readlines()
lines = split(chomp(texts), "\n")

for (i, line) in enumerate(lines)
    l, r = [parse(Int, x) for x in split(line)]
    val[i] = sum(ac[l:r-1])
end

for v in val
    println(v)
end


n, q = [parse(Int, x) for x in split(chomp(readline()))]
str = readline() |> chomp

val = zeros(Int, q)
for i = 1:q
    l, r = [parse(Int, x) for x in split(chomp(readline()))]
    substr = str[l:r]
    n_substr = length(substr)
    count = 0
    for j = 1:n_substr-1
        if substr[j:j+1] == "AC"
            count += 1
        end
    end
    val[i] = count
end

for v in val
    println(v)
end


idx(x,y,z) = (x-1)*16 + (y-1)*4 + (z-1) + 1
const mod = 10^9+7

function calc(n::Int64)
    A = zeros(Int128,64,64)

    # ACGT = 1234
    for i=1:4, j=1:4, k=1:4, l=1:4
        if (j==1 && k==3 && l==2) continue end #*AGC
        if (j==1 && k==2 && l==3) continue end #*ACG
        if (j==3 && k==1 && l==2) continue end #*GAC
        if (i==1 && k==3 && l==2) continue end #A*GC
        A[idx(i,j,k), idx(j,k,l)] = 1
    end

    ans = A^0
    while n > 0

        if (n%2 == 1)
            ans = (ans * A) .% mod
        end

        A = (A * A) .% mod

        n = n ÷ 2
    end
    return ans
end

function main()
    n = parse(Int, readline())
    A = calc(n)

    ans = 0
    for i=1:4^3
        ans += A[idx(4,4,4),i]
        ans %= mod
    end
    println(ans)
end

main()

Score : 400 points

Problem Statement

You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:

The string does not contain characters other than A, C, G and T.

The string does not contain AGC as a substring.

The condition above cannot be violated by swapping two adjacent characters once.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

61

There are 4^3 = 64 strings of length 3 that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is 64 - 3 = 61.

Sample Input 2

4

Sample Output 2

230

Sample Input 3

100

Sample Output 3

388130742

Be sure to print the number of strings modulo 10^9+7.