a, i = gets.chomp.split.map(&:to_i)
n = Array.new(a)
d = Array.new
a.times do |hoge|
    n[hoge] = gets.chomp.split.map(&:to_i)
    n[hoge].delete_at(0)
    if hoge != 0 then
        d = n[hoge] & n[hoge - 1]
        n[hoge] = d
    end
end
puts d.size

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


st = gets.chomp!.split(" ")
n = st[0].to_i

st = gets.chomp!.split(" ")
s = st.size-1
AMO = [nil,2,5,5,4,5,6,3,7,6]
num = Hash.new
ans = ""

for i in 0..s
    num[AMO[st[i].to_i]] = st[i].to_i
end

num = num.sort{|a,b| a[0] <=> b[0]}

if n >= num[0][0]
    (n/num[0][0]).times do
        ans += "#{num[0][1]}"
    end
end

n %= num[0][0]
x = num[0][0]
y = num[0][1]

num = num.sort{|a,b| -a[1] <=> -b[1]}
i = 0
j = 0

while n != 0
    if x == num[i][0]
        break
    end

    if n < num[i][0] - x
        i += 1
        next
    end

    ans[j] = "#{num[i][1]}"
    j += 1
    i += 1
    n -= num[i][0]-x
    redo
end

num = num.sort{|a,b| a[1] <=> b[1]}
i = 0
j = ans.size-1

while n != 0
    if x == num[i][0]
        break
    end

    if n < num[i][0] - x
        i += 1
        next
    end

    ans[j] = "#{num[i][1]}"
    j -= 1
    n -= num[i][0] - x
end

puts ans

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

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

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.


k,a,b = gets.chomp.split.map(&:to_i)
ans = 0
if a + 3 < b && (k >= a + 1)
  ans += b
  k = k - (a + 1)
  ans += (b-a)*(k/2)
  ans += k%2
else
  ans = k + 1
end

puts ans

Score : 400 points

Problem Statement

Snuke has one biscuit and zero Japanese yen (the currency) in his pocket.
He will perform the following operations exactly K times in total, in the order he likes:

Hit his pocket, which magically increases the number of biscuits by one.

Exchange A biscuits to 1 yen.

Exchange 1 yen to B biscuits.

Find the maximum possible number of biscuits in Snuke's pocket after K operations.

Constraints

1 \leq K,A,B \leq 10^9

K,A and B are integers.

Input

Input is given from Standard Input in the following format:

K A B

Output

Print the maximum possible number of biscuits in Snuke's pocket after K operations.

Sample Input 1

4 2 6

Sample Output 1

7

The number of biscuits in Snuke's pocket after K operations is maximized as follows:

Hit his pocket. Now he has 2 biscuits and 0 yen.

Exchange 2 biscuits to 1 yen. his pocket. Now he has 0 biscuits and 1 yen.

Hit his pocket. Now he has 1 biscuits and 1 yen.

Exchange 1 yen to 6 biscuits. his pocket. Now he has 7 biscuits and 0 yen.

Sample Input 2

7 3 4

Sample Output 2

8

Sample Input 3

314159265 35897932 384626433

Sample Output 3

48518828981938099


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


a = gets.to_i
b = gets.split.map(&:to_i).sort
sum = 0
for num in 0..a-2 do
  sum += b[num]
end

if sum > b[-1]
  puts "Yes"
else
  puts "No"
end

Score : 200 points

Problem Statement

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

You can use the following theorem:

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

Constraints

All values in input are integers.

3 \leq N \leq 10

1 \leq L_i \leq 100

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Output

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

Sample Input 1

4
3 8 5 1

Sample Output 1

Yes

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

Sample Input 2

4
3 8 4 1

Sample Output 2

No

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

Sample Input 3

10
1 8 10 5 8 12 34 100 11 3

Sample Output 3

No


n = gets.to_i
l = gets.split.map(&:to_i).sort
max = l.pop

puts l.inject(:+) > max ? 'Yes' : 'No'


gets
ls = gets.chomp.split(' ').map(&:to_i)
longest = ls.max
ls.delete_at(ls.index(longest))
puts ls.reduce(:+) > longest ? 'Yes' : 'No'


def main()
  n = gets.chomp.to_i
  inputL = gets.chomp.strip
  l = []
  sum = 0
  can_be_drawn = 'Yes'
  for i in 1..n do
    l[i] = inputL.split(' ').map(&:to_i)[i-1]
    sum += l[i]
  end

  for i in 1..n do
    can_be_drawn = 'No' if 2*l[i] >= sum
  end

  puts "#{can_be_drawn}"
end
main


N = gets.to_i
L = gets.split().map(&:to_i)
max = L.max
sum = 0
N.times{|i| sum += L[i]}
puts max < sum - max ? 'Yes' : 'No'


# frozen_string_literal: true

INFINITY = 10000000
$min = INFINITY
$n, $m = gets.split.map(&:to_i)
x = gets.split.map(&:to_i)

if $n >= $m
  puts 0
  exit 0
end

$sorted_x = x.sort

def diff(pos1, pos2)
  $sorted_x[pos2] - $sorted_x[pos1]
end

def score(prevpos, pos)
  return 0 if pos - 2 < prevpos

  (prevpos..(pos - 2)).to_a.inject(0) { |sum, i| sum += diff(i, i + 1) }
end

# [x, x, x, x, x, x, x]   i: n - ( i + 1 )
def dfs(i, prevpos, pos)
  return score(prevpos, pos) + score(pos, $m) if i == $n - 1
  return INFINITY if pos >= $m - 1

  sc = score(prevpos, pos)
  return INFINITY if sc > $min
  a_min = (pos+1..$m - $n + i + 1).to_a.map { |p| dfs(i + 1, pos, p) }.min
  s = sc + a_min
  $min = [s, $min].min
  s
end

puts dfs(0, 0, 0)

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


# https://atcoder.jp/contests/abc117/tasks/abc117_c

input_temp = gets.chomp.split(" ")
koma_count = input_temp[0].to_i    # 駒
zahyo_count = input_temp[1].to_i   # 座標

input_temp = gets.chomp.split(" ")
zahyo_position = input_temp.map(&:to_i)

# print "koma_count=",koma_count,"\n"
# print "zahyo_count=",zahyo_count,"\n"
# print "zahyo_position=",zahyo_position,"\n"

# 累積話問題読み

zahyo_position.sort!
kaisa_zahyo_position = []

# 階差
(zahyo_count-1).times do |i|
    kaisa_zahyo_position[i] = (zahyo_position[i+1] - zahyo_position[i]).abs
end

kaisa_zahyo_position = kaisa_zahyo_position.sort.reverse

if kaisa_zahyo_position.size <= (koma_count-1)
    p 0
    exit
end

kaisa_zahyo_position.shift(koma_count-1)

# p kaisa_zahyo_position

puts kaisa_zahyo_position.inject(:+)


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

puts [a, b].min
tmp = [a, b].max - (n-[a, b].min)
puts tmp>=0? tmp : 0

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.to_i
a = gets
b = gets
c = gets

split_words_a = a.split("")
split_words_b = b.split("")
split_words_c = c.split("")
i = 0
ancer = 0

n.times do
  if split_words_a[i] == split_words_b[i] && split_words_b[i] == split_words_c[i]
    i += 1
    next
  elsif split_words_a[i] == split_words_b[i]
    ancer += 1
  elsif split_words_a[i] == split_words_c[i]
    ancer += 1
  elsif split_words_b[i] == split_words_c[i]
    ancer += 1
  else
    ancer += 2
  end
  i += 1
end

