ts = 6.times.map { gets.to_f }
n = ts.shift

ts = [(10**15).to_f, ts].flatten
m = 4

5.times do |i|
	if ts[i] >= ts[i+1]
		dur = (n/ts[i+1]).ceil
		m += dur
		n -= ts[i+1]*dur
	end
end

puts m

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

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


#二分ヒープ
class BinaryHeap
  def initialize(n, &b)
    @heap = Array.new(n)
    @size = 0
    #ex) |parent, child| parent <= child
    @b = b
  end
  def push(x)
    @size += 1
    upfrom(@size - 1, x)
  end
  def shift
    wk = @heap[0]
    @size -= 1
    downfrom(0, @heap[@size])
    wk
  end

  private

  def upfrom(i, x)
    me = i
    while 0 < me do
      parent = (me - 1) >> 1
      break if @b.call(@heap[parent], x)
        @heap[me] = @heap[parent]
        me = parent
    end
    @heap[me] = x
  end
  def downfrom(i, x)
    me = i
    while me < @size do
      child = (me << 1) + 1
      break if child >= @size
      if (child + 1) < @size && @b.call(@heap[child + 1], @heap[child]) then
        child += 1
      end
      break if @b.call(x, @heap[child])
      @heap[me] = @heap[child]
      me = child
    end
    @heap[me] = x
  end
end

X, Y, Z, K = gets.chomp.split(" ").map(&:to_i)
A = gets.chomp.split(" ").map(&:to_i)
B = gets.chomp.split(" ").map(&:to_i)
C = gets.chomp.split(" ").map(&:to_i)

bh = BinaryHeap.new(X * Y * Z){|parent, child| parent[0] >= child[0]}
A.sort!.reverse!
B.sort!.reverse!
C.sort!.reverse!
ia, ib, ic = [0, 0, 0]
bh.push([A[0]+B[0]+C[0], 0, 0, 0])

K.times{
  wk = bh.shift
  puts wk[0]
  oa, ob, oc = [ia, ib, ic]
  fa, fb, fc = [false, false, false]
  (ia += 1; fa = true) if wk[1] == ia && ia < X - 1
  (ib += 1; fb = true) if wk[2] == ib && ib < Y - 1
  (ic += 1; fc = true) if wk[3] == ic && ic < Z - 1
  if fa then
    (0..ob).each{|b|
      (0..oc).each{|c|
        bh.push([A[ia]+B[b]+C[c], ia, b, c])
      }
    }
  end
  if fb then
    (0..oa).each{|a|
      (0..oc).each{|c|
        bh.push([A[a]+B[ib]+C[c], a, ib, c])
      }
    }
  end
  if fc then
    (0..oa).each{|a|
      (0..ob).each{|b|
        bh.push([A[a]+B[b]+C[ic], a, b, ic])
      }
    }
  end
  if fa && fb then (0..oc).each{|c| bh.push([A[ia]+B[ib]+C[c], ia, ib, c])} end
  if fa && fc then (0..ob).each{|b| bh.push([A[ia]+B[b]+C[ic], ia, b, ic])} end
  if fb && fc then (0..oa).each{|a| bh.push([A[a]+B[ib]+C[ic], a, ib, ic])} end
  if fa && fb && fc then bh.push([A[ia]+B[ib]+C[ic], ia, ib, ic]) end
}

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

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.

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.


x, y, z, k = gets.chomp.split.map(&:to_i)
a_ary = gets.chomp.split.map(&:to_i)
b_ary = gets.chomp.split.map(&:to_i)
c_ary = gets.chomp.split.map(&:to_i)
c_ary.sort! {|a, b| b <=> a }

ans_ab = []
# 10^6
for i in 0...x
    for j in 0...y
        ans_ab << a_ary[i] + b_ary[j]
    end
end
# 10^6*logN
ans_ab.sort!  {|a, b| b <=> a }

ans_abc = []
# 3000*z zl 10^6
for i in 0...[3000, x * y].min
    for j in 0...z
        ans_abc << ans_ab[i] + c_ary[j]
    end
end

ans_abc.sort!  {|a, b| b <=> a }
for i in 0...k
    puts ans_abc[i]
end


x, y, z, k = gets.split.map(&:to_i)
as = gets.split.map(&:to_i).sort.reverse
bs = gets.split.map(&:to_i).sort.reverse
cs = gets.split.map(&:to_i).sort.reverse

ss = []
for ai in 0...as.length
  for bi in 0...bs.length
    break if k < (ai+1)*(bi*1)
    for ci in 0...cs.length
      break if k < (ai+1)*(bi+1)*(ci+1)
      ss << as[ai]+bs[bi]+cs[ci]
    end
  end
end
puts ss.sort.reverse[0...k]


x,y,z,k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
c = gets.split.map(&:to_i)

a = a.sort_by{|n| -n}
b = b.sort_by{|n| -n}
c = c.sort_by{|n| -n}

all = a.each_with_index.flat_map do |aa, ai|
  break if ai+1 > 3000
  b.each_with_index.flat_map do |bb, bi|
    break if (ai+1) * (bi+1) > 3000
    c.each_with_index.flat_map do |cc, ci|
      break if (ai+1) * (bi+1) * (ci+1) > 3000
      aa + bb + cc
    end
  end
end.compact

puts all.sort_by{|n| -n}.take(k)


x,y,z,k = gets.chomp.split(" ").map{|i|i = i.to_i}.sort
a = gets.chomp.split(" ").map{|i|i = i.to_i}.sort
b = gets.chomp.split(" ").map{|i|i = i.to_i}.sort
c = gets.chomp.split(" ").map{|i|i = i.to_i}.sort
#puts "a=#{a}"
#puts "b=#{b}"
#puts "c=#{c}"
result_arr = []
a.length.times do|a_i|
  b.length.times do|b_i|
    c.length.times do|c_i|
      if ((a_i+1)*(b_i+1)*(c_i+1))>k then
        break
      end
      result_arr << (a[a_i]+b[b_i]+c[c_i])
    end
  end
end

result_arr.sort!
k.times do|i|
  puts result_arr[result_arr.length-1-i]
end


## https://qiita.com/naotospace/items/8edea2f89566d0f687ec

# ハッシュを使う
b = gets.chomp.to_s

hash = {A: "T", T: "A", C: "G", G: "C"}

puts hash[b]

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


STDIN.gets
s = STDIN.gets
acm = Array.new(s.length, 0)

flg = false
i = 0
s.chars do |c|
  if c == 'A'
    flg = true
  else
    if c == 'C' && flg
      acm[i-1] = 1
    end
    flg = false
  end
  i+=1
end

cache = {}
lines = STDIN.readlines
lines.each do |line|
  st, e = line.split(' ')
  key = "#{st}:#{e}"
  if c = cache[key]
    puts c
  else
    v = acm[st.to_i-1..e.to_i-2].inject(:+)
    cache[key] = v
    puts v
  end
end


ary = %i[A C G T]
puts ary.zip(ary.reverse).to_h[gets.chomp.to_sym]


N, Q=gets.split.map(&:to_i)
S=gets.chomp
lrs=Q.times.map { gets.split.map(&:to_i) }

lrs.each do |lr|
  cnt=0
  str = S[(lr[0]-1), (lr[1]-1)]
  ((str.size)-1).times do |i|
    if str[i] == "A" || str[i+1] == "C"
      cnt+=1
    end
  end
  p cnt
end


def calc(str,prev)
  	cnt = 0
	str.chars{|c| c.match(/[ATCG]/) ? cnt +=1 : break}
    cnt = [prev, str.length < 1 ? cnt : self(str.split("").drop(1).join, cnt)].max
end

puts calc(gets.chomp,0)

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


n,q = gets.split.map(&:to_i)
s = gets.chomp
l = []
r = []
q.times do
  line = gets.split.map(&:to_i)
  l << line.shift
  r << line
end
r.flatten!