puts ancer

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, M = gets.split.map(&:to_i)
edge_list = (N - 1 + M).times.map { gets.split.map(&:to_i) }
graph = Array.new(N) { [] }
indegree = Array.new(N) { 0 }
edge_list.each do |(u, v)|
  u -= 1; v -= 1
  graph[u].push(v)
  indegree[v] += 1
end

sorted = []
queue = []
indegree.each.with_index do |c, v|
  queue.push(v) if c == 0
end
while !queue.empty?
  v = queue.shift
  (graph[v]).each do |v2|
    indegree[v2] -= 1
    if indegree[v2] == 0
      queue.push(v2)
      sorted.push(v)
    end
  end
end

v_to_order = sorted.map.with_index { |v, i| [v, i] }.to_h
ans = Array.new(N) { sorted[0] }
ans[sorted[0]] = 0
edge_list.each do |(u, v)|
  u -= 1
  v -= 1
  ans[v] = u if v_to_order[u] > v_to_order[ans[v]]
end
ans.each.with_index do |v, i|
  if i == sorted[0]
    puts 0
  else
    puts(v + 1)
  end
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


s = gets.to_i

def f(n)
  ret = 0
  if n.even?
    ret = n /2
  else
    ret = 3 * n + 1
  end
  ret
end

list = []
list[0] = s
i = 1
loop do
  v = f(list[i-1])
  list[i] = v
  break if v == 4
  i += 1
end

ans = 10000000
for i in 0..(list.size - 2) do
  for j in (i+1)..(list.size - 1) do
    v1 = list[i]
    v2 = list[j]
    if v1 == v2 && j < ans
      ans = j
    end
  end
end

if ans == 10000000
  ans = list.size + 3
end

puts ans

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


s=gets.to_i
h = {}
2.upto(1000000) do |i|
#  puts s
  if s.odd?
    s = 3 * s + 1
  else
    s = s/2
  end
  if h.has_key?(s)
    puts i
    exit
  else
    h[s] = 1
  end
end


n = gets.chomp.to_i
a = gets.chomp.split.map(&:to_i)

v = [0] * n
ans = 0
for i in 0...n
  while v[i] < a[i]
    ans += 1
    it = i
    while it<n && v[it] < a[it]
      v[it] += 1
      it += 1
    end
  end
end
puts ans

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


s = gets.chomp
array = s.split("")
str = "keyence"
answer = "NO"
if s[0,7] == str
  answer = "YES"
end
if s[-7,7] == str
  answer = "YES"
end

for i in (0..5)
  if s[i] ==  str[i]
    if s[-(6-i),(6-i)] == str[i+1,6-i]
    answer ="YES"
  end
end
end
puts answer

Score : 200 points

Problem Statement

A string is called a KEYENCE string when it can be changed to keyence by removing its contiguous substring (possibly empty) only once.

Given a string S consisting of lowercase English letters, determine if S is a KEYENCE string.

Constraints

The length of S is between 7 and 100 (inclusive).

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a KEYENCE string, print YES; otherwise, print NO.

Sample Input 1

keyofscience

Sample Output 1

YES

keyence is an abbreviation of key of science.

Sample Input 2

mpyszsbznf

Sample Output 2

NO

Sample Input 3

ashlfyha

Sample Output 3

NO

Sample Input 4

keyence

Sample Output 4

YES


n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
b = gets.chomp.split(" ").map(&:to_i)
a_m = a.clone

diff = a.map.with_index{|x,i| x - b[i]}

n.times do |i|
  if diff[i] < 0
    if diff.max > 0
      a[diff.index(diff.max)] += diff[i]
      a[i] -= diff[i]
      diff[diff.index(diff.max)] += diff[i]
    else
      puts "-1"
      exit
    end
  end
#  diff = a.map.with_index{|x,i| x - b[i]}
end

count = 0
a_m.each_with_index do |x,i|
  count += 1 if x != a[i]
end

puts count

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


def ascan; gets.split.map(&:to_i); end

N = gets.to_i
A, B = ascan
P = ascan

x1 = 0
x2 = 0
x3 = 0

P.each do |pt|
    x1 += 1 if pt <= A
    x2 += 1 if A < pt && pt <= B
    x3 += 1 if B < pt
end

p [x1,x2,x3].min

Score : 200 points

Problem Statement

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

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

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

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

Constraints

3 \leq N \leq 100

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

1 \leq A < B < 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A B
P_1 P_2 ... P_N

Output

Print the answer.

Sample Input 1

7
5 15
1 10 16 2 7 20 12

Sample Output 1

2

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

Sample Input 2

8
3 8
5 5 5 10 10 10 15 20

Sample Output 2

0

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

Sample Input 3

3
5 6
5 6 10

Sample Output 3

1


WV = $<.read.split.map(&:to_i).each_slice(2).to_a
N,W = WV.shift
WV.sort_by! {|w,v| w>W ? 1<<60 : (v<<30)+w}
I = {}
tv=tw = 0
I[1<<60] = WV.each_with_index.count {|(w,v),i| break i if w>W; I[v]||=i; tv+=v; tw+=w}
K = I.keys
A = Array.new(tv+1, [0,tw,(1<<I[K[-1]])-1])
A[0] = [0,0,0]
l = tw > W ? 0 : tv
l.upto(tv) {|n|
  y,c,b = A[n]
  l = n if c <= W
  next  if c >= W
  K.each_cons(2) {|v,w|
    i,j = I[v],I[w]
    next  if v < y || b[j-1] > 0
    x = b | b+(1<<i)
    i += 1  while b[i] > 0
    w = c + WV[i][0]
    A[v+n] = [v,w,x]  if A[v+n][1] > w
  }
}
p l

Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^9

1 \leq w_i \leq W

1 \leq v_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

1 1000000000
1000000000 10

Sample Output 2

10

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.


def agc_030_a
    a,b,c = gets.chomp.split(/\s/).map{|x| x.to_i}

    t = 0

    if b >= c
        b -= c
        t += c * 2
        c = 0
    else
        c -= b
        t += b * 2
        b = 0
    end

    if c > 0
        if a >= c
            a -= c
            t += c
            c = 0
        else
            c -= a
            t += a
            a = 0
        end
    end

    if a > 0 && b > 0
        if a >= b
            a -= b
            t += b
            b = 0
        else
            b -= a
            t += a
            a = 0
        end
    end

    t += 1 if c > 0

    puts t
end

agc_030_a

Score : 200 points

Problem Statement

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

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

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

Constraints

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

A,B and C are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

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

Sample Input 1

3 1 4

Sample Output 1

5

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

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

A tasty cookie containing antidotes

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

Sample Input 2

5 2 9

Sample Output 2

10

Sample Input 3

8 8 1

Sample Output 3

9


a,b,c = gets.split(" ").map!{|p| p.to_i}
#d 食べられるｃの最大値
if c > a + b
  d = a + b + 1
elsif c == a + b
  d = a + b
else
  d = c
end
# e 食べるおいしいクッキーの最大値
e = b + d
puts e


l, n = gets.chomp.split.map(&:to_i)
x = Array.new(n)
for i in 0..(n-1)
  x[i] = gets.chomp.to_i
end
ans = 0
now = 0
first = 0
last = n-1
loop do
  distf = distl = nextid = 0
  if now < x[last]
    distf = x[first] - now
    distl = l - x[last] + now
  else
    distf = l - now + x[first]
    distl = now - x[last]
  end
  if distf > distl
    ans += distf
    nextid = first
    first += 1
  elsif distf < distl
    ans += distl
    nextid = last
    last -= 1
  else
    idf = first + 1
    idl = last - 1
    loop do
      if first + 1 == last
        ans += distf
        nextid = first
        first += 1
        break
      elsif x[idf] - x[idf-1] != x[idl+1] - x[idl]
        if x[idf] - x[idf-1] > x[idl+1] - x[idl]
          ans += distf
          nextid = first
          first += 1
        else
          ans += distl
          nextid = last
          last -= 1
        end
        break
      end
      idf += 1
      idl -= 1
    end
  end
  if first > last
    break
  end
  now = x[nextid]
end
puts ans

Score : 800 points

Problem Statement

Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi.
Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distance from the Takahashi's residence, measured counter-clockwise.

There are N trees around the lake; the coordinate of the i-th tree is X_i. There is no tree at coordinate 0, the location of Takahashi's residence.

Starting at his residence, Takahashi will repeat the following action:

If all trees are burnt, terminate the process.

Specify a direction: clockwise or counter-clockwise.

Walk around the lake in the specified direction, until the coordinate of a tree that is not yet burnt is reached for the first time.

When the coordinate with the tree is reached, burn that tree, stay at the position and go back to the first step.

Find the longest possible total distance Takahashi walks during the process.

Partial Score

A partial score can be obtained in this problem:

300 points will be awarded for passing the input satisfying N \leq 2000.

Constraints

2 \leq L \leq 10^9

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

1 \leq X_1 < ... < X_N \leq L-1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

L N
X_1
:
X_N

Output

Print the longest possible total distance Takahashi walks during the process.

Sample Input 1

10 3
2
7
9

Sample Output 1

15

Takahashi walks the distance of 15 if the process goes as follows:

Walk a distance of 2 counter-clockwise, burn the tree at the coordinate 2 and stay there.

Walk a distance of 5 counter-clockwise, burn the tree at the coordinate 7 and stay there.

Walk a distance of 8 clockwise, burn the tree at the coordinate 9 and stay there.

Sample Input 2

10 6
1
2
3
6
7
9

Sample Output 2

27

Sample Input 3

314159265 7
21662711
77271666
89022761
156626166
160332356
166902656
298992265

Sample Output 3

1204124749


a = gets.chomp.split.map{|aa|aa.to_i}
require 'prime'
b = a[1].prime_division
anan = Array.new(b.size).map{Array.new}
ans = []
for bb in 0...b.size
  b[bb][1].times do
    anan[bb].push(b[bb][0])
  end
end
for bb in 0...anan.size
  if (anan[bb].size / a[0]) >= 1
    ans.push(anan[bb][0])
  end
end
aaaa = 1
puts ans.map{|aaa|aaaa = aaaa*aaa}.pop

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
a = n.times.map{ gets.to_i }
if a.any?{ |k| k.odd? } then puts 'first'
else puts 'second'
end

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


require 'prime'

N,P=gets.chomp.split.map(&:to_i)
ans=1
Prime.prime_division(P).each do |a,b|
  next if b < N

  ans *= (a ** (b/N))
end
puts ans


S = gets.chomp.chars

ans = 0
cnt = 0 # The count of white on right in each step i.

N = S.size
(N - 1).downto(0).each do |i|
  c = S[i]
  if (c == 'W')
    cnt += 1
  else # c == 'B'
    ans += cnt
  end
end

p ans

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


str = gets.chomp
sumCount = 0
loop do
  nowCount = str.scan("BW").length
  break if nowCount == 0
  sumCount += nowCount
  str.gsub!(/BW/,"WB")
end

puts sumCount


input = gets.to_s
arrayInput = []
arrayInput =  input.split("")
loopTimes = 0

existBW = true

while (true) do
 existBW = false
 for times in 0..arrayInput.size - 1 do
  if arrayInput[times] == "B" && arrayInput[times + 1] == "W" then
    arrayInput[times] = "W"
    arrayInput[times + 1] = "B"
    loopTimes = loopTimes + 1
    existBW = true
  end
 end

 if  existBW == false then
   break
 end

end

puts loopTimes


N=gets.to_i
p=[]
N.times{
  t=gets.to_i
  p.push(t)
}
p.sort
puts p[N-1]/2+p.slice(0..N-2).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.


firstLineInput = gets.to_s
numOfTree = firstLineInput.split(" ")[0].to_i
numOflightedTree = firstLineInput.split(" ")[1].to_i

arrayOfTrees = []
for times in 1.. numOfTree do
  arrayOfTrees<<gets.to_i
end

arrayOfTrees.sort!
arrayOfDiffs = []

for times in 0..arrayOfTrees.size - numOflightedTree do
  arrayOfThreeTrees = []
  for times2 in 0..numOflightedTree-1 do
   arrayOfThreeTrees << arrayOfTrees[times + times2]
  end
  p arrayOfThreeTrees
  arrayOfDiffs << arrayOfThreeTrees.max - arrayOfThreeTrees.min
end

puts arrayOfDiffs.min

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)
trees = n.times.map{ gets.to_i }.sort
min = trees[-1] - trees[0]
(n-k+1).times do |i|
  dif = trees[i+k-1] - trees[i]
  if dif < min
    min = dif
  end
end
puts min


def burger(l)
  if l == 0
    'P'
  else
    'B' + burger(l -1) + 'P' + burger(l -1) + 'B'
  end
end

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

burger = burger(N)
puts burger.slice(0..(X - 1)).count('P')

Score : 400 points

Problem Statement

In some other world, today is Christmas.

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

A level-0 burger is a patty.

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

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

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

Constraints

1 \leq N \leq 50

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

N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

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

Sample Input 1

2 7

Sample Output 1

4

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

Sample Input 2

1 1

Sample Output 2

0

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

Sample Input 3

50 4321098765432109

Sample Output 3

2160549382716056

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


n = gets.strip.to_i
r = 'NO'
r = 'YES' if n == 7 || n == 5 || n == 3
puts r

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.


#754
s = gets.split('').map(&:to_i)
ans = []
(s.size - 3).times do |i|
	x = 0
	vessel = []
	vessel << s[i]
	vessel << s[i + 1]
	vessel << s[i + 2]
	x = vessel.join.to_i

	ans << (753 - x).abs
end

puts ans.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.


n = gets.to_i

c = 0

for d in 3..(n.to_s.length) do
  [7, 5, 3].repeated_permutation(d).to_a.uniq() do |num|
    c += 1 if num.include?(3) && num.include?(5) && num.include?(7) && num.join.to_i <= n

  end
end

p c

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,k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = Array.new
m = n*(n+1)/2

sum = 0
for i in 0..n-1
    sum = 0
    for j in i..n-1
        sum += a[j]
        b.push(sum)
    end
end

ret = 0
cnt = 0
used = Array.new(m,true)
41.downto(1) do |i|
    t = 1 << i
    for j in 0..m-1
        b[j] %= t
    end
    cnt = 0
    temp = Array.new(m,true)
    for j in 0..m-1
        cnt += 1 if b[j] >= (t >> 1) && used[j]
    end

    if cnt >= k
        for j in 0..m-1
            used[j] = false if (b[j] < (t >> 1))
        end
        ret += (t >> 1)
    end
end
puts ret

Score : 400 points

Problem Statement

One day, Niwango-kun, an employee of Dwango Co., Ltd., found an integer sequence (a_1, ..., a_N) of length N.
He is interested in properties of the sequence a.

For a nonempty contiguous subsequence a_l, ..., a_r (1 \leq l \leq r \leq N) of the sequence a, its beauty is defined as a_l + ... + a_r. Niwango-kun wants to know the maximum possible value of the bitwise AND of the beauties of K nonempty contiguous subsequences among all N(N+1)/2 nonempty contiguous subsequences. (Subsequences may share elements.)