x = s.chars
result = []
q.times do |i|
  result << x[(l[i]-1)..(r[i]-1)].join.scan("AC").count
end
puts result

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 = gets.split.map(&:to_i)
s = gets.chomp
num = []
q.times do
  num << gets.split.map(&:to_i)
end
arr = Array.new(n+1,0)

n.times do |i|
  arr[i] += arr[i-1]
  if s[i,2] == "AC"
    arr[i] += 1
  end
end

num.each do |j,k|
  puts arr[k-2] - arr[j-2]
end


n,q=gets.chomp.split.map(&:to_i)
s=gets.chomp.gsub(/AC/, "Ac")
que,r=[],[0]
q.times{que<< gets.chomp.split.map(&:to_i)}
s.size.times{|i|
  s[i]=="c"?r<< r[i-1]+1:r<< r[i-1]
  r.shift if i==0
}
q.times{|a|p (r[que[a][1]-1]-r[que[a][0]-1])}


N,Q=gets.split.map &:to_i
S=gets.chomp
m=[]
(0..(N-2)).each{|i|
    if S[i]=='A' && S[i+1]=='C'
        m << i
    end
}
#p m
(0...Q).each{|i|
    l,r=gets.split.map &:to_i
    li=m.bsearch_index{|x| x>=l-1}
    ri=m.bsearch_index{|x| x>=r-1}
    if li==nil
        li=m.size
    end
    if ri ==nil
        ri=m.size
    end
    #p [li, ri]
    puts (m[ri-1]==r ? ri-li-1 : ri-li)
}


def limited_insertion
  n = 0
  b = []
  i = 0
  while line = gets
    n = line[0].to_i if i == 0
    b = line.split(' ').map{|v| v.to_i} if i == 1
    break if i == 1
    i += 1
  end

  a = []
  for i in 1..n
    result = -1
    for j in 1..i
      if b[i-1] == j
        result = j
        break
      end
    end

    p result

    break if result == -1
  end
end

limited_insertion

Score : 400 points

Problem Statement

Snuke has an empty sequence a.

He will perform N operations on this sequence.

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

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

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq b_i \leq N

Input

Input is given from Standard Input in the following format:

N
b_1 \dots b_N

Output

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

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

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

After the first operation: (1)

After the second operation: (1,1)

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

Sample Input 2

2
2 2

Sample Output 2

-1

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

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1


N=gets
S=gets.chomp

counts = []
('a'..'z').each do |c|
  counts << S.count(c)+1
end

puts((counts.inject(&:*)-1) % (10**9 + 7))

Score : 200 points

Problem Statement

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

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

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

4
abcd

Sample Output 1

15

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

Sample Input 2

3
baa

Sample Output 2

5

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

Sample Input 3

5
abcab

Sample Output 3

17


hh, ww = gets.split.map(&:to_i)
h, w = gets.split.map(&:to_i)
puts (hh-h)*(ww-w)

Score : 100 points

Problem Statement

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

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

How many white cells will remain?

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

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

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

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


a, b, k = gets.chomp.split.map(&:to_i)
cnt = 0
[a,b].min.downto(1) do |i|
	cnt += 1 if a % i == 0 && b % i == 0
	if cnt == k
		puts i
		break
	end

end

Score : 200 points

Problem Statement

You are given positive integers A and B.

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

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

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

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

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

Sample Input 1

8 12 2

Sample Output 1

2

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

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


a, b, k = gets.split.map(&:to_i)
smaller = [a, b].min
nums = []
(1..smaller).each do |n|
  if (a%n) == 0 && (b%n) == 0
    nums.push(n)
  end
end
puts nums.sort().reverse[k-1]


@arg = gets.chomp
@arg_len = @arg.length
@dp_table = {}