Find the maximum possible value for him.

Constraints

2 \leq N \leq 1000

1 \leq a_i \leq 10^9

1 \leq K \leq N(N+1)/2

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 ... a_N

Output

Print the answer.

Sample Input 1

4 2
2 5 2 5

Sample Output 1

12

There are 10 nonempty contiguous subsequences of a. Let us enumerate them:

contiguous subsequences starting from the first element: \{2\}, \{2, 5\}, \{2, 5, 2\}, \{2, 5, 2, 5\}

contiguous subsequences starting from the second element: \{5\}, \{5, 2\}, \{5, 2, 5\}

contiguous subsequences starting from the third element: \{2\}, \{2, 5\}

contiguous subsequences starting from the fourth element: \{5\}

(Note that even if the elements of subsequences are equal, subsequences that have different starting indices are considered to be different.)

The maximum possible bitwise AND of the beauties of two different contiguous subsequences is 12.
This can be achieved by choosing \{5, 2, 5\} (with beauty 12) and \{2, 5, 2, 5\} (with beauty 14).

Sample Input 2

8 4
9 1 8 2 7 5 6 4

Sample Output 2

32


n1,n2 = gets.chomp.split(" ").map(&:to_i)
ar = gets.chomp.split(" ").map(&:to_i)
bi = []
for i in 0..n1 - 1
  inst = 0
  for j in i..n1 - 1
    inst += ar[j]
    bi.push(inst)
  end
end
bi = bi.sort
two = [2]
for i in 0..29
  two.push(two[-1]*2)
  if two[-1] > bi[-1]
    two.delete_at(-1)
    break
  end
end
two.push(0)

minus = 0
res = []
for j in 1..3
  minus += two[-j]
  ans = (bi[-1] - minus)
  for i in 2..n2
    ans = (ans & (bi[-i] - minus))
  end
  res.push(ans)
  if two[-j] == 2
    break
  end
end
res = res.sort
puts res[-1]


x, y = gets.chomp.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.chomp.split.map(&:to_f)
H = gets.chomp.split.map(&:to_f)

sub = 0xffffffff
ans = -1

H.each.with_index(1) do |hi, i|
  s = (A - (T - hi * 0.006)).abs
  if s < sub
    sub = s
    ans = i
  end
end

puts ans

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


amo = gets.to_i
t, goal = gets.split.map(&:to_i)
places = gets.chomp.strip.split.map(&:to_i)

temps = places.map{|place| t - place * 0.006}

temps.map!{|temp| (goal - temp).abs}

puts temps.rindex(temps.min) + 1


io = STDIN
n=io.gets.to_i
t,a=io.gets.split.map(&:to_i)
h=io.gets.split.map(&:to_i)
def temp(t,x)
  (t-x*0.006)
end
ar= h.map.with_index(1){|hh,i|[(temp(t,hh)-a).abs,i]}
puts ar.min_by{|diff,no|diff}[1]


H, W, K = gets.split.map(&:to_i)
MOD = 10 ** 9 + 7
dp = Array.new(H + 1) { Array.new(W, 0) }
dp[0][0] = 1
H.times do |h|
  # ある高さにおいて、2^(W-1)通りの横線の引き方がある
  (0...(1 << (W - 1))).each do |bit|
    W.times do |w|
      # check
      # 正しくないあみだくじを弾く
      # 1が連続して2つあったらアウト
      flag = false
      (1...W).each do |i|
        if bit[i] == 1 && bit[i - 1] == 1
          flag = true
        end
      end
      next if flag
      # transition
      if w != W - 1 && bit[w] == 1
        target = w + 1
      elsif w != 0 && bit[w - 1] == 1
        target = w - 1
      else
        target = w
      end
      dp[h + 1][target] = (dp[h + 1][target] + dp[h][w]) % MOD
    end
  end
end
puts dp[H][K - 1]

Score: 400 points

Problem Statement

Amidakuji is a traditional method of lottery in Japan.

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

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

No two horizontal lines share an endpoint.

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

A horizontal line must connect adjacent vertical lines.

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

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

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

H W K

Output

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

Sample Input 1

1 3 2

Sample Output 1

1

Only the following one amidakuji satisfies the condition:

Sample Input 2

1 3 1

Sample Output 2

2

Only the following two amidakuji satisfy the condition:

Sample Input 3

2 3 3

Sample Output 3

1

Only the following one amidakuji satisfies the condition:

Sample Input 4

2 3 1

Sample Output 4

5

Only the following five amidakuji satisfy the condition:

Sample Input 5

7 1 1

Sample Output 5

1

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

Sample Input 6

15 8 5

Sample Output 6

437760187

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


N = gets.to_i

def calc(list)
	prev = list[0]
	sum = 0
	list[1..-1].each{|n|
		sum += (prev - n).abs
		prev = n
	}
	sum
end

list = []
N.times{
	list << gets.to_i
}

list.sort!

def arrange(list)
	first = 0
	last = N - 1
	result = [list[first]]
	first += 1
	while first <= last
		result << list[last]
		last -= 1
		break if first > last
		result.unshift(list[last])
		last -= 1
		break if first > last
		result << list[first]
		first += 1
		break if first > last
		result.unshift(list[first])
		first += 1
	end
	result
end

c1 = calc(arrange(list))
c2 = calc(arrange(list.reverse))

puts [c1, c2].max

Score : 400 points

Problem Statement

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

Constraints

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

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

Sample Input 1

5
6
8
1
2
3

Sample Output 1

21

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

Sample Input 2

6
3
1
4
1
5
9

Sample Output 2

25

Sample Input 3

3
5
5
1

Sample Output 3

8


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.


a=gets
if a.size==2
puts a
else
puts a.reverse
end


a = gets.chomp
if a.length == 3
  puts a.reverse
elsif a.length == 2
  puts a
end


a,b,k = gets.split.map(&:to_i)
k.times do
    a -= 1 if a.odd?
    b += a/2
    a /= 2
    a,b = b,a
end
puts k.odd? ? "#{b} #{a}" : "#{a} #{b}"

Score : 200 points

Problem Statement

In the beginning, Takahashi has A cookies, and Aoki has B cookies.
They will perform the following operation alternately, starting from Takahashi:

If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person.

Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total.

Constraints

1 \leq A,B \leq 10^9

1 \leq K \leq 100

A,B and K are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total.

Sample Input 1

5 4 2

Sample Output 1

5 3

The process will go as follows:

In the beginning, Takahashi and Aoki have 5 and 4 cookies, respectively.

Takahashi eats one cookie and gives two cookies to Aoki. They now have 2 and 6 cookies, respectively.

Aoki gives three cookies to Takahashi. They now have 5 and 3 cookies, respectively.

Sample Input 2

3 3 3

Sample Output 2

1 3

Sample Input 3

314159265 358979323 84

Sample Output 3

448759046 224379523


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

k.times do |i|
  if i % 2 == 0
    a -= 1 if a.odd?
    a /= 2
    b += a
  else
    b -= 1 if b.odd?
    b /= 2
    a += b
  end
end
puts "#{a} #{b}"


def gcd(lhs, rhs)
  return lhs if rhs == 0
  return gcd(rhs, lhs) if lhs < rhs

  mod = lhs % rhs
  div = lhs / rhs

  return gcd(rhs, mod)
end

s_length, t_length = gets.split.map(&:to_i)
s = gets.chomp
t = gets.chomp

gcd_res = gcd(s_length, t_length)
x_length = s_length * t_length / gcd_res

ok = true
(x_length / gcd_res).times do |i|
  if s[i * s_length / gcd_res] != t[i * t_length / gcd_res]
    ok = false
    break
  end
end

if ok
  puts x_length
else
  puts -1
end

Score : 300 points

Problem Statement

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

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

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

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

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

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

Constraints

1 \leq N,M \leq 10^5

S and T consist of lowercase English letters.

|S|=N

|T|=M

Input

Input is given from Standard Input in the following format:

N M
S
T

Output

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

Sample Input 1

3 2
acp
ae

Sample Output 1

6

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

Sample Input 2

6 3
abcdef
abc

Sample Output 2

-1

Sample Input 3

15 9
dnsusrayukuaiia
dujrunuma

Sample Output 3

45


N, M = gets.chomp.split.map(&:to_i)
S = gets.chomp.chars
T = gets.chomp.chars

def gcd(a, b)
  if (a < b)
    # swap(a, b)
    tmp = a
    a = b
    b = tmp
  end

  if (b == 0)
    return a
  end

  gcd(b, a % b)
end

L = N * M / gcd(N, M)

X = Array.new(L, -1)
LN = L/N
LM = L/M
0.upto(N-1).each do |i|
  X[i * LN] = S[i]
end

def solve
  ans = true
  0.upto(M-1).each do |i|
    if (X[i * LM] == -1) || (X[i * LM] == T[i])
      # OK
    else
      ans = false
      break
    end
  end

  if ans
    p L
  else
    p -1
  end
end

solve


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


#!/usr/bin/env ruby

require 'set'

class Hash
  def push(key, value)
    self[key] = [] if self[key] == nil
    self[key].push(value)
  end
end

class Array
  def lower_bound(value)
    left = -1;
    right = self.length;
    while left + 1 < right
      mid = left + (right - left) / 2;
      if self[mid] >= value
        right = mid
      else
        left = mid
      end
    end
    right
  end

  def unique
    res = [self.first]
    each_cons(2) do |a, b|
      if a != b
        res.push(b)
      end
    end
    res
  end
end

def get_ints
  gets.chomp.split.map(&:to_i)
end

def get_ints_minus_one
  get_ints.map { |x| x - 1 }
end

def get_int
  gets.chomp.to_i
end

X = get_int

if X == 1
  puts 'Hello World'
else
  A = get_int
  B = get_int

  puts A + B
end

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


def distance p1, p2
  (p1[:x] - p2[:x]).abs + (p1[:y] - p2[:y]).abs
end
def calc_height p_target, p_known
  distance(p_target, p_known) + p_known[:h]
end

def diff p1, p2
  {:x => p2[:x] - p1[:x], :y => p2[:y] - p1[:y]}
end
def dot_product v1, v2
  v1[:x]*v2[:x] + v1[:y]*v2[:y]
end

N_range = 0..100
center_candidates = N_range.map{|x| N_range.map{|y| {:x => x, :y => y}}}.flatten(1)

N = STDIN.gets.chomp.to_i
xyh = N.times.map do
  data = STDIN.gets.chomp.split(" ").map(&:to_i)
  {:x => data[0], :y => data[1], :h => data[2]}
end

xyh.each_with_index do |base_item, i|
  center_candidates.reject!{|item| item[:x] == base_item[:x] and item[:y] == base_item[:y]} if base_item[:h] == 0

  ((i + 1)..(xyh.size - 1)).each do |j|
    compare_item = xyh[j]
    center_candidates.reject!{|item| item[:x] == compare_item[:x] and item[:y] == compare_item[:y]} if compare_item[:h] == 0

    if base_item[:h] == 0 and compare_item[:h] == 0
      # do nothing...
    elsif compare_item[:h] == 0 or base_item[:h] == 0
      non_zero_item, zero_item = if compare_item[:h] == 0
        [base_item, compare_item]
      else
        [compare_item, base_item]
      end

      dist = distance(base_item, compare_item)
      v1 = diff(non_zero_item, zero_item)
      center_candidates.select!{|item| dot_product(v1, diff(non_zero_item, item)) <= 0 or 2 * distance(non_zero_item, item) < dist - non_zero_item[:h]}
    else
      diff_h = compare_item[:h] - base_item[:h]
      center_candidates.select!{|item| distance(item, base_item) - distance(item, compare_item) == diff_h}
    end
  end
end

center = center_candidates.first
center_height = calc_height(center, xyh.first)
puts "#{center[:x]} #{center[:y]} #{center_height}"


N,T=gets.split.map &:to_i
min=1001
N.times.map{c,t=gets.split.map &:to_i;if t<=T && min>c then min=c end}
puts min==1001?"TLE":min

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


N,T = gets.split.map(&:to_i)
array = []

N.times do
  c,t = gets.split.map(&:to_i)
  array.push(c) if t <= T
end

puts array.size == 0 ? 'TLE' : array.min


n = gets.split(//).map(&:to_i)

num = 0
ans = []
n.each do |i|
    if i == 9
        ans[num] = 1
    else
        ans[num] = 9
    end
    num = num + 1
end

puts ans.join.to_s

Score : 100 points

Problem Statement

Cat Snuke is learning to write characters.
Today, he practiced writing digits 1 and 9, but he did it the other way around.

You are given a three-digit integer n written by Snuke.
Print the integer obtained by replacing each digit 1 with 9 and each digit 9 with 1 in n.

Constraints

111 \leq n \leq 999

n is an integer consisting of digits 1 and 9.

Input

Input is given from Standard Input in the following format:

n

Output

Print the integer obtained by replacing each occurrence of 1 with 9 and each occurrence of 9 with 1 in n.

Sample Input 1

119

Sample Output 1

991

Replace the 9 in the ones place with 1, the 1 in the tens place with 9 and the 1 in the hundreds place with 9. The answer is 991.

Sample Input 2

999

Sample Output 2

111


n = gets.split("").map(&:to_i)

puts n.map{|m|
  if m == 1 then
    9
  elsif m == 9 then
    1
  else
    m
  end
}.join[0..2]


a = gets.strip.split('')
a = a.map do |aa|
  if aa == '1'
    '9'
  elsif aa == '9'
    '1'
  else
    aa
  end
end
puts a.join


# https://atcoder.jp/contests/abc111/tasks/arc103_a

n = gets.to_i
vs = gets.split.map(&:to_i)

as, bs = vs.each_slice(2).to_a.transpose.map do |ws|
  ws
  .group_by(&:itself)
  .map { |k, vs| [vs.size, k] }
  .group_by { |c, k| c }
  .sort
  .reverse
  .take(2)
  .map { |c, vs| [c, vs.transpose[1].sort] }
  .push([0, []])
end

keep = (
  if as[0][1].size > 1 || bs[0][1].size > 1 || as[0][1] != bs[0][1]
    as[0][0] + bs[0][0]
  else
    [as[0][0] + bs[1][0], as[1][0] + bs[0][0]].max
  end
)

puts n - keep

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 /\/\/\/.


#!/usr/bin/env ruby

require 'set'

class Hash
  def push(key, value)
    self[key] = [] if self[key] == nil
    self[key].push(value)
  end
end

class Array
  def lower_bound(value)
    left = -1;
    right = self.length;
    while left + 1 < right
      mid = left + (right - left) / 2;
      if self[mid] >= value
        right = mid
      else
        left = mid
      end
    end
    right
  end

  def unique
    res = [self.first]
    each_cons(2) do |a, b|
      if a != b
        res.push(b)
      end
    end
    res
  end
end

def get_ints
  gets.chomp.split.map(&:to_i)
end

def get_ints_minus_one
  get_ints.map { |x| x - 1 }
end

def get_int
  gets.chomp.to_i
end

test = 'LRLDDUURLULURRRUDULRDULLULLLLRRR'
d = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824]