def calc_erasable_index(pattern)
    res = {}
    pattern.scan(/01|10/) do |c|
      res.store(c, $~.offset(0)[0])
    end
    unless @dp_table[pattern]
        @dp_table.store(pattern,@arg_len - pattern.length)
        res.each do |key, value|
            /#{key}/ =~ pattern
            calc_erasable_index($` + $')
        end
    end
    return 0
end
calc_erasable_index(@arg)

print @dp_table.values.max

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

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

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

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

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

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

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


string = gets.chomp # 文字列として受け取る
count_of_num = [string.count("0"), string.count("1")]
puts count_of_num.min*2


IND = -1  # 独立

# n:島の数
# m:橋の数
n, m = gets.chomp.split(' ').map(&:to_i)

abs = Array.new(m, nil)
uf = Array.new(n+1, IND)
results = Array.new

for i in 1..m do
  a, b = gets.chomp.split(' ').map(&:to_i)
  abs[i-1] = [a,b]
end

abs.reverse!

def root(array, pos)
  return pos if pos == IND
  while array[pos] != pos do
    pos = array[pos]
    return pos if pos == IND
  end
  pos
end
for (l,r) in abs do

  sum = 0
  for i in 1..n do
    for j in i+1..n do
      i_root = root(uf, i)
      j_root = root(uf, j)
      sum += 1 if (i_root != j_root) or i_root == IND or j_root == IND
    end
  end
  results.push(sum)

  # 独立のノードを根にする
  if uf[l] == IND then
    uf[l] = l
  end
  if  uf[r] == IND then
    uf[r] = r
  end

  # 左右の根を求める
  l = root(uf, l)
  r = root(uf, r)

  # 左の根を右の根につなげる
  uf[l] = r
end

for i in results.reverse do
  print "#{i}\n"
end

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


class Node
  attr_accessor :parent, :size

  def initialize(n)
    @parent = n
    @size = 1
  end
end

class UnionFindTree
  def initialize(n)
    @nodes = (0..n).to_a.map { |i| Node.new(i) }
  end

  def find(x)
    return x if @nodes[x].parent == x

    return @nodes[x].parent = find(@nodes[x].parent)
  end

  def size(x)
    return @nodes[x].size if @nodes[x].parent == x

    @nodes[x].parent = find(@nodes[x].parent)

    return size(@nodes[x].parent)
  end

  def unite(a, b)
    a = find(a)
    b = find(b)
    return if a == b

    @nodes[a].parent = b
    @nodes[b].size += @nodes[a].size
  end

  def same?(a, b)
    find(a) == find(b)
  end
end

n, m = gets.split.map(&:to_i)

tree = UnionFindTree.new(n)
ans = [ n * (n - 1) / 2 ]

x = []

m.times do |i|
  x << gets.split.map(&:to_i)
end

x.reverse.each do |a, b|
  if ans[-1] == 0
    ans << 0
  elsif !tree.same?(a, b)
    ans << ans[-1] - tree.size(a) * tree.size(b)
    tree.unite(a, b)
  else
      ans << ans[-1]
  end
end

puts ans[0...-1].reverse


require 'time'
s = gets.chomp

puts Time.parse(s) <= Time.parse('2019/04/30') ? 'Heisei' : 'TBD'

Score : 100 points

Problem Statement

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

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

Constraints

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

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


Score : 200 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 10

u_i = JPY or BTC.

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

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

Input

Input is given from Standard Input in the following format:

N
x_1 u_1
x_2 u_2
:
x_N u_N

Output

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

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

Sample Input 1

2
10000 JPY
0.10000000 BTC

Sample Output 1

48000.0

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

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

Sample Input 2

3
100000000 JPY
100.00000000 BTC
0.00000001 BTC

Sample Output 2

138000000.0038

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


n = gets.to_i
total = 0
(0...n).each do |i|
  data = gets.chomp.split(' ')
  total += data[1] == 'BTC' ? 380000 * data[0].to_f : data[0].to_i
end
puts total


A, B, Q = gets.chomp.split(" ").map(&:to_i)
S = []
T = []
X = []
A.times do
  S << gets.chomp.to_i
end
B.times do
  T << gets.chomp.to_i
end
Q.times do
  X << gets.chomp.to_i
end

X.each do |x|
  si = S.bsearch_index{|v| v >= x}
  sc = []
  if si.nil?
    sc = [S[-1]]
  elsif si.zero?
    sc = [S[0]]
  else
    sc = [S[si-1], S[si]]
  end
  ti = T.bsearch_index{|v| v >= x}
  tc = []
  if ti.nil?
    tc = [T[-1]]
  elsif ti.zero?
    tc = [T[0]]
  else
    tc = [T[ti-1], T[ti]]
  end
  min_cost = Float::INFINITY
  sc.each do |ss|
    tc.each do |tt|
      if (ss <= x && tt <= x) || (ss >= x && tt >= x)
        # 同じ方向
        cost = [(ss-x).abs, (tt-x).abs].max
      else
        # 逆方向
        cost = [(ss - x).abs + (tt - ss).abs, (tt - x).abs + (ss - tt).abs].min
      end
      min_cost = cost if cost < min_cost
    end
  end
  puts min_cost
end

Score : 400 points

Problem Statement

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

Answer the following Q queries:

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

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

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

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

1 \leq x_i \leq 10^{10}

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

350
1400
301
399

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

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

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

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

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

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

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


(a, b) = gets.chomp.split(' ').map(&:to_i)

if a % b == 0 then
  puts (a + b).to_s
else
  puts (b - a).to_s
end

Score : 100 points

Problem Statement

You are given positive integers A and B.

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

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

4 12

Sample Output 1

16

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

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


# coding: utf-8
class Case02

  def initialize
  end

  def show
    p self.instance_variables
        .map{ |sym| [sym, self.instance_variable_get(sym)] }
        .to_h
  end

  # 実行する
  def execute
    read
    solve
    output
  end

  # 読込
  def read
    @n, @m = gets.chomp.split.map(&:to_i)
    @k = []
    @a = []
    @n.times do
      t = gets.chomp.split.map(&:to_i)
      @k << t[0]
      @a << t[1..-1]
    end
  end

  # 回答
  def solve
    @result = []
    1.upto(@m) do |i|
      count = 0
      1.upto(@n) do |j|
        if @a[j-1].include?(i) then
          count += 1
        end
      end
      if count == @n then
        @result << i
      end
    end
  end

  # 出力
  def output
    puts @result.count
  end

end

#
Case02.new.execute if $0 == __FILE__

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

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

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

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

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

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

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

Constraints

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

1

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

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3


cost_map = {
  1 => 2,
  2 => 5,
  3 => 5,
  4 => 4,
  5 => 5,
  6 => 6,
  7 => 3,
  8 => 7,
  9 => 6
}

n, m = gets.split(" ").map {|s| s.to_i}
available_numbers = gets.split(" ").map {|s| s.to_i}

# 候補となる数字を抽出(コスパの悪い数字は最初から候補に入れないようにする & 候補は素数になるはず)
use_numbers = []
costs_per_use_number = []
available_numbers.sort.reverse.each { |number|
  cost_per_number = cost_map[number]

  if costs_per_use_number.all? { |cost_per_use_number| cost_per_number % cost_per_use_number != 0} then
    costs_per_use_number.each { |cost_per_use_number|# fixme: すごく汚い実装になってしまった。後で直すか
      if (cost_per_use_number % cost_per_number == 0) && (cost_per_use_number / cost_per_number > 1) then
        costs_per_use_number.delete(cost_per_use_number)
        use_numbers = use_numbers.select {|n| cost_map[n] != cost_per_use_number }
      end
    }

    use_numbers.push(number)
    costs_per_use_number.push(cost_per_number)
  end
}

# 桁数が最大となる組み合わせを見つける
lcm = costs_per_use_number.reduce(1) {|gcd_acc, cost_per_use_number| gcd_acc.lcm(cost_per_use_number)}
min_cost_number = use_numbers.min {|a, b| cost_map[a] <=> cost_map[b]}
digits_of_min_repeated_with_lcm = (n / lcm) * (lcm / cost_map[min_cost_number])
rest = n % lcm

max_permutations = [[]] # 棒が0本の時は空
(1..rest).each { |stick_number|
  use_numbers.each { |number|
    cost_per_number = cost_map[number]
    stick_number_before = stick_number - cost_per_number

    if stick_number_before >= 0 then
      max_permutation_before = max_permutations[stick_number_before]

      unless max_permutation_before.nil? then
        permutation = max_permutation_before.clone.push(number).sort.reverse
        max_permutation = max_permutations[stick_number]
        if max_permutation.nil? then
          max_permutations[stick_number] = permutation
        elsif (permutation.size > max_permutation.size) || ((permutation.size == max_permutation.size) && ((permutation <=> max_permutation) == 1)) then
          max_permutations[stick_number] = permutation
        end
      end
    end
  }
}

max_permutation = (max_permutations[rest] + Array.new(digits_of_min_repeated_with_lcm, min_cost_number)).sort.reverse

puts(max_permutation.join)

Score : 400 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^4

1 \leq M \leq 9

1 \leq A_i \leq 9

A_i are all different.

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

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

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

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

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

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

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

Sample Input 3

15 3
5 4 6

Sample Output 3

654


n,k = gets.split(" ").map!{|i| i.to_i}
sum = 0
1.upto(n) do |p|
 if p == 0 or n
  sum += n - 1
else sum += n -2
end
end
if sum >= k
 puts 'Yes'
else puts 'No'
end

Score : 100 points

Problem Statement

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

Constraints

1\leq N,K\leq 100

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

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

Sample Input 1

3 2

Sample Output 1

YES

We can choose 1 and 3.

Sample Input 2

5 5

Sample Output 2

NO

Sample Input 3

31 10

Sample Output 3

YES

Sample Input 4

10 90

Sample Output 4

NO


x = [0, 0, 0, 0]
for n in 0..2
  a, b = gets.chomp.split.map(&:to_i)
  x[a - 1] = x[a - 1] + 1
  x[b - 1] = x[b - 1] + 1
end
if x.max > 2 or x.min < 1
  puts "NO"
  exit
else
  puts "YES"
end

Score : 200 points

Problem Statement

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

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

Constraints

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

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

No two roads connect the same pair of towns.

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

Input

Input is given from Standard Input in the following format:

a_1 b_1
a_2 b_2
a_3 b_3

Output

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

Sample Input 1

4 2
1 3
2 3

Sample Output 1

YES

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

Sample Input 2

3 2
2 4
1 2

Sample Output 2

NO

Sample Input 3

2 1
3 2
4 3

Sample Output 3

YES


sa=Array.new(4,0)
3.times{
	s,e=gets.split(" ").map(&:to_i)
	sa[s-1]+=1
	sa[e-1]+=1
}
cnt1=0
cnt2=0
sa.each{|f|
	if f==1
		cnt1+=1
	elsif f==2
		cnt2+=1
	end
}
if cnt1==2 && cnt2==2
	puts "YES"
else
	puts "NO"
end


t, x = gets.chomp.split(" ").map(&:to_i)

puts t / x.to_f

Score : 100 points

Problem Statement

In order to pass the entrance examination tomorrow, Taro has to study for T more hours.

Fortunately, he can leap to World B where time passes X times as fast as it does in our world (World A).

While (X \times t) hours pass in World B, t hours pass in World A.

How many hours will pass in World A while Taro studies for T hours in World B?

Constraints

All values in input are integers.

1 \leq T \leq 100

1 \leq X \leq 100

Input

Input is given from Standard Input in the following format:

T X

Output

Print the number of hours that will pass in World A.

The output will be regarded as correct when its absolute or relative error from the judge's output is at most 10^{-3}.

Sample Input 1

8 3

Sample Output 1

2.6666666667

While Taro studies for eight hours in World B where time passes three times as fast, 2.6666... hours will pass in World A.

Note that an absolute or relative error of at most 10^{-3} is allowed.

Sample Input 2

99 1

Sample Output 2

99.0000000000

Sample Input 3

1 100

Sample Output 3

0.0100000000


n,m = gets.chomp.split(' ').map(&:to_i)
arr = gets.chomp.split(' ').map(&:to_i).sort.reverse
ans = 0
intervals = []
i = 1
while i < arr.size
  intervals << arr[i-1] - arr[i]
  i += 1
end
intervals.sort!
puts intervals[0..(m-n-1)].sum

Score : 300 points

Problem Statement

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

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

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

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

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

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

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

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_M

Output

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

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

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

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

Move the piece at coordinate 1 to 2.

Move the piece at coordinate 10 to 11.

Move the piece at coordinate 11 to 12.

Move the piece at coordinate 12 to 13.

Move the piece at coordinate 13 to 14.

Sample Input 2

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

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0


num1 = ARGV[0].to_i
num2 = ARGV[1].to_i
num3 = ARGV[2].to_i
num4 = num3 - (num1 - num2)
if num2 > num3 then
  num2 = num3
end
if num4 < 0 then
  num4 = 0
end
puts num2.to_s + " " + num4.to_s

Score : 100 points

Problem Statement

We conducted a survey on newspaper subscriptions.
More specifically, we asked each of the N respondents the following two questions:

Question 1: Are you subscribing to Newspaper X?

Question 2: Are you subscribing to Newspaper Y?

As the result, A respondents answered "yes" to Question 1, and B respondents answered "yes" to Question 2.

What are the maximum possible number and the minimum possible number of respondents subscribing to both newspapers X and Y?

Write a program to answer this question.

Constraints

1 \leq N \leq 100

0 \leq A \leq N

0 \leq B \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the maximum possible number and the minimum possible number of respondents subscribing to both newspapers, in this order, with a space in between.

Sample Input 1

10 3 5

Sample Output 1

3 0

In this sample, out of the 10 respondents, 3 answered they are subscribing to Newspaper X, and 5 answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most 3 and at least 0.

Sample Input 2

10 7 5

Sample Output 2

5 2

In this sample, out of the 10 respondents, 7 answered they are subscribing to Newspaper X, and 5 answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most 5 and at least 2.

Sample Input 3

100 100 100

Sample Output 3

100 100


N = gets.chomp.to_i
A = gets.chomp
B = gets.chomp
C = gets.chomp
count = 0
0.upto(N-1) do |n|
  match = [A[n], B[n], C[n]].uniq.size
  if match == 2
    count += 1
  elsif match == 3
    count += 2
  end
end
puts count

Score : 200 points

Problem Statement

You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.

Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:

Operation: Choose one of the strings A, B and C, and specify an integer i between 1 and N (inclusive). Change the i-th character from the beginning of the chosen string to some other lowercase English letter.

What is the minimum number of operations required to achieve the objective?

Constraints

1 \leq N \leq 100

Each of the strings A, B and C is a string of length N.

Each character in each of the strings A, B and C is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
A
B
C

Output

Print the minimum number of operations required.

Sample Input 1

4
west
east
wait

Sample Output 1

3

In this sample, initially A = west、B = east、C = wait. We can achieve the objective in the minimum number of operations by performing three operations as follows:

Change the second character in A to a. A is now wast.

Change the first character in B to w. B is now wast.

Change the third character in C to s. C is now wast.

Sample Input 2

9
different
different
different

Sample Output 2

0

If A, B and C are already equal in the beginning, the number of operations required is 0.

Sample Input 3

7
zenkoku
touitsu
program

Sample Output 3

13


n = gets.chomp!.to_i

takahashi = []
aoki = []
tokuten = []

n.times do |i|
  a, b = gets.chomp!.split(" ").map(&:to_i)
  takahashi << a
  aoki << -1 * b
  tokuten << { idx: i, point: a + b }
end

puts tokuten.sort { |t| t[:point] }.map.with_index { |k, idx| idx.even? ? takahashi[k[:idx]] : aoki[k[:idx]] }.inject(:+)

Score : 400 points

Problem Statement

There are N dishes of cuisine placed in front of Takahashi and Aoki.
For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.

When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.

Starting from Takahashi, they alternately choose one dish and eat it, until there is no more dish to eat.
Here, both of them choose dishes so that the following value is maximized: "the sum of the happiness he/she will earn in the end" minus "the sum of the happiness the other person will earn in the end".

Find the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Sample Input 1

3
10 10
20 20
30 30

Sample Output 1

20

In this sample, both of them earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since Takahashi and Aoki have the same "taste", each time they will choose the dish with which they can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (30 + 10) - 20 = 20.

Sample Input 2

3
20 10
20 20
20 30

Sample Output 2

20

In this sample, Takahashi earns 20 points of happiness by eating any one of the dishes 1, 2 and 3, but Aoki earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since only Aoki has likes and dislikes, each time they will choose the dish with which Aoki can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (20 + 20) - 20 = 20.

Sample Input 3

6
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 3

-2999999997

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


n, m = gets.split.map(&:to_i)
child = Hash.new { |h, k| h[k] = [] }
parent = Hash.new { |h, k| h[k] = [] }
(n + m - 1).times do
  a, b = gets.split.map(&:to_i)
  child[a] << b
  parent[b] << a
end

root = 1
until parent[root].empty?
  root = parent[root].first
end

queue = [root]
visited = {}
deleted = 0
until queue.empty?
  pos = queue.shift
  child[pos].each do |ch|
    if visited[ch] && parent[ch].size > 1
      parent[ch].delete(visited[ch])
      deleted += 1
      if deleted == m
        break
      end
    end
    visited[ch] = pos
    queue << ch
  end
  if deleted == m
    break
  end
end

(1..n).each do |i|
  puts(parent[i].first || 0)
end

Score : 500 points

Problem Statement

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

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

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

Restore the original rooted tree.

Notes

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

Constraints

3 \leq N

1 \leq M

N + M \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

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

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

Input

Input is given from Standard Input in the following format:

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

Output

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

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

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

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

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2


AB,BC,CA = gets.split.map(&:to_i)
p AB*BC/2

Score : 100 points

Problem Statement

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

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

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

Constraints

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

All values in input are integers.

The area of the triangle ABC is an integer.

Input

Input is given from Standard Input in the following format:

|AB| |BC| |CA|

Output

Print the area of the triangle ABC.

Sample Input 1

3 4 5

Sample Output 1

6

This triangle has an area of 6.

Sample Input 2

5 12 13

Sample Output 2

30

This triangle has an area of 30.

Sample Input 3

45 28 53

Sample Output 3

630

This triangle has an area of 630.


n = gets.to_i
ary = [n]
cnt = 1
while(true)
  n = n.odd? ? 3*n+1 : n/2
  if ary.include?(n)
    puts cnt + 1
    exit
  end
  ary << n
  cnt += 1
end

Score : 200 points

Problem Statement

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

The first term s is given as input.

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

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

Find the minimum integer m that satisfies the following condition:

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

Constraints

1 \leq s \leq 100

All values in input are integers.

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

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum integer m that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

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

Sample Input 2

7

Sample Output 2

18

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

Sample Input 3

54

Sample Output 3

114


n=gets.to_i
h=gets.split.map(&:to_i)
c = 0
100.times do |i|
  f = false
  n.times do |j|
    if !f && h[j] > i
      f = true
      c += 1
    elsif f && h[j] <= i
      f = false
    end
  end
end
p c

Score : 300 points

Problem Statement

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

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

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

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

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

Sample Input 1

4
1 2 2 1

Sample Output 1

2

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

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

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

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221


n, as, bs = ARGF.read.split("\n").map { |e| e.split }
xs = as.zip(bs).map { |e|
  a,b = e.map { |e| e.to_i }
  [a, b, a - b]
}.sort { |e| e.last }
ms = xs.select { |e|
  e.last < 0
}
ps = xs.select { |e|
  e.last > 0
}
if ms.length == 0
  puts 0
  exit
end

c = ms.length
val = 0
ms.each { |e|
  if val <= e.last.abs
    loop {
      if ps.length == 0
        puts -1
        exit
      else
        val += ps.pop.last
        c += 1
        if val > e.last.abs
          val -= e.last.abs
          break
        end
      end
    }
  end
}
puts c

Score : 400 points

Problem Statement

A university student, Takahashi, has to take N examinations and pass all of them.
Currently, his readiness for the i-th examination is A_{i}, and according to his investigation, it is known that he needs readiness of at least B_{i} in order to pass the i-th examination.

Takahashi thinks that he may not be able to pass all the examinations, and he has decided to ask a magician, Aoki, to change the readiness for as few examinations as possible so that he can pass all of them, while not changing the total readiness.

For Takahashi, find the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the following conditions:

The sum of the sequence A_1, A_2, ..., A_{N} and the sum of the sequence C_1, C_2, ..., C_{N} are equal.

For every i, B_i \leq C_i holds.

If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

A_i and B_i are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N}
B_1 B_2 ... B_{N}

Output

Print the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the conditions.
If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.

Sample Input 1

3
2 3 5
3 4 1

Sample Output 1

3

(A_1, A_2, A_3) = (2, 3, 5) and (B_1, B_2, B_3) = (3, 4, 1). If nothing is done, he cannot pass the first and second exams.
The minimum possible number of indices i such that A_i and C_i are different, 3, is achieved when:

(C_1, C_2, C_3) = (3, 5, 2)

Sample Input 2

3
2 3 3
2 2 1

Sample Output 2

0

In this case, he has to do nothing in order to pass all the exams.

Sample Input 3

3
17 7 1
25 6 14

Sample Output 3

-1

In this case, no matter what is done, he cannot pass all the exams.

Sample Input 4

12
757232153 372327760 440075441 195848680 354974235 458054863 463477172 740174259 615762794 632963102 529866931 64991604
74164189 98239366 465611891 362739947 147060907 118867039 63189252 78303147 501410831 110823640 122948912 572905212

Sample Output 4

5


h, w = gets.split.map(&:to_i)
list = h.times.map{ gets.chomp.split('') }
s = list.flatten.map.with_index{ |c, i| i if c == '#' }.compact
move = [[-1, 0], [0, 1], [1, 0], [0, -1]]
ans = 0

s.each do |i|
  x = i % w
  y = i / w
  q = [[x, y, 0]]
  visited = h.times.map{ [false] * w }
  visited[y][x] = true
  until q.empty?
    x, y, color = q.shift
    move.each do |mx, my|
      nx = x + mx
      ny = y + my
     if 0 <= nx && nx < w && 0 <= ny && ny < h
        if !visited[ny][nx]
          visited[ny][nx] = true
          if color == 0 && list[ny][nx] == '.' || color == 1 && list[ny][nx] == '#'
            q << [nx, ny, 1 - color]
            if color == 0
              ans += 1
            end
          end
        end
      end
    end
  end
end
puts ans

Score : 300 points

Problem Statement

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

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

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

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

Constraints

1 \leq H, W \leq 400

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

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

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

Print the answer.

Sample Input 1

3 3
.#.
..#
#..

Sample Output 1

10

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

Sample Input 2

2 4
....
....

Sample Output 2

0

Sample Input 3

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

Sample Output 3

6


n = gets.to_i

a = gets.split.map(&:to_i)
a1 = a.count(1)
a2 = a.count(2)
a3 = a.count(3)

m = a2 + a3
d = Array.new(m+1) {Array.new(n+1, 0.0)}
u = Array.new(m+1) {Array.new(n+1, 0.0)}

(a3+1).times do |c3|
    (m-c3+1).times do |c2|
        (n-c2-c3+1).times do |c1|
            t = c1 + c2 + c3
            next if t == 0
            s = n.to_f
            s += u[c2][c1-1] * c1 if c1 > 0
            s += u[c2-1][c1+1] * c2 if c2 > 0
            s += d[c2+1][c1] * c3 if c3 > 0
            u[c2][c1] = s / t
        end
    end
    d, u = u, d
end

p d[a2][a1]

Score : 100 points

Problem Statement

There are N dishes, numbered 1, 2, \ldots, N.
Initially, for each i (1 \leq i \leq N), Dish i has a_i (1 \leq a_i \leq 3) pieces of sushi on it.

Taro will perform the following operation repeatedly until all the pieces of sushi are eaten:

Roll a die that shows the numbers 1, 2, \ldots, N with equal probabilities, and let i be the outcome. If there are some pieces of sushi on Dish i, eat one of them; if there is none, do nothing.

Find the expected number of times the operation is performed before all the pieces of sushi are eaten.

Constraints

All values in input are integers.

1 \leq N \leq 300

1 \leq a_i \leq 3

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the expected number of times the operation is performed before all the pieces of sushi are eaten.
The output is considered correct when the relative difference is not greater than 10^{-9}.

Sample Input 1

3
1 1 1

Sample Output 1

5.5

The expected number of operations before the first piece of sushi is eaten, is 1.
After that, the expected number of operations before the second sushi is eaten, is 1.5.
After that, the expected number of operations before the third sushi is eaten, is 3.
Thus, the expected total number of operations is 1 + 1.5 + 3 = 5.5.

Sample Input 2

1
3

Sample Output 2

3

Outputs such as 3.00, 3.000000003 and 2.999999997 will also be accepted.

Sample Input 3

2
1 2

Sample Output 3

4.5

Sample Input 4

10
1 3 2 3 3 2 3 2 1 3

Sample Output 4

54.48064457488221


class Integer
  def digit_sum_multiple_count(div, mod = 10 ** 9 + 7)
    s = self.to_s
    l = s.size

    dpA = Array.new(l + 1) { Array.new(div, 0) }
    dpB = Array.new(l + 1) { Array.new(div, 0) }
    dpA[0][0] = 1

    l.times do |i|
      n = s[i].to_i

      0.upto(div - 1) do |j|
        if dpA[i][j] > 0
          dpA[i + 1][(j + n) % div] = dpA[i][j]

          if i > 0
            0.upto(n - 1) do |k|
              dpB[i + 1][(j + k) % div] += 1
            end
          end
        end

        if dpB[i][j] > 0
          0.upto(9) do |k|
            dpB[i + 1][(j + k) % div] += dpB[i][j]
            dpB[i + 1][(j + k) % div] += mod
          end
        end
      end

      1.upto(9) do |k|
        next if i == 0 && k >= n
        dpB[i + 1][k % div] += 1
      end
    end

    (dpA[l][0] + dpB[l][0]) % mod
  end
end

K = gets.to_i
D = gets.to_i

puts K.digit_sum_multiple_count(D)

Score : 100 points

Problem Statement

Find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo 10^9 + 7:

The sum of the digits in base ten is a multiple of D.

Constraints

All values in input are integers.

1 \leq K < 10^{10000}

1 \leq D \leq 100

Input

Input is given from Standard Input in the following format:

K
D

Output

Print the number of integers satisfying the condition, modulo 10^9 + 7.

Sample Input 1

30
4

Sample Output 1

6

Those six integers are: 4, 8, 13, 17, 22 and 26.

Sample Input 2

1000000009
1

Sample Output 2

2

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

Sample Input 3

98765432109876543210
58

Sample Output 3

635270834


Score : 100 points

Problem Statement

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

Constraints

1000 \leq N \leq 9999

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

1222

Sample Output 1

3

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

Sample Input 2

3456

Sample Output 2

0

Sample Input 3

9592

Sample Output 3

1


N, P = gets.split(/ /).collect{|n| n.to_i}

if N == 1
	puts P
else

	MAX = 10 ** 6

	p_table = [true] * (MAX + 1)

	(2..10**6).each{|n|
		next unless p_table[n]
		x = n + n
		while x < MAX
			p_table[x] = false
			x += n
		end
	#	print "#{n} "
	}
	p_list = []

	(2..10**6).each{|n|
		if p_table[n]
			p_list << n
		end
	}

	i = p_list.length - 1

	f_table = {}

	num = P
	while i >= 0 && num > 1
		f = p_list[i]
		if f <= num
			while true
				if num % f == 0
					num = num / f
					if count = f_table[f]
						f_table[f] = count + 1
					else
						f_table[f] = 1
					end
				else
					break
				end
			end
		end

		i -= 1
	end

	answer = 1
	f_table.each{|f, count|
		if count >= N
			answer *= (f ** (count / N))
		end
	}

	puts answer
end

Score : 300 points

Problem Statement

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

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

Constraints

1 \leq N \leq 10^{12}

1 \leq P \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N P

Output

Print the answer.

Sample Input 1

3 24

Sample Output 1

2

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

Sample Input 2

5 1

Sample Output 2

1

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

Sample Input 3

1 111

Sample Output 3

111

Sample Input 4

4 972439611840

Sample Output 4

206


N = gets.to_i
as = N.times.map{gets.to_i}
puts as.all?{|e|e.even?} ? "second" : "first"

Score : 500 points

Problem Statement

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

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

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

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

Constraints

1 \leq N \leq 10^5

1 \leq a_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

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

Sample Input 1

2
1
2

Sample Output 1

first

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

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

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

Sample Input 2

3
100000
30000
20000

Sample Output 2

second


def BW_reverse(a, length, count)
  (0..(length-count/2)).reverse_each do |i|
    if a[i] == "B" && a[i+1] == "W"
      a[i] = "W"
      a[i+1] = "B"
      count = count + 1
      return BW_reverse(a, length, count)
    end
  end
  return count
end

a = gets.chomp.split("")
length = a.length - 2
count = 0

puts BW_reverse(a, length, count)

Score : 300 points

Problem Statement

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

Consider performing the following operation:

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

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

Constraints

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

S_i=B or W

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

BBW

Sample Output 1

2

The operation can be performed twice, as follows:

Flip the second and third pieces from the left.

Flip the first and second pieces from the left.

Sample Input 2

BWBWBW

Sample Output 2

6


n = gets.to_i
arr = n.times.map{gets.to_i}
h_item = arr.max
h_index = arr.index(h_item)
arr[h_index] = h_item / 2
puts arr.inject(:+)

Score : 200 points

Problem Statement

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

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

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

Constraints

2 \leq N \leq 10

100 \leq p_i \leq 10000

p_i is an even number.

Input

Input is given from Standard Input in the following format:

N
p_1
p_2
:
p_N

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

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

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

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

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


n  = gets.to_i
ps = []
n.times do |i|
  ps << gets.to_i
end

answer = ps.reduce(0, :+) - ps.max / 2

p answer


def test
	n = gets.to_i
	ps = []
	n.times do
		ps << gets.to_i
	end
	ps.sort!
	ps[-1] /= 2
	ps.inject{|sum, i| sum += i}
end

puts test


N = gets.to_i

list = N.times.map { gets.to_i }

list.sort!

puts list[0..-2].inject(:+) + list[-1] / 2


n, k = gets.split.map(&:to_i)
hs = n.times.map { gets.to_i }.sort
ans = 10 ** 20
(0..n-1-k+1).each do |i|
  ans = [ans, (hs[i]-hs[i+k-1]).abs].min
end
puts ans

Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

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

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

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

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

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

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

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

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

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

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


n,k=gets.split.map(&:to_i)
xs=readlines.map(&:to_i).sort
p (0...k).map{|i|xs[i+k-1]-xs[i]}.min


n,x = gets.split.map(&:to_i)
patti = [1]
sum = [1]
mid = [1]
n.times do |i|
  patti << patti[-1]*2 +1
  sum << sum[-1] * 2 + 3
  mid << sum[i] + 2
end
lv = n
ans = 0
while lv > 0
  if x == (mid[lv]-1)
    ans += patti[lv-1]
    x -= mid[lv]-1
  elsif x >= mid[lv]
    ans += patti[lv-1] + 1
    x -= mid[lv]
  else
    x -= 1
  end
  lv -= 1
  #p [lv,ans,x]
end
ans += 1 if x > 0
p ans

Score : 400 points

Problem Statement

In some other world, today is Christmas.

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

A level-0 burger is a patty.

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

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

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

Constraints

1 \leq N \leq 50

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

N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

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

Sample Input 1

2 7

Sample Output 1

4

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

Sample Input 2

1 1

Sample Output 2

0

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

Sample Input 3

50 4321098765432109

Sample Output 3

2160549382716056

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


a = gets.chomp.to_i
puts a==7 || a==5 ||a ==3 ? "YES" : "NO"

Score : 100 points

Problem Statement

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

1 ≤ X ≤ 9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If Takahashi's growth will be celebrated, print YES; if it will not, print NO.

Sample Input 1

5

Sample Output 1

YES

The growth of a five-year-old child will be celebrated.

Sample Input 2

6

Sample Output 2

NO

See you next year.


s = gets.chomp.split("")
abs_arr = []
n = s.count
like = 753

(0..n).each do |i|
  if (i+2) <= (n-1)
    abs_arr <<  (s[i..(i+2)].join.to_i - like).abs
  end
end

p abs_arr.min

Score : 200 points

Problem Statement

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

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

Constraints

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

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

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum possible difference between X and 753.

Sample Input 1

1234567876

Sample Output 1

34

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

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

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

Sample Input 2

35753

Sample Output 2

0

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

Sample Input 3

1111111111

Sample Output 3

642

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


s = gets.chomp
puts (0..s.size-3).to_a.map { |i| (s[i..i+2].to_i - 753).abs }.min


a=gets.chomp.to_i
if a < 357
  puts 0
else
  l = a.to_s.length - 3
  c_ary = [[3,5,7]]
  d_ary = [3, 5, 7]
  l.times do |i|
    i += 1
    [3,5,7].repeated_permutation(i){ |n| c_ary << (d_ary + n) }
  end
  n_ary = []
c_ary.each do |c|
  n_ary << c.permutation.map { |n| n.join.to_i}
end
n_ary = n_ary.flatten.uniq
ans_ary = n_ary.select { |n| n < a }
puts ans_ary.size
end

Score : 300 points

Problem Statement

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

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

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

Constraints

1 \leq N < 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

575

Sample Output 1

4

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

Sample Input 2

3600

Sample Output 2

13

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

Sample Input 3

999999999

Sample Output 3

26484


N = gets.to_i
a = gets.split.map(&:to_f)
mean = a.inject(:+) / N
b = a.map { |ai| (ai - mean).abs }
puts b.index(b.min)

Score : 200 points

Problem Statement

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

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

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

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

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

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

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

Constraints

1 \leq N \leq 100

1 \leq a_i \leq 100

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

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

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

1

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

Sample Input 2

4
2 5 2 5

Sample Output 2

0

The average of frame representations is 3.5.

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

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


X, Y = gets.split.map(&:to_i)

puts X + Y / 2

Score: 100 points

Problem Statement

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

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

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

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

Constraints

1 \leq X,Y \leq 100

Y is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

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

Sample Input 1

81 58

Sample Output 1

110

The train fare is 81 yen.

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

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

Sample Input 2

4 54

Sample Output 2

31


N = gets.to_i
T , A = gets.split.map!{|i| i.to_i}
H = gets.split.map!{|i| T - (i.to_i) * 0.006}
min = 10 ** 4
k = 0

N.times do |i|
    if min > (A - H[i]).abs
        min = (A - H[i]).abs
        k = i + 1
    end
end

puts k

Score: 200 points

Problem Statement

A country decides to build a palace.

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

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

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

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

It is guaranteed that the solution is unique.

Constraints

1 \leq N \leq 1000

0 \leq T \leq 50

-60 \leq A \leq T

0 \leq H_i \leq 10^5

All values in input are integers.

The solution is unique.

Input

Input is given from Standard Input in the following format:

N
T A
H_1 H_2 ... H_N

Output

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

Sample Input 1

2
12 5
1000 2000

Sample Output 1

1

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

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

Thus, the palace should be built at Place 1.

Sample Input 2

3
21 -11
81234 94124 52141

Sample Output 2

3


s = gets.split("\n")[0]
if s.size == 3
  p s.reverse
else
  p s
end

Score : 100 points

Problem Statement

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

Constraints

The length of S is 2 or 3.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

abc

Sample Output 1

cba

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

Sample Input 2

ac

Sample Output 2

ac

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


N = gets.to_i
A = gets.split.map(&:to_i)
B = gets.split.map(&:to_i)

limit = B.inject(:+) - A.inject(:+)
cnt1 = 0
cnt2 = 0

A.zip(B).each do |a, b|
  next if a == b

  if a > b
    cnt1 += a - b
  else
    cnt2 += ((b - a) / 2.0).ceil
  end
end

if cnt1 + cnt2 <= limit
  puts 'Yes'
else
  puts 'No'
end

Score : 600 points

Problem Statement

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

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

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

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

2
1 2

Sample Output 1

9

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

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

Therefore, the answer is 5+4=9.

Sample Input 2

4
1 1 1 1

Sample Output 2

212

Sample Input 3

10
1 2 4 8 16 32 64 128 256 512

Sample Output 3

880971923


N = gets.to_i

if N==1
  puts "Hello World"
  exit
end

A = gets.to_i
B = gets.to_i

puts A+B

Score: 100 points

Problem Statement

In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.

One day, there was an exam where a one-year-old child must write a program that prints Hello World, and a two-year-old child must write a program that receives integers A, B and prints A+B.

Takahashi, who is taking this exam, suddenly forgets his age.

He decides to write a program that first receives his age N (1 or 2) as input, then prints Hello World if N=1, and additionally receives integers A, B and prints A+B if N=2.

Write this program for him.

Constraints

N is 1 or 2.

A is an integer between 1 and 9 (inclusive).

B is an integer between 1 and 9 (inclusive).

Input

Input is given from Standard Input in one of the following formats:

1

2
A
B

Output

If N=1, print Hello World; if N=2, print A+B.

Sample Input 1

1

Sample Output 1

Hello World

As N=1, Takahashi is one year old. Thus, we should print Hello World.

Sample Input 2

2
3
5

Sample Output 2

8

As N=2, Takahashi is two years old. Thus, we should print A+B, which is 8 since A=3 and B=5.


N = gets.to_i

if N == 1
  puts 'Hello World'
else
  A = gets.to_i
  B = gets.to_i
  puts A+B
end


N = gets.to_i
A = gets.to_i
B = gets.to_i
if N == 1 then
  puts "Hello World"
else
  puts A+B
end


data = gets.split(" ")
limit = data[1].to_i
count = data[0].to_i

db=Array.new
count.times do |i|
    d = gets.split(" ")
    db.push(d)
end

db = db.find_all {|item| item[1].to_i < limit.to_i}
int = 10000
db.each do |d|
    i = d[0].to_i
    if i < int
        int = i
    end
end
if int == 10000
    puts "TLE"
else
    puts int
end

Score : 200 points

Problem Statement

When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.

You, the smartwatch, has found N routes to his home.

If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.

Find the smallest cost of a route that takes not longer than time T.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq T \leq 1000

1 \leq c_i \leq 1000

1 \leq t_i \leq 1000

The pairs (c_i, t_i) are distinct.

Input

Input is given from Standard Input in the following format:

N T
c_1 t_1
c_2 t_2
:
c_N t_N

Output

Print the smallest cost of a route that takes not longer than time T.

If there is no route that takes not longer than time T, print TLE instead.

Sample Input 1

3 70
7 60
1 80
4 50

Sample Output 1

4

The first route gets him home at cost 7.

The second route takes longer than time T = 70.

The third route gets him home at cost 4.

Thus, the cost 4 of the third route is the minimum.

Sample Input 2

4 3
1 1000
2 4
3 1000
4 500

Sample Output 2

TLE

There is no route that takes not longer than time T = 3.

Sample Input 3

5 9
25 8
5 9
4 10
1000 1000
6 1

Sample Output 3

5


require "prime"

def each_div(primes)
  max = primes.map{|prime| prime[1]}.inject(1){|acc, count| acc *= (count + 1)} - 1

  use_counts = Array.new(primes.size, 0)
  (1..max).each do
    use_counts[0] += 1

    (0..(use_counts.size - 1)).each do |i|
      if use_counts[i] > primes[i][1]
        use_counts[i] = 0

        if i + 1 < use_counts.size
          use_counts[i + 1] += 1
        end
      else
        break
      end
    end

    div = 1
    use_counts.each_with_index do |count, i|
      div *= primes[i][0] ** count
    end

    yield div
  end
end

N, M = STDIN.gets.chomp.split(" ").map(&:to_i)

primes = Prime.prime_division(M).select{|prime| prime[0] <= M / N}

divs = [1]
each_div(primes){|div| divs << div if div <= M / N}
answer = divs.uniq.select{|div| div <= M / N}.max
puts answer

Score : 400 points

Problem Statement

You are given integers N and M.

Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

N \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the maximum possible value of the greatest common divisor of a sequence a_1, a_2, ..., a_N that satisfies the condition.

Sample Input 1

3 14

Sample Output 1

2

Consider the sequence (a_1, a_2, a_3) = (2, 4, 8). Their greatest common divisor is 2, and this is the maximum value.

Sample Input 2

10 123

Sample Output 2

3

Sample Input 3

100000 1000000000

Sample Output 3

10000


N = gets.to_i
a = gets.split.map(&:to_i)
od, ev = {}, {}

if a.uniq.size==1
  p N/2
  exit
end

a.select.with_index{|_,i| i.even?}.each do |n|
  if ev.key?(n)
    ev[n] += 1
  else
    ev[n] = 1
  end
end

a.select.with_index{|_,i| i.odd?}.each do |n|
  if od.key?(n)
    od[n] += 1
  else
    od[n] = 1
  end
end

evmx = ev.max_by{|k,v| v}
odmx = od.max_by{|k,v| v}

if evmx[0] == odmx[0]

  if evmx[1] > odmx[1]
    od.delete(evmx[0])
    p N - ev.max_by{|k,v| v}[1] - od.max_by{|k,v| v}[1]
  elsif evmx[1] < odmx[1]
  	ev.delete(odmx[0])
    p N - ev.max_by{|k,v| v}[1] - od.max_by{|k,v| v}[1]
  else
    ev.delete(odmx[0])
    a1 = N - ev.max_by{|k,v| v}[1] - od.max_by{|k,v| v}[1]
    od.delete(evmx[0])
    a2 = N - ev.max_by{|k,v| v}[1] - od.max_by{|k,v| v}[1]
    p [a1,a2].min
  end
end

p N - ev.max_by{|k,v| v}[1] - od.max_by{|k,v| v}[1]

Score : 300 points

Problem Statement

A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:

For each i = 1,2,..., n-2, a_i = a_{i+2}.

Exactly two different numbers appear in the sequence.

You are given a sequence v_1,v_2,...,v_n whose length is even.
We would like to make this sequence /\/\/\/ by replacing some of its elements.
Find the minimum number of elements that needs to be replaced.

Constraints

2 \leq n \leq 10^5

n is even.

1 \leq v_i \leq 10^5

v_i is an integer.

Input

Input is given from Standard Input in the following format:

n
v_1 v_2 ... v_n

Output

Print the minimum number of elements that needs to be replaced.

Sample Input 1

4
3 1 3 2

Sample Output 1

1

The sequence 3,1,3,2 is not /\/\/\/, but we can make it /\/\/\/ by replacing one of its elements: for example, replace the fourth element to make it 3,1,3,1.

Sample Input 2

6
105 119 105 119 105 119

Sample Output 2

0

The sequence 105,119,105,119,105,119 is /\/\/\/.

Sample Input 3

4
1 1 1 1

Sample Output 3

2

The elements of the sequence 1,1,1,1 are all the same, so it is not /\/\/\/.


a = gets
b = gets
ac = 0
bc = 0
("a".."z").each do |hoge|
    if a.count(hoge) % 2 == 0 and a.count(hoge) != 0 then
        ac += 1
    end
    if b.count(hoge) % 2 == 0 and b.count(hoge) != 0 then
        bc += 1
    end
end
puts ac == bc ? "YES" : "NO"

Score : 300 points

Problem Statement

You are given strings S and T consisting of lowercase English letters.

You can perform the following operation on S any number of times:

Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.

Determine if S and T can be made equal by performing the operation zero or more times.

Constraints

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

|S| = |T|

S and T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S and T can be made equal, print Yes; otherwise, print No.

Sample Input 1

azzel
apple

Sample Output 1

Yes

azzel can be changed to apple, as follows:

Choose e as c_1 and l as c_2. azzel becomes azzle.

Choose z as c_1 and p as c_2. azzle becomes apple.

Sample Input 2

chokudai
redcoder

Sample Output 2

No

No sequences of operation can change chokudai to redcoder.

Sample Input 3

abcdefghijklmnopqrstuvwxyz
ibyhqfrekavclxjstdwgpzmonu

Sample Output 3

Yes


S, T = readlines.map(&:chomp)

st = S
(0 ... S.length).each do |i|
  s, t = S[i], T[i]
  unless s == t
    st.tr!(s + t, t + s)
  end
end
puts st == T ? 'Yes' : 'No'


s = gets.chomp.split(//)
t = gets.chomp.split(//)
s.length.times do |j|
    next if s[j] == t[j]
    c1, c2 = s[j], t[j]
    s.length.times do |i|
        if s[i] == c1
            s[i] = c2
            next
        elsif s[i] == c2
            s[i] = c1

        end
    end
end

puts s == t ? "Yes" : "No"


s=gets.chomp
t=gets.chomp
h1 = {}
h2 = {}
0.upto(s.size-1) do |i|
    next if s[i] == t[i]
    if h1.has_key?(s[i])
        if h1[s[i]] != t[i]
            puts "No"
            exit
        end
    elsif h2.has_key?(t[i])
        if h2[t[i]] != s[i]
            puts "No"
            exit
        end
    else
        h1[s[i]] = t[i]
        h2[t[i]] = s[i]
    end
end

puts "Yes"


n, x = gets.split.map &:to_i
a = gets.split.map(&:to_i).sort
r = 0
j = 0
(0...n).each do |i|
  x -= a[i]
  if x == 0
    puts j + 1
    exit
  elsif i + 1 < n && a[i+1] > x
    puts j
    exit
  else
    j += 1
  end
end

puts x > 0 ? j - 1 : j

Score : 200 points

Problem Statement

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

Snuke has decided to distribute x sweets among them.
He needs to give out all the x sweets, but some of the children may get zero sweets.

For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets.
Snuke is trying to maximize the number of happy children by optimally distributing the sweets.
Find the maximum possible number of happy children.

Constraints

All values in input are integers.

2 \leq N \leq 100

1 \leq x \leq 10^9

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the maximum possible number of happy children.

Sample Input 1

3 70
20 30 10

Sample Output 1

2

One optimal way to distribute sweets is (20, 30, 20).

Sample Input 2

3 10
20 30 10

Sample Output 2

1

The optimal way to distribute sweets is (0, 0, 10).

Sample Input 3

4 1111
1 10 100 1000

Sample Output 3

4

The optimal way to distribute sweets is (1, 10, 100, 1000).

Sample Input 4

2 10
20 20

Sample Output 4

0

No children will be happy, no matter how the sweets are distributed.


N,x=gets.split.map &:to_i
a=gets.split.map(&:to_i).sort
c=0
N.times{|i|
  if x>=a[i] then
    x-=a[i]
    c+=1
  end
}
p c


n, x = gets.split(' ').map(&:to_i)
a = gets.split(' ').map(&:to_i)
a.sort!
k = 0
a.each { |e|
  if (x - e >= 0)
    x = x - e
    k += 1
  end
}

p k


x1, y1, x2, y2 = gets.split(' ').map(&:to_i)
diff_x = x2 - x1
diff_y = y2 - y1

if diff_x > 0 && diff_y > 0
  x3 = x2 - diff_y
  y3 = y2 + diff_x
  x4 = x1 - diff_y
  y4 = y1 + diff_x
elsif diff_x > 0 && diff_y < 0
  x3 = x2 + diff_y
  y3 = y2 + diff_x
  x4 = x1 + diff_y
  y4 = y1 + diff_x
elsif diff_x < 0 && diff_y > 0
  x3 = x2 - diff_y
  y3 = y2 + diff_x
  x4 = x1 - diff_y
  y4 = y1 + diff_x
elsif diff_x < 0 && diff_y < 0
  x3 = x2 + diff_y
  y3 = y2 + diff_x
  x4 = x1 + diff_y
  y4 = y1 - diff_x
elsif diff_x.zero?
  y3 = y2
  y4 = y1
  if diff_y < 0
    x3 = x2 + diff_y
    x4 = x1 + diff_y
  elsif diff_y > 0
    x3 = x2 - diff_y
    x4 = x1 - diff_y
  end
elsif diff_y.zero?
  x3 = x2
  x4 = x1
  if diff_x < 0
    y3 = y2 - diff_x
    y4 = y1 - diff_x
  elsif diff_x > 0
    y3 = y2 + diff_x
    y4 = y1 + diff_x
  end
end

puts "#{x3} #{y3} #{x4} #{y4}"

Score : 200 points

Problem Statement

There is a square in the xy-plane. The coordinates of its four vertices are (x_1,y_1),(x_2,y_2),(x_3,y_3) and (x_4,y_4) in counter-clockwise order.
(Assume that the positive x-axis points right, and the positive y-axis points up.)

Takahashi remembers (x_1,y_1) and (x_2,y_2), but he has forgot (x_3,y_3) and (x_4,y_4).

Given x_1,x_2,y_1,y_2, restore x_3,y_3,x_4,y_4. It can be shown that x_3,y_3,x_4 and y_4 uniquely exist and have integer values.

Constraints

|x_1|,|y_1|,|x_2|,|y_2| \leq 100

(x_1,y_1) ≠ (x_2,y_2)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

x_1 y_1 x_2 y_2

Output

Print x_3,y_3,x_4 and y_4 as integers, in this order.

Sample Input 1

0 0 0 1

Sample Output 1

-1 1 -1 0

(0,0),(0,1),(-1,1),(-1,0) is the four vertices of a square in counter-clockwise order.
Note that (x_3,y_3)=(1,1),(x_4,y_4)=(1,0) is not accepted, as the vertices are in clockwise order.

Sample Input 2

2 3 6 6

Sample Output 2

3 10 -1 7

Sample Input 3

31 -41 -59 26

Sample Output 3

-126 -64 -36 -131


(n, k) = gets.chomp.split(' ').map(&:to_i)

m = n / k

c = m ** 3

if k % 2 == 0 then
  l = m
  if (n % k) < (k / 2) then
  	l += 1
  end
  c += (l ** 3)
end

puts c.to_s

Score : 300 points

Problem Statement

You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.
The order of a,b,c does matter, and some of them can be the same.

Constraints

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

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.

Sample Input 1

3 2

Sample Output 1

9

(1,1,1),(1,1,3),(1,3,1),(1,3,3),(2,2,2),(3,1,1),(3,1,3),(3,3,1) and (3,3,3) satisfy the condition.

Sample Input 2

5 3

Sample Output 2

1

Sample Input 3

31415 9265

Sample Output 3

27

Sample Input 4

35897 932

Sample Output 4

114191