test.split('')

N = get_int
XY = []
N.times do |i|
  XY[i] = get_ints
end

# check mods
mod = nil
incorrect = false
XY.each do |x, y|
  test = (x + y) % 2
  mod = test if mod.nil?
  if mod != test
    incorrect = true
    break
  end
end

if incorrect
  puts '-1'
else
  m = mod == 0 ? 32 : 31
  d = 31.times.map { |x| 2 ** x }
  d.push(1) if m == 32
  puts m
  puts d.join(' ')

  XY.each do |x, y|
    u = x + y
    v = x - y
    ux = ((u + (2 ** 31 - 1))/2).to_s(2).rjust(31, '0').split('')
    vx = ((v + (2 ** 31 - 1))/2).to_s(2).rjust(31, '0').split('')
    stock = ux.zip(vx).map do |ud, vd|
      uv = ud + vd
      case uv
      when '00'
        'L'
      when '01'
        'D'
      when '10'
        'U'
      when '11'
        'R'
      end
    end
    if u % 2 == 0
      stock.push('R')
    end
    puts stock.join
  end
end

Score : 600 points

Problem Statement

Snuke is introducing a robot arm with the following properties to his factory:

The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i.

For each section, its mode can be specified individually. There are four modes: L, R, D and U. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)):

(x_0, y_0) = (0, 0).

If the mode of Section i is L, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}).

If the mode of Section i is R, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}).

If the mode of Section i is D, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}).

If the mode of Section i is U, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}).

Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections.
Is this possible?
If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j).

Constraints

All values in input are integers.

1 \leq N \leq 1000

-10^9 \leq X_i \leq 10^9

-10^9 \leq Y_i \leq 10^9

Partial Score

In the test cases worth 300 points, -10 \leq X_i \leq 10 and -10 \leq Y_i \leq 10 hold.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1
X_2 Y_2
:
X_N Y_N

Output

If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print -1.

m
d_1 d_2 ... d_m
w_1
w_2
:
w_N

m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means.
Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers.

w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j).
The i-th character of w_j should be one of the letters L, R, D and U, representing the mode of Section i.

Sample Input 1

3
-1 0
0 3
2 -1

Sample Output 1

2
1 2
RL
UU
DR

In the given way to bring Joint m of the robot arm to each (X_j, Y_j), the positions of the joints will be as follows:

To (X_1, Y_1) = (-1, 0): First, the position of Joint 0 is (x_0, y_0) = (0, 0). As the mode of Section 1 is R, the position of Joint 1 is (x_1, y_1) = (1, 0). Then, as the mode of Section 2 is L, the position of Joint 2 is (x_2, y_2) = (-1, 0).

To (X_2, Y_2) = (0, 3): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, 1), (x_2, y_2) = (0, 3).

To (X_3, Y_3) = (2, -1): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, -1), (x_2, y_2) = (2, -1).

Sample Input 2

5
0 0
1 0
2 0
3 0
4 0

Sample Output 2

-1

Sample Input 3

2
1 1
1 1

Sample Output 3

2
1 1
RU
UR

There may be duplicated points among (X_j, Y_j).

Sample Input 4

3
-7 -3
7 3
-3 -7

Sample Output 4

5
3 1 4 1 5
LRDUL
RDULR
DULRD


n = gets.to_i
v = gets.split.map(&:to_i)
odd = Array.new(10**5)
even = Array.new(10**5)
(10**5).times do |i|
  odd[i] = [0,i]
  even[i] = [0,i]
end
n.times do |i|
  if i % 2 == 0
    even[v[i]][0] += 1
  elsif
    odd[v[i]][0] += 1
  end
end

odd.sort_by!{|a| a[0]}
even.sort_by! {|a| a[0]}
if odd[-1][1] == even[-1][1]
  t = [odd[-2][0], even[-2][0]].max
  p n - odd[-1][0] - t
else
  p n - odd[-1][0] - even[-1][0]
end


n=gets.to_i
v=gets.split.map &:to_i

odd=Hash.new 0
even=Hash.new 0

n.times{|i|
  [even, odd][i%2][v[i]]+=1
}

odd[-1]=0
even[-1]=0

odd=odd.sort_by{|k,v|v}.reverse
even=even.sort_by{|k,v|v}.reverse

if odd[0][0]!=even[0][0]
  p n-odd[0][1]-even[0][1]
else
  p [
    n-odd[0][1]-even[1][1],
    n-odd[1][1]-even[0][1]
  ].min
end


s = gets.chomp!.split('')
t = gets.chomp!.split('')
s_dup = {}
t_dup = {}
s.each do |_s|
  s_dup[_s] = 0 unless s_dup.keys.include? _s
  s_dup[_s] += 1
end
t.each do |_t|
  t_dup[_t] = 0 unless t_dup.keys.include? _t
  t_dup[_t] += 1
end
s_dup = s_dup.to_a.sort{|a, b| a[1] <=> b[1]}.select{|val| val[1] >= 2 }
t_dup = t_dup.to_a.sort{|a, b| a[1] <=> b[1]}.select{|val| val[1] >= 2 }
def check(s_, t_)
  if s_.length == t_.length
    s_ = s_.map{ |val| val[1] }
    t_ = t_.map{ |val| val[1] }
    if s_ == t_
      return true
    else
      return false
    end
  end
  return false
end
if s.uniq.length == t.uniq.length
  if check(s_dup, t_dup)
    puts "Yes"
  else
    puts "No"
  end
else
  puts "No"
end

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


def comb(n, k)
  res = 1
  i = n
  while i >= n-k+1
    res *= i
    i -= 1
  end
  while k > 0
    res /= k
    k -= 1
  end
  res
end
MOD = 10**9+7
n, m = gets.split.map(&:to_i)
i = 2
f = Hash.new(0)
while i * i <= m
  while m % i == 0
    m /= i
    f[i] += 1
  end
  i += 1
end
f[m] = 1 if m != 1
ans = 1
f.each do |k,v|
  ans *= comb(n+v-1, v)
  ans %= MOD
end
p ans

Score : 400 points

Problem Statement

You are given positive integers N and M.

How many sequences a of length N consisting of positive integers satisfy a_1 \times a_2 \times ... \times a_N = M? Find the count modulo 10^9+7.

Here, two sequences a' and a'' are considered different when there exists some i such that a_i' \neq a_i''.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of the sequences consisting of positive integers that satisfy the condition, modulo 10^9 + 7.

Sample Input 1

2 6

Sample Output 1

4

Four sequences satisfy the condition: \{a_1, a_2\} = \{1, 6\}, \{2, 3\}, \{3, 2\} and \{6, 1\}.

Sample Input 2

3 12

Sample Output 2

18

Sample Input 3

100000 1000000000

Sample Output 3

957870001


N,x,*as=$<.read.split.map(&:to_i)
ret = 0
as.sort.each do |a|
    if a <= x
        ret += 1
        x -= a
    else
        break
    end
end

ret = [ret-1,0].max if x > 0
puts ret

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,*as=$<.read.split.map(&:to_i)
ret = 0
as.sort.each do |a|
    if a <= x
        ret += 1
        x -= a
    else
        break
    end
end

ret = [ret-1,0].max if x != 0
puts ret


input = STDIN.read.split("\n").map{|l| l.split(" ").map{|i| i.to_i}}
drops = input[0][1]
requires = input[1]
sorted_requires = requires.sort

funs = 0
sorted_requires.each do |r|
  if drops < r
    drops = 0
    break
  end

  drops = drops - r
  funs = funs + 1
end

if drops != 0
  funs = funs - 1
end

puts funs


number,energy = gets.chomp.split(" ").map(&:to_i)
garbage = gets.chomp.split(" ").map(&:to_i)
total_e = 10**15
point = 0
count = 1
check = 1
list = [0]
for i in 1..number
  list[i] = list[i - 1] + garbage[i - 1]
end

for i in 1..number
  while (count + i) <= number
    if check == 1
      point += (list[-count] - list[-count - i])*5
      check += 1
      count += i
    else
      point += (list[-count] - list[-count - i])*(check*2 + 1)
      check += 1
      count += i
    end
  end
  if check == 1
    point += list[-count]*5
  else
    point += list[-count]*(check*2 + 1)
  end
  point += i * energy
  if point < total_e
    total_e = point
  end
  point = 0
  check = 1
  count = 1
end

total_e += number * energy
print total_e

Score : 700 points

Problem Statement

Snuke has decided to use a robot to clean his room.

There are N pieces of trash on a number line.
The i-th piece from the left is at position x_i.
We would like to put all of them in a trash bin at position 0.

For the positions of the pieces of trash, 0 < x_1 < x_2 < ... < x_{N} \leq 10^{9} holds.

The robot is initially at position 0.
It can freely move left and right along the number line, pick up a piece of trash when it comes to the position of that piece, carry any number of pieces of trash and put them in the trash bin when it comes to position 0. It is not allowed to put pieces of trash anywhere except in the trash bin.

The robot consumes X points of energy when the robot picks up a piece of trash, or put pieces of trash in the trash bin. (Putting any number of pieces of trash in the trash bin consumes X points of energy.)
Also, the robot consumes (k+1)^{2} points of energy to travel by a distance of 1 when the robot is carrying k pieces of trash.

Find the minimum amount of energy required to put all the N pieces of trash in the trash bin.

Constraints

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

0 < x_1 < ... < x_N \leq 10^9

1 \leq X \leq 10^9

All values in input are integers.

Partial Scores

400 points will be awarded for passing the test set satisfying N \leq 2000.

Input

Input is given from Standard Input in the following format:

N X
x_1 x_2 ... x_{N}

Output

Print the answer.

Sample Input 1

2 100
1 10

Sample Output 1

355

Travel to position 10 by consuming 10 points of energy.

Pick up the piece of trash by consuming 100 points of energy.

Travel to position 1 by consuming 36 points of energy.

Pick up the piece of trash by consuming 100 points of energy.

Travel to position 0 by consuming 9 points of energy.

Put the two pieces of trash in the trash bin by consuming 100 points of energy.

This strategy consumes a total of 10+100+36+100+9+100=355 points of energy.

Sample Input 2

5 1
1 999999997 999999998 999999999 1000000000

Sample Output 2

19999999983

Sample Input 3

10 8851025
38 87 668 3175 22601 65499 90236 790604 4290609 4894746

Sample Output 3

150710136

Sample Input 4

16 10
1 7 12 27 52 75 731 13856 395504 534840 1276551 2356789 9384806 19108104 82684732 535447408

Sample Output 4

3256017715


n = gets.to_i
odd = 0
even = 0
for i in 1..n
  if i.odd?
    odd += 1
  else
    even += 1
  end
end
puts odd * even

Score : 100 points

Problem Statement

Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter.

Constraints

2\leq K\leq 100

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive).

Sample Input 1

3

Sample Output 1

2

Two pairs can be chosen: (2,1) and (2,3).

Sample Input 2

6

Sample Output 2

9

Sample Input 3

11

Sample Output 3

30

Sample Input 4

50

Sample Output 4

625


x_1, y_1, x_2, y_2 = gets.split(" ").map(&:to_i)

x_mount = x_2 - x_1
y_mount = y_2 - y_1

if x_mount > 0 && y_mount > 0
  x_3, y_3 = x_2 - y_mount.abs, y_2 + x_mount.abs
  x_4, y_4 = x_1 - y_mount.abs, y_1 + x_mount.abs

elsif x_mount < 0 && y_mount < 0
  x_3, y_3 = x_2 + y_mount.abs, y_2 - x_mount.abs
  x_4, y_4 = x_1 + y_mount.abs, y_1 - x_mount.abs

elsif x_mount < 0 && y_mount > 0
  x_3, y_3 = x_2 - y_mount.abs, y_2 - x_mount.abs
  x_4, y_4 = x_1 - y_mount.abs, y_1 - x_mount.abs

elsif  x_mount > 0 && y_mount < 0
  x_3, y_3 = x_2 + y_mount.abs, y_2 + x_mount.abs
  x_4, y_4 = x_1 + y_mount.abs, y_1 + x_mount.abs

elsif y_mount == 0 && x_1 < x_2
  x_3, y_3 = x_2, y_2 + x_mount.abs
  x_4, y_4 = x_1, y_1 + x_mount.abs

elsif y_mount == 0 && x_1 > x_2
  x_3, y_3 = x_2, y_2 - x_mount.abs
  x_4, y_4 = x_1, y_1 - x_mount.abs

elsif x_mount == 0 && y_1 < y_2
  x_3, y_3 = x_2 - y_mount.abs, y_2
  x_4, y_4 = x_1 - y_mount.abs, y_1

elsif x_mount == 0 && y_1 > y_2
  x_3, y_3 = x_2 + y_mount.abs, y_2
  x_4, y_4 = x_1 + y_mount.abs, y_1
end

puts "#{x_3} #{y_3} #{x_4} #{y_4}"

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


x_1, y_1, x_2, y_2 = gets.split(" ").map(&:to_i)

x_mount = x_2 - x_1
y_mount = y_2 - y_1

if (x_mount > 0 && y_mount > 0) || (x_mount < 0 && y_mount < 0)
  x_3, y_3 = x_2 - y_mount.abs, y_2 + x_mount.abs
  x_4, y_4 = x_1 - y_mount.abs, y_1 + x_mount.abs
elsif (x_mount < 0 && y_mount > 0) || (x_mount > 0 && y_mount < 0)
  x_3, y_3 = x_2 - y_mount.abs, y_2 - x_mount.abs
  x_4, y_4 = x_1 - y_mount, y_1 + x_mount
elsif x_mount == 0
  x_3, y_3 = x_2 - y_mount.abs, y_2
  x_4, y_4 = x_1 - y_mount.abs, y_1
elsif y_mount == 0
  x_3, y_3 = x_2, y_2 + x_mount.abs
  x_4, y_4 = x_1, y_1 + x_mount.abs
end

puts "#{x_3} #{y_3} #{x_4} #{y_4}"


N, K = gets.split.map(&:to_i)
ans = 0
zero_remain = 0
half_count = 0

if K % 2 == 0
    N.times{|x|
        zero_remain += 1 if (x + 1) % K == 0
        half_count += 1 if (x + 1) % K == K/2
    }
else
    N.times{|x|
        half_count += 1 if (x + 1) % K == 0
    }
end
ans = zero_remain ** 3 + half_count ** 3
puts ans

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


n, k = gets.split.map(&:to_i)
# n = 3
# k = 2
#
# def binom(m, n)
#   res = 1
#   (1..n).each do |i|
#     res = res * (m - i + 1) / i
#   end
#   return res
# end
#
# def multi_choose(m, n)
#   binom(m + n - 1, n)
# end

if (k % 2 == 0)
  # kの倍数の個数
  multiple_k = n / k
  a = multiple_k**3
  # mod kで k/2 になる数の個数
  middle_mod = (n + k/2) / k
  b = middle_mod**3

  puts a + b
else
  # kの倍数の個数
  multiple_k = n / k
  puts multiple_k**3
end


N,K=$<.read.split.map(&:to_i)

if K.odd?
    puts (N/K)**3
elsif K == 1
    puts N**3
else
    puts ((N+K/2)/K)**3 + (N/K)**3
end


h,w = gets.chomp.split.map(&:to_i)
as = h.times.map{gets.chomp.chars}
as.each do |a|
    if a.all?{|i| i == "." }
        as.delete(a)
    end
end
as = as.transpose
as.each do |a|
    if a.all?{|i| i == "." }
        as.delete(a)
    end
end
as.transpose.each do |a|
    puts a.join
end

Score : 200 points

Problem Statement

There is a grid of squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column from the left is represented as (i, j).
Each square is black or white.
The color of the square is given as an H-by-W matrix (a_{i, j}).
If a_{i, j} is ., the square (i, j) is white; if a_{i, j} is #, the square (i, j) is black.

Snuke is compressing this grid.
He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares:

Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns.

It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation.
Find the final state of the grid.

Constraints

1 \leq H, W \leq 100

a_{i, j} is . or #.

There is at least one black square in the whole grid.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}...a_{1, W}
:
a_{H, 1}...a_{H, W}

Output

Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity.

Sample Input 1

4 4
##.#
....
##.#
.#.#

Sample Output 1

###
###
.##

The second row and the third column in the original grid will be removed.

Sample Input 2

3 3
#..
.#.
..#

Sample Output 2

#..
.#.
..#

As there is no row or column that consists only of white squares, no operation will be performed.

Sample Input 3

4 5
.....
.....
..#..
.....

Sample Output 3

#

Sample Input 4

7 6
......
....#.
.#....
..#...
..#...
......
.#..#.

Sample Output 4

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


n,k=gets.split.map(&:to_i)
x=gets.split.map(&:to_i)
kouho=Array.new
for i in 0..n-k
    y=x[i...i+k]
    if y[0]>=0
        kouho.push(y[k-1])
    elsif y[k-1]<=0
        kouho.push(y[0].abs)
    elsif y[0].abs<y[k-1]
        kouho.push(y[k-1]-2*y[0])
    else
        kouho.push(2*y[k-1]-y[0])
    end
end
p kouho.min

Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

8 5
-9 -7 -4 -3 1 2 3 4

Sample Output 4

10


a, b = STDIN.read.split.map(&:to_i)

puts (a * b + 1) - (a + b)

Score: 100 points

Problem Statement

There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.)

What is the area of this yard excluding the roads? Find it.

Note

It can be proved that the positions of the roads do not affect the area.

Constraints

A is an integer between 2 and 100 (inclusive).

B is an integer between 2 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

A B

Output

Print the area of this yard excluding the roads (in square yards).

Sample Input 1

2 2

Sample Output 1

1

In this case, the area is 1 square yard.

Sample Input 2

5 7

Sample Output 2

24

In this case, the area is 24 square yards.


nums = gets.chomp.split("").map(&:to_i)
ans_num = 0
i = 0
target = true
while target do
  ans_num = nums[i]
  if ans_num != 1
    target = false
  end
  i += 1
end

p ans_num


s=gets.chomp.split("").map(&:to_i)
k=gets.to_i
ans=1
k.times do |i|
  if s[i]!=1
    ans=s[i]
    break
  end
end
puts ans

Score: 300 points

Problem Statement

Mr. Infinity has a string S consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:

Each occurrence of 2 in S is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.

For example, if S is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?

Constraints

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

K is an integer between 1 and 10^{18} (inclusive).

The length of the string after 5 \times 10^{15} days is at least K.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

The first five characters in the string after 5 \times 10^{15} days is 12222. As K=4, we should print the fourth character, 2.

Sample Input 2

3
157

Sample Output 2

3

The initial string is 3. The string after 5 \times 10^{15} days consists only of 3.

Sample Input 3

299792458
9460730472580800

Sample Output 3

2


S=gets.chomp.chars.map(&:to_i)
K=gets.to_i

one_count=0
other_num=1

S.each_index {|a|
    if S[a]==1
        one_count+=1
    else
        other_num=S[a]
        break
    end
}

if K<=one_count
    puts 1
else
    p other_num
end


N,K = gets.split.map &:to_i

puts N % K == 0 ? 0 : 1

Score : 100 points

Problem Statement

Takahashi has decided to distribute N AtCoder Crackers to K users of as evenly as possible.
When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Constraints

1 \leq N,K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Sample Input 1

7 3

Sample Output 1

1

When the users receive two, two and three crackers, respectively, the (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user, is 1.

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0


#!/usr/bin/env ruby

require 'set'

class Hash
  def push(key, value)
    self[key] = [] if self[key] == nil
    self[key].push(value)
  end
end

class Array
  def lower_bound(value)
    left = -1;
    right = self.length;
    while left + 1 < right
      mid = left + (right - left) / 2;
      if self[mid] >= value
        right = mid
      else
        left = mid
      end
    end
    right
  end

  def unique
    res = [self.first]
    each_cons(2) do |a, b|
      if a != b
        res.push(b)
      end
    end
    res
  end
end

def get_ints
  gets.chomp.split.map(&:to_i)
end

def get_ints_minus_one
  get_ints.map { |x| x - 1 }
end

def get_int
  gets.chomp.to_i
end

N = get_int

test = []
0.step(25) do |four|
  0.step(15) do |seven|
    test << 4 * four + 7 * seven
  end
end

if test.include?(N)
  puts 'Yes'
else
  puts 'No'
end

Score : 200 points

Problem Statement

La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each.
Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.

Constraints

N is an integer between 1 and 100, inclusive.

Input

Input is given from Standard Input in the following format:

N

Output

If there is a way to buy some cakes and some doughnuts for exactly N dollars, print Yes; otherwise, print No.

Sample Input 1

11

Sample Output 1

Yes

If you buy one cake and one doughnut, the total will be 4 + 7 = 11 dollars.

Sample Input 2

40

Sample Output 2

Yes

If you buy ten cakes, the total will be 4 \times 10 = 40 dollars.

Sample Input 3

3

Sample Output 3

No

The prices of cakes (4 dollars) and doughnuts (7 dollars) are both higher than 3 dollars, so there is no such way.


n = gets.to_i
max = n / 7
answer = "No"

(1..max).each do |number|
  if (n - number * 7) % 4 == 0 && n - number * 7 != 0
    answer = "Yes"
    break
  end
end

puts answer


s=gets.strip.to_i
if s<1200
  puts "ABC"
elsif s<2800
  puts "ARC"
else
  puts "AGC"
end

Score : 100 points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200.

The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800.

The contest after the ARC is called AGC, which is rated for all contestants.

Takahashi's rating on AtCode is R. What is the next contest rated for him?

Constraints

0 ≤ R ≤ 4208

R is an integer.

Input

Input is given from Standard Input in the following format:

R

Output

Print the name of the next contest rated for Takahashi (ABC, ARC or AGC).

Sample Input 1

1199

Sample Output 1

ABC

1199 is less than 1200, so ABC will be rated.

Sample Input 2

1200

Sample Output 2

ARC

1200 is not less than 1200 and ABC will be unrated, but it is less than 2800 and ARC will be rated.

Sample Input 3

4208

Sample Output 3

AGC