n = gets.to_i

if n == 3
    puts "2 5 63"
elsif n == 4
    puts "2 5 20 62"
else
    ans = [2, 4, 6]
    i = 6
    n -= 3

    while i + 12 < 30000
        if n > 8
            6.times {ans << i += 2}
            n -= 6
        else
            if n.odd?
                n -= 1
                ans << i + 6
            end
            break
        end
    end

    i = -3
    n.times {ans << i += 6}
    puts ans * " "
end

Score : 600 points

Problem Statement

Nagase is a top student in high school. One day, she's analyzing some properties of special sets of positive integers.

She thinks that a set S = \{a_{1}, a_{2}, ..., a_{N}\} of distinct positive integers is called special if for all 1 \leq i \leq N, the gcd (greatest common divisor) of a_{i} and the sum of the remaining elements of S is not 1.

Nagase wants to find a special set of size N. However, this task is too easy, so she decided to ramp up the difficulty. Nagase challenges you to find a special set of size N such that the gcd of all elements are 1 and the elements of the set does not exceed 30000.

Constraints

3 \leq N \leq 20000

Input

Input is given from Standard Input in the following format:

N

Output

Output N space-separated integers, denoting the elements of the set S. S must satisfy the following conditions :

The elements must be distinct positive integers not exceeding 30000.

The gcd of all elements of S is 1, i.e. there does not exist an integer d > 1 that divides all elements of S.

S is a special set.

If there are multiple solutions, you may output any of them. The elements of S may be printed in any order. It is guaranteed that at least one solution exist under the given contraints.

Sample Input 1

3

Sample Output 1

2 5 63

\{2, 5, 63\} is special because gcd(2, 5 + 63) = 2, gcd(5, 2 + 63) = 5, gcd(63, 2 + 5) = 7. Also, gcd(2, 5, 63) = 1. Thus, this set satisfies all the criteria.

Note that \{2, 4, 6\} is not a valid solution because gcd(2, 4, 6) = 2 > 1.

Sample Input 2

4

Sample Output 2

2 5 20 63

\{2, 5, 20, 63\} is special because gcd(2, 5 + 20 + 63) = 2, gcd(5, 2 + 20 + 63) = 5, gcd(20, 2 + 5 + 63) = 10, gcd(63, 2 + 5 + 20) = 9. Also, gcd(2, 5, 20, 63) = 1. Thus, this set satisfies all the criteria.


A = gets.to_i
B = gets.to_i

C = gets.to_i
D = gets.to_i

train_min_price = A < B ? A : B
bus_min_price = C < D ? C : D

puts train_min_price + bus_min_price

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

Score : 100 points

Problem Statement

You planned a trip using trains and buses.
The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket.
Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.

Find the minimum total fare when the optimal choices are made for trains and buses.

Constraints

1 \leq A \leq 1 000

1 \leq B \leq 1 000

1 \leq C \leq 1 000

1 \leq D \leq 1 000

All input values are integers.

Input

Input is given from Standard Input in the following format:

A
B
C
D

Output

Print the minimum total fare.

Sample Input 1

600
300
220
420

Sample Output 1

520

The train fare will be 600 yen if you buy ordinary tickets, and 300 yen if you buy an unlimited ticket.
Thus, the optimal choice for trains is to buy an unlimited ticket for 300 yen.
On the other hand, the optimal choice for buses is to buy ordinary tickets for 220 yen.

Therefore, the minimum total fare is 300 + 220 = 520 yen.

Sample Input 2

555
555
400
200

Sample Output 2

755

Sample Input 3

549
817
715
603

Sample Output 3

1152

Submitted source-code file size, in bytes.

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

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


n = gets.to_i
d,x = gets.split.map(&:to_i)
ans = x+n
d -= 1
n.times do
    a = gets.to_i
    ans += d/a
end
puts ans

Score : 200 points

Problem Statement

Some number of chocolate pieces were prepared for a training camp.
The camp had N participants and lasted for D days.
The i-th participant (1 \leq i \leq N) ate one chocolate piece on each of the following days in the camp: the 1-st day, the (A_i + 1)-th day, the (2A_i + 1)-th day, and so on.
As a result, there were X chocolate pieces remaining at the end of the camp. During the camp, nobody except the participants ate chocolate pieces.

Find the number of chocolate pieces prepared at the beginning of the camp.

Constraints

1 \leq N \leq 100

1 \leq D \leq 100

1 \leq X \leq 100

1 \leq A_i \leq 100 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
D X
A_1
A_2
:
A_N

Output

Find the number of chocolate pieces prepared at the beginning of the camp.

Sample Input 1

3
7 1
2
5
10

Sample Output 1

8

The camp has 3 participants and lasts for 7 days.
Each participant eats chocolate pieces as follows:

The first participant eats one chocolate piece on Day 1, 3, 5 and 7, for a total of four.

The second participant eats one chocolate piece on Day 1 and 6, for a total of two.

The third participant eats one chocolate piece only on Day 1, for a total of one.

Since the number of pieces remaining at the end of the camp is one, the number of pieces prepared at the beginning of the camp is 1 + 4 + 2 + 1 = 8.

Sample Input 2

2
8 20
1
10

Sample Output 2

29

Sample Input 3

5
30 44
26
18
81
18
6

Sample Output 3

56


N = gets.to_i
as = gets.split.map(&:to_i)
max = (as[0]).abs
(N-1).times{|i|
  max += (as[i+1]-as[i]).abs
}
max += as[N-1].abs
as.push(0)
as.unshift(0)
1.upto(N){|i|
  if as[i] < 0
    if as[i+1] <= as[i]
      puts max
    else
      puts (max- 2*[(as[i]-as[i-1]).abs, (as[i+1]-as[i]).abs].min)
    end
  else
    if as[i+1] >= as[i]
      puts max
    else
      puts (max- 2*[(as[i]-as[i-1]).abs, (as[i+1]-as[i]).abs].min)
    end
  end
}

Score : 300 points

Problem Statement

There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N.
Spot i is at the point with coordinate A_i.
It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.

You planned a trip along the axis.
In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.

However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i.
You will visit the remaining spots as planned in the order they are numbered.
You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.

For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.

Constraints

2 \leq N \leq 10^5

-5000 \leq A_i \leq 5000 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N lines.
In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.

Sample Input 1

3
3 5 -1

Sample Output 1

12
8
10

Spot 1, 2 and 3 are at the points with coordinates 3, 5 and -1, respectively.
For each i, the course of the trip and the total cost of travel when the visit to Spot i is canceled, are as follows:

For i = 1, the course of the trip is 0 \rightarrow 5 \rightarrow -1 \rightarrow 0 and the total cost of travel is 5 + 6 + 1 = 12 yen.

For i = 2, the course of the trip is 0 \rightarrow 3 \rightarrow -1 \rightarrow 0 and the total cost of travel is 3 + 4 + 1 = 8 yen.

For i = 3, the course of the trip is 0 \rightarrow 3 \rightarrow 5 \rightarrow 0 and the total cost of travel is 3 + 2 + 5 = 10 yen.

Sample Input 2

5
1 1 1 2 0

Sample Output 2

4
4
4
2
4

Sample Input 3

6
-679 -2409 -3258 3095 -3291 -4462

Sample Output 3

21630
21630
19932
8924
21630
19288


N = gets.to_i
A = gets.split(" ").map { |item| item.to_i }
A.freeze

res = []

for i in 0..N-1 do
  if i==0
    ryohi = A[1].abs
  else
    ryohi = A[0].abs
  end
  for j in 0..N-2 do
    if j+1 == i
      if j+2 < N
        ryohi += (A[j+2] - A[j]).abs
      end
    elsif j != i
      ryohi += (A[j+1] - A[j]).abs
    end
  end
  if i == N-1
    ryohi += A[N-2].abs
  else
    ryohi += A[N-1].abs
  end
  res[i] = ryohi
  print "#{res[i] } "
end

print "\n"


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

if a+b > c
	puts "Yes"
else
	puts "NO"
end

Score : 100 points

Problem Statement

An elementary school student Takahashi has come to a variety store.

He has two coins, A-yen and B-yen coins (yen is the currency of Japan), and wants to buy a toy that costs C yen. Can he buy it?

Note that he lives in Takahashi Kingdom, and may have coins that do not exist in Japan.

Constraints

All input values are integers.

1 \leq A, B \leq 500

1 \leq C \leq 1000

Input

Input is given from Standard Input in the following format:

A B C

Output

If Takahashi can buy the toy, print Yes; if he cannot, print No.

Sample Input 1

50 100 120

Sample Output 1

Yes

He has 50 + 100 = 150 yen, so he can buy the 120-yen toy.

Sample Input 2

500 100 1000

Sample Output 2

No

He has 500 + 100 = 600 yen, but he cannot buy the 1000-yen toy.

Sample Input 3

19 123 143

Sample Output 3

No

There are 19-yen and 123-yen coins in Takahashi Kingdom, which are rather hard to use.

Sample Input 4

19 123 142

Sample Output 4

Yes


a, b, o = STDIN.read.split(' ').map{|e|Integer(e)}
a + b >= o ? 'Yes' : 'No'


s=[]
t=[]
n=gets.to_i
n.times{s<<gets.chomp}
m=gets.to_i
m.times{t<<gets.chomp}
h=Hash.new(0)
s.each{|x|h[x]+=1}
t.each{|x|h[x]-=1}
puts h.values.push(0).max

Score : 200 points

Problem Statement

Takahashi has N blue cards and M red cards.
A string is written on each card. The string written on the i-th blue card is s_i, and the string written on the i-th red card is t_i.

Takahashi will now announce a string, and then check every card. Each time he finds a blue card with the string announced by him, he will earn 1 yen (the currency of Japan); each time he finds a red card with that string, he will lose 1 yen.

Here, we only consider the case where the string announced by Takahashi and the string on the card are exactly the same. For example, if he announces atcoder, he will not earn money even if there are blue cards with atcoderr, atcode, btcoder, and so on. (On the other hand, he will not lose money even if there are red cards with such strings, either.)

At most how much can he earn on balance?

Note that the same string may be written on multiple cards.

Constraints

N and M are integers.

1 \leq N, M \leq 100

s_1, s_2, ..., s_N, t_1, t_2, ..., t_M are all strings of lengths between 1 and 10 (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N
M
t_1
t_2
:
t_M

Output

If Takahashi can earn at most X yen on balance, print X.

Sample Input 1

3
apple
orange
apple
1
grape

Sample Output 1

2

He can earn 2 yen by announcing apple.

Sample Input 2

3
apple
orange
apple
5
apple
apple
apple
apple
apple

Sample Output 2

1

If he announces apple, he will lose 3 yen. If he announces orange, he can earn 1 yen.

Sample Input 3

1
voldemort
10
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort

Sample Output 3

0

If he announces voldemort, he will lose 9 yen. If he announces orange, for example, he can avoid losing a yen.

Sample Input 4

6
red
red
blue
yellow
yellow
red
5
red
red
yellow
green
blue

Sample Output 4

1


n=gets.to_i
r=(1..n).map{gets.split.map &:to_i}.sort{|s,t|t[1]<=>s[1]} #y zahyo dekai jun
b=(1..n).map{gets.split.map &:to_i}.sort{|s,t|s[0]<=>t[0]} #x zahyo tittyai jun
flg_r=Array.new(n,true)
cnt=0

b.each{|xb,yb|
    for i in 0...n
        if flg_r[i]&&r[i][0]<xb&&r[i][1]<yb
            cnt+=1
            flg_r[i]=false
            break
        end
    end
}

p cnt

Score : 400 points

Problem Statement

On a two-dimensional plane, there are N red points and N blue points.
The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i).

A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, and the y-coordinate of the red point is also smaller than that of the blue point.

At most how many friendly pairs can you form? Note that a point cannot belong to multiple pairs.

Constraints

All input values are integers.

1 \leq N \leq 100

0 \leq a_i, b_i, c_i, d_i < 2N

a_1, a_2, ..., a_N, c_1, c_2, ..., c_N are all different.

b_1, b_2, ..., b_N, d_1, d_2, ..., d_N are all different.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N

Output

Print the maximum number of friendly pairs.

Sample Input 1

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

Sample Output 1

2

For example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).

Sample Input 2

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

Sample Output 2

2

For example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).

Sample Input 3

2
2 2
3 3
0 0
1 1

Sample Output 3

0

It is possible that no pair can be formed.

Sample Input 4

5
0 0
7 3
2 2
4 8
1 6
8 5
6 9
5 4
9 1
3 7

Sample Output 4

5

Sample Input 5

5
0 0
1 1
5 5
6 6
7 7
2 2
3 3
4 4
8 8
9 9

Sample Output 5

4


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

    result = 0
    (1..n).each do |b|
      result += ( (n/b) * [(b-k), 0].max + [(n%b)-k+1, 0].max )
    end

    result -= n if k==0

    p result

Score : 100 points

Problem Statement

We have a 3×3 square grid, where each square contains a lowercase English letters.
The letter in the square at the i-th row from the top and j-th column from the left is c_{ij}.

Print the string of length 3 that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Constraints

Input consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

c_{11}c_{12}c_{13}
c_{21}c_{22}c_{23}
c_{31}c_{32}c_{33}

Output

Print the string of length 3 that can be obtained by concatenating the letters on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Sample Input 1

ant
obe
rec

Sample Output 1

abc

The letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid are a, b and c from top-right to bottom-left. Concatenate these letters and print abc.

Sample Input 2

edu
cat
ion

Sample Output 2

ean


Score : 200 points

Problem Statement

Find the number of palindromic numbers among the integers between A and B (inclusive).
Here, a palindromic number is a positive integer whose string representation in base 10 (without leading zeros) reads the same forward and backward.

Constraints

10000 \leq A \leq B \leq 99999

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the number of palindromic numbers among the integers between A and B (inclusive).

Sample Input 1

11009 11332

Sample Output 1

4

There are four integers that satisfy the conditions: 11011, 11111, 11211 and 11311.

Sample Input 2

31415 92653

Sample Output 2

612


a,b=gets.chomp.split(" ")
puts (a..b).count{|n| n == n.reverse}


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

# a < b のとき
asb = (K..N-1).map { |a| N - a }.inject(:+)

# a >= b のとき
alb = 0
(K+1..N).each do |b|
  between = (N-b+1)
  slots = between / b
  rest = between % b
  alb += (b-K) * slots
  alb += rest - K if rest > K
  alb -= 1 if K == 0
end

puts alb + asb

Score : 400 points

Problem Statement

Takahashi had a pair of two positive integers not exceeding N, (a,b), which he has forgotten.
He remembers that the remainder of a divided by b was greater than or equal to K.
Find the number of possible pairs that he may have had.

Constraints

1 \leq N \leq 10^5

0 \leq K \leq N-1

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of possible pairs that he may have had.

Sample Input 1

5 2

Sample Output 1

7

There are seven possible pairs: (2,3),(5,3),(2,4),(3,4),(2,5),(3,5) and (4,5).

Sample Input 2

10 0

Sample Output 2

100

Sample Input 3

31415 9265

Sample Output 3

287927211


Score : 100 points

Problem Statement

There are N students in a school.

We will divide these students into some groups, and in each group they will discuss some themes.

You think that groups consisting of two or less students cannot have an effective discussion, so you want to have as many groups consisting of three or more students as possible.

Divide the students so that the number of groups consisting of three or more students is maximized.

Constraints

1 \leq N \leq 1000

All input values are integers.

Input

Input is given from Standard Input in the following format:

N

Output

If you can form at most x groups consisting of three or more students, print x.

Sample Input 1

8

Sample Output 1

2

For example, you can form a group of three students and another of five students.

Sample Input 2

2

Sample Output 2

0

Sometimes you cannot form any group consisting of three or more students, regardless of how you divide the students.

Sample Input 3

9

Sample Output 3

3


io = STDIN
io = DATA   #!#!#!#!must delete
hh,ww,d=io.gets.split.map(&:to_i)
$hash={}
$memo=Array.new(hh*ww+1,0)
hh.times do |h|
  row=io.gets.split.map(&:to_i)
  row.each_with_index do |n,w|
    $hash[n]=[h,w]
  end
end
require 'pp'
((d+1)..hh*ww).each do |xy|
  i,j=$hash[xy-d]
  x,y=$hash[xy]
  $memo[xy]=$memo[xy-d]+(x-i).abs+(y-j).abs
end
q=io.gets.to_i
q.times do
  l,r=io.gets.split.map(&:to_i)
  puts $memo[r]-$memo[l]
end

Score : 400 points

Problem Statement

We have a grid with H rows and W columns. The square at the i-th row and the j-th column will be called Square (i,j).

The integers from 1 through H×W are written throughout the grid, and the integer written in Square (i,j) is A_{i,j}.

You, a magical girl, can teleport a piece placed on Square (i,j) to Square (x,y) by consuming |x-i|+|y-j| magic points.

You now have to take Q practical tests of your ability as a magical girl.

The i-th test will be conducted as follows:

Initially, a piece is placed on the square where the integer L_i is written.

Let x be the integer written in the square occupied by the piece. Repeatedly move the piece to the square where the integer x+D is written, as long as x is not R_i. The test ends when x=R_i.

Here, it is guaranteed that R_i-L_i is a multiple of D.

For each test, find the sum of magic points consumed during that test.

Constraints

1 \leq H,W \leq 300

1 \leq D \leq H×W

1 \leq A_{i,j} \leq H×W

A_{i,j} \neq A_{x,y} ((i,j) \neq (x,y))

1 \leq Q \leq 10^5

1 \leq L_i \leq R_i \leq H×W

(R_i-L_i) is a multiple of D.

Input

Input is given from Standard Input in the following format:

H W D
A_{1,1} A_{1,2} ... A_{1,W}
:
A_{H,1} A_{H,2} ... A_{H,W}
Q
L_1 R_1
:
L_Q R_Q

Output

For each test, print the sum of magic points consumed during that test.

Output should be in the order the tests are conducted.

Sample Input 1

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

Sample Output 1

5

4 is written in Square (1,2).

6 is written in Square (3,3).

8 is written in Square (3,1).

Thus, the sum of magic points consumed during the first test is (|3-1|+|3-2|)+(|3-3|+|1-3|)=5.

Sample Input 2

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

Sample Output 2

0
0

Note that there may be a test where the piece is not moved at all, and there may be multiple identical tests.

Sample Input 3

5 5 4
13 25 7 15 17
16 22 20 2 9
14 11 12 1 19
10 6 23 8 18
3 21 5 24 4
3
13 13
2 10
13 13

Sample Output 3

0
5
0


n=gets.to_i

if n < 10
  puts n
  exit 0
end

x = Math.log10(n).floor
ret = x*9 + (n/(10**x))
ret -= 1 if (n+1)%10 != 0
puts ret

Score : 300 points

Problem Statement

Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Constraints

1\leq N \leq 10^{16}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Sample Input 1

100

Sample Output 1

18

For example, the sum of the digits in 99 is 18, which turns out to be the maximum value.

Sample Input 2

9995

Sample Output 2

35

For example, the sum of the digits in 9989 is 35, which turns out to be the maximum value.

Sample Input 3

3141592653589793

Sample Output 3

137


n = gets.to_i
num = gets.strip.split.map(&:to_i)
num.sort.reverse #大きい順
i = 0
sum = 0
tum = 0
while i < n do
  if i%2==0
    sum += num[i]
  else
    tum += num[i]
  end
  i += 1
end
puts sum-tum

Score: 200 points

Problem Statement

We have N cards. A number a_i is written on the i-th card.

Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first.

The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards he/she has taken. When both players take the optimal strategy to maximize their scores, find Alice's score minus Bob's score.

Constraints

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

a_i \ (1 \leq i \leq N) is an integer between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print Alice's score minus Bob's score when both players take the optimal strategy to maximize their scores.

Sample Input 1

2
3 1

Sample Output 1

2

First, Alice will take the card with 3. Then, Bob will take the card with 1.
The difference of their scores will be 3 - 1 = 2.

Sample Input 2

3
2 7 4

Sample Output 2

5

First, Alice will take the card with 7. Then, Bob will take the card with 4. Lastly, Alice will take the card with 2. The difference of their scores will be 7 - 4 + 2 = 5. The difference of their scores will be 3 - 1 = 2.

Sample Input 3

4
20 18 2 18

Sample Output 3

18


cards_size = gets.to_i
cards = gets.split(" ").map(&:to_i)
cards.sort!{ |a, b| b <=> a }
alice = 0
bob = 0
isAliceTurn = true
cards.each do |card|
  if isAliceTurn then
    alice += card
    isAliceTurn = false
  else
    bob += card
    isAliceTurn = true
  end
end
puts alice - bob


Score: 300 points

Problem Statement

We have a 3 \times 3 grid. A number c_{i, j} is written in the square (i, j), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

According to Takahashi, there are six integers a_1, a_2, a_3, b_1, b_2, b_3 whose values are fixed, and the number written in the square (i, j) is equal to a_i + b_j.

Determine if he is correct.

Constraints

c_{i, j} \ (1 \leq i \leq 3, 1 \leq j \leq 3) is an integer between 0 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

c_{1,1} c_{1,2} c_{1,3}
c_{2,1} c_{2,2} c_{2,3}
c_{3,1} c_{3,2} c_{3,3}

Output

If Takahashi's statement is correct, print Yes; otherwise, print No.

Sample Input 1

1 0 1
2 1 2
1 0 1

Sample Output 1

Yes

Takahashi is correct, since there are possible sets of integers such as: a_1=0,a_2=1,a_3=0,b_1=1,b_2=0,b_3=1.

Sample Input 2

2 2 2
2 1 2
2 2 2

Sample Output 2

No

Takahashi is incorrect in this case.

Sample Input 3

0 8 8
0 8 8
0 8 8

Sample Output 3

Yes

Sample Input 4

1 8 6
2 9 7
0 7 7

Sample Output 4

No


c=3.times.map{gets.split.map(&:to_i)}
puts c.map{ |e| e.inject(:+) }.inject(:+)%3 == 0 ? :Yes : :No


grid=Array.new(3).map{Array.new(3)}
(0..2).each do |i|
  str=gets.chomp.split(" ").map{|str|str.to_i}
  grid[i]=str
end
p=Array.new()
q=Array.new()
r=Array.new()
(0..2).each do |i|
  p<<grid[i][0]-grid[i][1]
  q<<grid[i][1]-grid[i][2]
  r<<grid[i][2]-grid[i][0]
end
flag=p[0]==p[1] && p[1]==p[2]
flag=q[0]==q[1] && q[1]==q[2]
flag=r[0]==r[1] && r[1]==r[2]

if flag then
  puts "Yes"
else
  puts "No"
end


# Your code here!
c1 = gets.split.map &:to_i
c2 = gets.split.map &:to_i
c3 = gets.split.map &:to_i
c = [c1, c2, c3]

a = [0, 0, 0]
b = [0, 0, 0]

c1.length.times { |i|
    b[i] = c[0][i] - a[0]
}
c1.length.times { |i|
    a[i] = c[i][0] - b[0]
}

c1.length.times { |i|
  c1.length.times { |j|
    if c[i][j] != a[i] + b[j] then
        print('No')
        return
    end
  }
}

print('Yes')


cell = Array[9]

3.times do |i|
  cell[i*3],cell[i*3+1],cell[i*3+2] = gets.split(" ").map(&:to_i)
end

flg = true

if cell[0] - cell[3] != cell[1] - cell[4]
  flg = false
end

if cell[1] - cell[4] != cell[2] - cell[5]
  flg = false
end

if cell[3] - cell[6] != cell[4] - cell[7]
  flg = false
end

if cell[4] - cell[7] != cell[5] - cell[8]
  flg = false
end

if cell[0] - cell[6] != cell[1] - cell[7]
  flg = false
end

if cell[1] - cell[7] != cell[2] - cell[8]
  flg = false
end

puts flg ? "Yes" : "No"


H,W=gets.split.map(&:to_i)
S=[]
white=0
H.times{
	S << gets.chomp
	white+=S[-1].chars.count(".")
}
warn white
q=[[0,0,1]]
visited=Array.new(H){Array.new(W){false}}
dist=nil
until q.empty?
	x,y,d=q.shift
	if x==W-1 && y==H-1
		dist=d
		break
	end
	next if visited[y][x]
	next if S[y][x]=="#"
	visited[y][x]=true
	d+=1
	if x>0
		q << [x-1,y,d]
	end
	if x<W-1
		q << [x+1,y,d]
	end
	if y>0
		q << [x,y-1,d]
	end
	if y<H-1
		q << [x,y+1,d]
	end
end
warn dist
puts dist ? white-dist : -1

Score: 400 points

Problem statement

We have an H \times W grid whose squares are painted black or white. The square at the i-th row from the top and the j-th column from the left is denoted as (i, j).

Snuke would like to play the following game on this grid. At the beginning of the game, there is a character called Kenus at square (1, 1). The player repeatedly moves Kenus up, down, left or right by one square. The game is completed when Kenus reaches square (H, W) passing only white squares.

Before Snuke starts the game, he can change the color of some of the white squares to black. However, he cannot change the color of square (1, 1) and (H, W). Also, changes of color must all be carried out before the beginning of the game.

When the game is completed, Snuke's score will be the number of times he changed the color of a square before the beginning of the game. Find the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed, that is, Kenus can never reach square (H, W) regardless of how Snuke changes the color of the squares.

The color of the squares are given to you as characters s_{i, j}. If square (i, j) is initially painted by white, s_{i, j} is .; if square (i, j) is initially painted by black, s_{i, j} is #.

Constraints

H is an integer between 2 and 50 (inclusive).

W is an integer between 2 and 50 (inclusive).

s_{i, j} is . or # (1 \leq i \leq H, 1 \leq j \leq W).

s_{1, 1} and s_{H, W} are ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1}s_{1, 2}s_{1, 3} ... s_{1, W}
s_{2, 1}s_{2, 2}s_{2, 3} ... s_{2, W}
: :
s_{H, 1}s_{H, 2}s_{H, 3} ... s_{H, W}

Output

Print the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed.

Sample Input 1

3 3
..#
#..
...

Sample Output 1

2

The score 2 can be achieved by changing the color of squares as follows:

Sample Input 2

10 37
.....................................
...#...####...####..###...###...###..
..#.#..#...#.##....#...#.#...#.#...#.
..#.#..#...#.#.....#...#.#...#.#...#.
.#...#.#..##.#.....#...#.#.###.#.###.
.#####.####..#.....#...#..##....##...
.#...#.#...#.#.....#...#.#...#.#...#.
.#...#.#...#.##....#...#.#...#.#...#.
.#...#.####...####..###...###...###..
.....................................

Sample Output 2

209


require 'pp'
# IS_DEBUG = true
IS_DEBUG = false
def dputs str
	if(IS_DEBUG)
		puts str
	end
end
def dpp str
	if(IS_DEBUG)
		pp str
	end
end

class Maze
  ROOT='.'; WALL='#'; START='1'; GOAL='2'

  def initialize(map=nil, vec=nil)
    self.parseMap(map) if map
    unless vec
      vec = []
      for i in 0..3
        j = i%3==0 ? 1 : -1
        vec[i] = { :x=>(i+1)%2*j, :y=>i%2*j }
      end
    end
    @vec = vec
  end

  # マップ文字列を展開する
  def parseMap(map)
    @map = map.split("\n").map{|line| line.split }
    @size = Hash[*[[:x,:y],@map.shift.map{|val|val.to_i}].transpose.flatten]
    @map.each_with_index do |line,i|
      line.each_with_index do |val,j|
        @start = {:x=>j, :y=>i} if val==START
        @goal  = {:x=>j, :y=>i} if val==GOAL
      end
    end
  end

  # 探索開始
  def search()
    self.openNode(nil, pos=@start, cost=0)
    loop do
      cost += 1
      @vec.each do |vec|
        newPos = { :x=>pos[:x]+vec[:x], :y=>pos[:y]+vec[:y] }
        self.openNode(@map[pos[:y]][pos[:x]], newPos, cost)
        return true if newPos==@goal
      end
      self.closeNode(pos)
      return false unless pos=self.getNextPos()
    end
  end

  # OPENノードからコストが最小のノードを選ぶ
  def getNextPos()
    minScore = nil
    minNode = []
    for j in 0..@size[:y]-1
      for i in 0..@size[:x]-1
        if @map[j][i].is_a?(AStar) && @map[j][i].status===true then
          if !minScore || minScore>@map[j][i].score then
            minScore = @map[j][i].score
            minNode = [{ :x=>i, :y=>j }]
          elsif minScore==@map[j][i].score then
            minNode.push({ :x=>i, :y=>j })
          end
        end
      end
    end
    return minNode.length ? minNode[rand(minNode.length)] : false
  end

  # ノードを開く
  def openNode(parent, pos, cost)
    x=pos[:x]; y=pos[:y]
    return false if x<0 || y<0 || x>=@size[:x] || y>=@size[:y]
    return false if @map[y][x].is_a?(AStar) || @map[y][x]==WALL
    @map[y][x] = AStar.new(parent, cost, self.calcHeuristic(pos), pos)
    return true
  end

  # ノードを閉じる
  def closeNode(pos)
    @map[pos[:y]][pos[:x]].status = false
  end

  # ヒューリスティックコストを計算する
  def calcHeuristic(pos)
    x = pos[:x] - @goal[:x]
    y = pos[:y] - @goal[:y]
    return Math.sqrt(x*x+y*y).to_i
  end

  # スタートからゴールまでの道筋を辿る
  def getRoot()
    root=[]; node=@map[@goal[:y]][@goal[:x]]
    loop do
      return root.reverse unless node
      return false unless node.is_a?(AStar)
      root.push(node.pos)
      node = node.parent
    end
  end

  def getMap()
  	@map
  end
end

class AStar
  attr_accessor :status, :cost, :heuristic, :pos, :score, :parent

  def initialize(parent, cost, heuristic, pos)
    @status = true
    @parent=parent; @cost=cost; @heuristic=heuristic; @pos=pos
    self.calcScore()
  end

  def calcScore
    @score = @cost + @heuristic
  end
end

INT_MAX = 1000000001

H,W=gets.chomp.split(' ').map{|n| n.to_i}
S=Array.new(H){Array.new(W){0}}
0.upto(H-1){|i|
	S[i]=gets.chomp.split('').map{|n| n}
}
dp=Array.new(H){Array.new(W){INT_MAX }}

# 「.」のマス数
sum = 0
0.upto(H-1){|i|
	sum += (S[i].count{|i|i=="."})
}
# puts sum

S[0][0]=1
S[H-1][W-1]=2
map = <<EOM
#{W} #{H}
#{S.map{|a|a.join(" ")}.join("\n")}
EOM
#p map
maze = Maze.new(map)
# p maze.getMap()
maze.search()
path = maze.getRoot()
if(!path)
	puts "-1"
else
	p sum - path.size
end


a, b = gets.split.map(&:to_i)
i = 2
if a % b == 0
  puts -1
else
  loop do
    a *= 2
    if a % b != 0
      puts a
      exit
    end
    if a >= 1e18+1
      puts -1
      exit
    end
  end
end

Score : 100 points

Problem Statement

You are given positive integers X and Y.
If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it.
If it does not exist, print -1.

Constraints

1 ≤ X,Y ≤ 10^9

X and Y are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, or print -1 if it does not exist.

Sample Input 1

8 6

Sample Output 1

16

For example, 16 is a multiple of 8 but not a multiple of 6.

Sample Input 2

3 3

Sample Output 2

-1

A multiple of 3 is a multiple of 3.


class UnionFind
  def initialize(n)
    @size = Array.new(n + 1, 1)
    @rank = Array.new(n + 1, 0)
    @parent = []

    (0..n).each do |i|
      @parent[i] = i
    end
  end

  def find(x)
    if @parent[x] == x
      x
    else
      @parent[x] = find(@parent[x])
    end
  end

  def unite(x, y)
    x = find(x)
    y = find(y)
    return if x == y

    if @rank[x] < @rank[y]
      @parent[x] = y
      @size[y] += @size[x]
    else
      @parent[y] = x
      @size[x] += @size[y]

      @rank[x] += 1 if @rank[x] == @rank[y]
    end
  end

  def same?(x, y)
    find(x) == find(y)
  end

  def size(x)
    @size[find(x)]
  end
end

class PriorityQueue
  attr_reader :size

  def initialize(order: :asc)
    @size = 0
    @nodes = []
  end

  def empty?
    @size.zero?
  end

  def push(node)
    index = size
    @size += 1

    while index > 0
      parent = (index - 1) / 2

      break if (@nodes[parent] <=> node) <= 0

      @nodes[index] = @nodes[parent]
      index = parent
    end

    @nodes[index] = node
  end

  alias_method :<<, :push

  def pop
    node = @nodes.first
    root = @nodes[size - 1]
    @size -= 1
    index = 0

    while index * 2 + 1 < @size
      left = 2 * index + 1
      right = left + 1

      if right < size && (@nodes[right] <=> @nodes[left]) <= 0
        left = right
      end

      break if (@nodes[left] <=> root) > 0

      @nodes[index] = @nodes[left]
      index = left
    end

    @nodes[index] = root
    node
  end

  def top
    @nodes.first
  end
end

Node = Struct.new(:v, :cost) do
  def <=>(node)
    cost <=> node.cost
  end
end

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

uf = UnionFind.new(N + 1)

M.times do
  x, y = gets.split.map(&:to_i)

  uf.unite(x, y)
end

trees = Hash.new { |h, k| h[k] = [] }

N.times do |v|
  trees[uf.find(v)] << v
end

trees = trees.sort_by { |_, list| -list.size }

base = trees.shift
ans = 0

pque = PriorityQueue.new

base.last.each do |v|
  pque.push(Node.new(v, A[v]))
end

while !trees.empty? && !pque.empty?
  tree = trees.shift
  stock = PriorityQueue.new

  tree.last.each do |v|
    stock.push(Node.new(v, A[v]))
  end

  v = pque.pop
  u = stock.pop

  ans += v.cost + u.cost

  until stock.empty?
    pque.push(stock.pop)
  end
end

if trees.empty?
  puts ans
else
  puts 'Impossible'
end

Score : 600 points

Problem Statement

You are given a forest with N vertices and M edges. The vertices are numbered 0 through N-1.
The edges are given in the format (x_i,y_i), which means that Vertex x_i and y_i are connected by an edge.

Each vertex i has a value a_i.
You want to add edges in the given forest so that the forest becomes connected.
To add an edge, you choose two different vertices i and j, then span an edge between i and j.
This operation costs a_i + a_j dollars, and afterward neither Vertex i nor j can be selected again.

Find the minimum total cost required to make the forest connected, or print Impossible if it is impossible.

Constraints

1 ≤ N ≤ 100,000

0 ≤ M ≤ N-1

1 ≤ a_i ≤ 10^9

0 ≤ x_i,y_i ≤ N-1

The given graph is a forest.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_0 a_1 .. a_{N-1}
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the minimum total cost required to make the forest connected, or print Impossible if it is impossible.

Sample Input 1

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

Sample Output 1

7

If we connect vertices 0 and 5, the graph becomes connected, for the cost of 1 + 6 = 7 dollars.

Sample Input 2

5 0
3 1 4 1 5

Sample Output 2

Impossible

We can't make the graph connected.

Sample Input 3

1 0
5

Sample Output 3

0

The graph is already connected, so we do not need to add any edges.


def main()
  n, m = gets.split.map { |t| t.to_i }
  if m == 0
    puts "Yes"
    exit
  end
  loc_info = []
  m.times do
    loc_info.push(gets.split.map { |t| t.to_i })
  end

  # person to loc
  p2l = {}
  for t in loc_info
    if p2l[t[0]]
      p2l[t[0]].push(t)
    else
      p2l[t[0]] = [t]
    end
    if p2l[t[1]]
      p2l[t[1]].push(t)
    else
      p2l[t[1]] = [t]
    end
  end

  person = loc_info[0][0]
  loc_hash = {}
  while p2l.size > 0
    if loc_hash.empty?
      person = p2l.keys[0]
    else
      for person in loc_hash.keys
        break if p2l[person]
      end
      person = p2l.keys[0] unless person
    end
    list = p2l[person]
    p2l.delete(person)

    loc = loc_hash[person] || 0
    loc_hash[person] = loc
    for left, right, dist in list
      if left == person
        if loc_hash[right] and loc_hash[right] != loc + dist
          puts "No"
          exit
        end
        loc_hash[right] = loc + dist
      else
        if loc_hash[left] and loc_hash[left] != loc - dist
          puts "No"
          exit
        end
        loc_hash[left] = loc - dist
      end
    end
  end
  puts "Yes"
end

main if __FILE__ == $0

Score : 400 points

Problem Statement

There are N people standing on the x-axis.
Let the coordinate of Person i be x_i.
For every i, x_i is an integer between 0 and 10^9 (inclusive).
It is possible that more than one person is standing at the same coordinate.

You will given M pieces of information regarding the positions of these people.
The i-th piece of information has the form (L_i, R_i, D_i).
This means that Person R_i is to the right of Person L_i by D_i units of distance, that is, x_{R_i} - x_{L_i} = D_i holds.

It turns out that some of these M pieces of information may be incorrect.
Determine if there exists a set of values (x_1, x_2, ..., x_N) that is consistent with the given pieces of information.

Constraints

1 \leq N \leq 100 000

0 \leq M \leq 200 000

1 \leq L_i, R_i \leq N (1 \leq i \leq M)

0 \leq D_i \leq 10 000 (1 \leq i \leq M)

L_i \neq R_i (1 \leq i \leq M)

If i \neq j, then (L_i, R_i) \neq (L_j, R_j) and (L_i, R_i) \neq (R_j, L_j).

D_i are integers.

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1 D_1
L_2 R_2 D_2
:
L_M R_M D_M

Output

If there exists a set of values (x_1, x_2, ..., x_N) that is consistent with all given pieces of information, print Yes; if it does not exist, print No.

Sample Input 1

3 3
1 2 1
2 3 1
1 3 2

Sample Output 1

Yes

Some possible sets of values (x_1, x_2, x_3) are (0, 1, 2) and (101, 102, 103).

Sample Input 2

3 3
1 2 1
2 3 1
1 3 5

Sample Output 2

No

If the first two pieces of information are correct, x_3 - x_1 = 2 holds, which is contradictory to the last piece of information.

Sample Input 3

4 3
2 1 1
2 3 5
3 4 2

Sample Output 3

Yes

Sample Input 4

10 3
8 7 100
7 9 100
9 8 100

Sample Output 4

No

Sample Input 5

100 0

Sample Output 5

Yes


require 'complex'

a, b = gets.chomp.split(" ")
c = (a + b).to_i

# floorは小数点切り捨て
d = Math.sqrt(c).floor
if (d*d) == c
    puts "Yes"
else
    puts "No"
end

#puts "#{}"
#puts "#{}"

Score : 200 points

Problem Statement

AtCoDeer the deer has found two positive integers, a and b.
Determine whether the concatenation of a and b in this order is a square number.

Constraints

1 ≤ a,b ≤ 100

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

If the concatenation of a and b in this order is a square number, print Yes; otherwise, print No.

Sample Input 1

1 21

Sample Output 1

Yes

As 121 = 11 × 11, it is a square number.

Sample Input 2

100 100

Sample Output 2

No

100100 is not a square number.

Sample Input 3

12 10

Sample Output 3

No


n = gets.to_i
txy = n.times.map{gets.split.map(&:to_i)}

ans = 'Yes'
now_x = 0
now_y = 0
now_t = 0
txy.each do |t, x, y|
  diff_x = (now_x - x).abs
  diff_y = (now_y - y).abs
  diff_t = t - now_t
  dist = (diff_x + diff_y)
  unless diff_t >= dist && (diff_t - dist).even?
    ans = 'No'
    break
  end
  now_t = t
  now_x = x
  now_y = y
end

puts ans

Score : 300 points

Problem Statement

AtCoDeer the deer is going on a trip in a two-dimensional plane.
In his plan, he will depart from point (0, 0) at time 0, then for each i between 1 and N (inclusive), he will visit point (x_i,y_i) at time t_i.

If AtCoDeer is at point (x, y) at time t, he can be at one of the following points at time t+1: (x+1,y), (x-1,y), (x,y+1) and (x,y-1).
Note that he cannot stay at his place.
Determine whether he can carry out his plan.

Constraints

1 ≤ N ≤ 10^5

0 ≤ x_i ≤ 10^5

0 ≤ y_i ≤ 10^5

1 ≤ t_i ≤ 10^5

t_i < t_{i+1} (1 ≤ i ≤ N-1)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
t_1 x_1 y_1
t_2 x_2 y_2
:
t_N x_N y_N

Output

If AtCoDeer can carry out his plan, print Yes; if he cannot, print No.

Sample Input 1

2
3 1 2
6 1 1

Sample Output 1

Yes

For example, he can travel as follows: (0,0), (0,1), (1,1), (1,2), (1,1), (1,0), then (1,1).

Sample Input 2

1
2 100 100

Sample Output 2

No

It is impossible to be at (100,100) two seconds after being at (0,0).

Sample Input 3

2
5 1 1
100 1 1

Sample Output 3

No


n = gets.to_i
tc, xc, yc = [0, 0, 0]

ans = "Yes"

n.times do |i|
  tn, xn, yn = gets.split.map(&:to_i)

  t = tn - tc
  x = (xn - xc).abs
  y = (yn - yc).abs

  if x + y > t || (t - (x + y)).odd?
    ans = "No"
    break
  end

  tc, xc, yc = tn, xn, yn
end

puts ans


def action_handler(array, count)
  result = false
  current_nums = [0, 0, 0]
  time_index = 0
  x_index = 1
  y_index = 2
  for i in 0..(count - 2)
    is_first = i == 0
    now_array = is_first ? current_nums : array[i]
    next_array = is_first ? array[i] : array[i + 1]
    dt = next_array[time_index] - now_array[time_index]
    dx = next_array[x_index] - now_array[x_index]
    dy = next_array[y_index] - now_array[y_index]
    #時間内に移動できるかの計算
    dxy = dx.abs + dy.abs
    if dxy <= dt
      new_dxy = dx + dy
      if dt.even? != new_dxy.even?
        return false
      else
        result = true
      end
    else
      return false
    end
  end
  return result
end
=begin
def variable_finder(sec, coordinates)
  a = [coordinates[0] + 1, coordinates[1]]
  b = [coordinates[0] - 1, coordinates[1]]
  c = [coordinates[0], coordinates[1] + 1]
  d = [coordinates[0], coordinates[1] - 1]
  all_cases = [a, b, c, d]
  for x_i in 0..sec
    y_i = sec - x_i
    tmp = [coordinates[0] + x_i, coordinates[1] + y_i]
    tmp2 = [coordinates[0] - x_i, coordinates[1] + y_i]
    tmp3 = [coordinates[0] + x_i, coordinates[1] - y_i]
    tmp4 = [coordinates[0] - x_i, coordinates[1] - y_i]
    all_cases.push(tmp)
    all_cases.push(tmp2)
    all_cases.push(tmp3)
    all_cases.push(tmp4)
  end
  return all_cases.uniq
end
=end

#複数行に複数の要素が存在するとき
input = gets.chop.to_i
lines = []
while line = gets
    lines << line.chomp.split(' ').map(&:to_i)
end

#p action_handler([[3, 1, 2], [6, 1, 1]], 2) => true
print action_handler(lines, input) ? 'Yes' : 'No'


N,K = gets.split.map(&:to_i)
KK = 2*K

$tot = [0,0]
$elvis = (0..1).map{ (0..K).map{ Array.new(K+1,0) } }
N.times{
  x,y,c = gets.split
  x,y = [x,y].map{ |r| r.to_i % KK }
  c = c == "B" ? 0 : 1
  if x >= K
    x %= K; c ^= 1
  end
  if y >= K
    y %= K; c ^= 1
  end
  $elvis[c][x][y] += 1
  $tot[c] += 1
}

def C(color, x, y)
  return 0 if x < 0 || y < 0
  $elvis[color][x][y]
end

$sum = (0..1).map{ |color|
  lastline = Array.new(K+1, 0)
  (0..K).map{ |y|
    linesum = 0
    lastline = (0..K).map{ |x|
      linesum += C(color, x, y)
      lastline[x] + linesum
    }
    lastline
  }
}

#p $elvis[0], $sum[0]
#p $elvis[1], $sum[1]

def S(color, x, y)
  return 0 if x < 0 || y < 0
  $sum[color][x][y]
end
#exit
ans = 0
(0..K).each{ |x|
  (0..K).each{ |y|
	bb = 2*S(0, x-1, y-1) - S(0, K, y-1) - S(0, x-1, K)
	ww = 2*S(1, x-1, y-1) - S(1, K, y-1) - S(1, x-1, K)
    ans = [ans, bb+$tot[0]-ww, ww+$tot[1]-bb].max
    #p ans
  }
}
puts ans

Score : 500 points

Problem Statement

AtCoDeer is thinking of painting an infinite two-dimensional grid in a checked pattern of side K.
Here, a checked pattern of side K is a pattern where each square is painted black or white so that each connected component of each color is a K × K square.
Below is an example of a checked pattern of side 3:

AtCoDeer has N desires.
The i-th desire is represented by x_i, y_i and c_i.
If c_i is B, it means that he wants to paint the square (x_i,y_i) black; if c_i is W, he wants to paint the square (x_i,y_i) white.
At most how many desires can he satisfy at the same time?

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 1000

0 ≤ x_i ≤ 10^9

0 ≤ y_i ≤ 10^9

If i ≠ j, then (x_i,y_i) ≠ (x_j,y_j).

c_i is B or W.

N, K, x_i and y_i are integers.

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1 c_1
x_2 y_2 c_2
:
x_N y_N c_N

Output

Print the maximum number of desires that can be satisfied at the same time.

Sample Input 1

4 3
0 1 W
1 2 W
5 3 B
5 4 B

Sample Output 1

4

He can satisfy all his desires by painting as shown in the example above.

Sample Input 2

2 1000
0 0 B
0 1 W

Sample Output 2

2

Sample Input 3

6 2
1 2 B
2 1 W
2 2 B
1 0 B
0 6 W
4 5 W

Sample Output 3

4


n,y=gets.chomp.split(" ").map(&:to_i)
found = false
catch(:break_loop) do
  (0..n).each do|ichiman|
    total = ichiman * 10000
    if total == y
      puts "#{ichiman} 0 0"
      found = true
      break
    elsif total > y
      break
    end
    (0..n-ichiman).each do |gosen|
      total = ichiman * 10000 + gosen * 5000
      if total == y
        puts "#{ichiman} #{gosen} 0"
        found = true
        throw :break_loop
      elsif total > y
        break
      end
      sen = n - ichiman - gosen
      total = ichiman * 10000 + gosen * 5000 + sen * 1000
      if total == y
        puts "#{ichiman} #{gosen} #{sen}"
        found = true
        throw :break_loop
      end
    end
  end
end
puts '-1 -1 -1' unless found

Score : 100 points

Problem Statement

On some day in January 2018, Takaki is writing a document. The document has a column where the current date is written in yyyy/mm/dd format. For example, January 23, 2018 should be written as 2018/01/23.

After finishing the document, she noticed that she had mistakenly wrote 2017 at the beginning of the date column. Write a program that, when the string that Takaki wrote in the date column, S, is given as input, modifies the first four characters in S to 2018 and prints it.

Constraints

S is a string of length 10.

The first eight characters in S are 2017/01/.

The last two characters in S are digits and represent an integer between 1 and 31 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Replace the first four characters in S with 2018 and print it.

Sample Input 1

2017/01/07

Sample Output 1

2018/01/07

Sample Input 2

2017/01/31

Sample Output 2

2018/01/31


n,y=gets.chomp.split(" ").map(&:to_i)
found = false
catch(:break_loop) do
  (0..n).each do|ichiman|
    (0..n-ichiman).each do |gosen|
      sen = n - ichiman - gosen
      total = ichiman * 10000 + gosen * 5000 + sen * 1000
      if total == y
        puts "#{ichiman} #{gosen} #{sen}"
        found = true
      end
    end
  end
end
puts '-1 -1 -1' unless found


n = gets.to_i
c = Array.new(n, 0)
s = Array.new(n, 0)
f = Array.new(n, 0)

(n - 1).times do |i|
  ct, st, ft = gets.chomp.split.map(&:to_i)
  c[i] = ct
  s[i] = st
  f[i] = ft
end

n.times do |i|
  res = 0
  i.step(n - 2) do |j|
    if j == i
      res += s[j]
    elsif res < s[j]
      res = s[j]
    else
      res += (f[j] - res) % f[j]
    end
    res += c[j]
  end
  puts res
end

Score : 300 points

Problem Statement

A railroad running from west to east in Atcoder Kingdom is now complete.

There are N stations on the railroad, numbered 1 through N from west to east.

Tomorrow, the opening ceremony of the railroad will take place.

On this railroad, for each integer i such that 1≤i≤N-1, there will be trains that run from Station i to Station i+1 in C_i seconds. No other trains will be operated.

The first train from Station i to Station i+1 will depart Station i S_i seconds after the ceremony begins. Thereafter, there will be a train that departs Station i every F_i seconds.

Here, it is guaranteed that F_i divides S_i.

That is, for each Time t satisfying S_i≤t and t％F_i=0, there will be a train that departs Station i t seconds after the ceremony begins and arrives at Station i+1 t+C_i seconds after the ceremony begins, where A％B denotes A modulo B, and there will be no other trains.

For each i, find the earliest possible time we can reach Station N if we are at Station i when the ceremony begins, ignoring the time needed to change trains.

Constraints

1≤N≤500

1≤C_i≤100

1≤S_i≤10^5

1≤F_i≤10

S_i％F_i=0

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
C_1 S_1 F_1
:
C_{N-1} S_{N-1} F_{N-1}

Output

Print N lines. Assuming that we are at Station i (1≤i≤N) when the ceremony begins, if the earliest possible time we can reach Station N is x seconds after the ceremony begins, the i-th line should contain x.

Sample Input 1

3
6 5 1
1 10 1

Sample Output 1

12
11
0

We will travel from Station 1 as follows:

5 seconds after the beginning: take the train to Station 2.

11 seconds: arrive at Station 2.

11 seconds: take the train to Station 3.

12 seconds: arrive at Station 3.

We will travel from Station 2 as follows:

10 seconds: take the train to Station 3.

11 seconds: arrive at Station 3.

Note that we should print 0 for Station 3.

Sample Input 2

4
12 24 6
52 16 4
99 2 2

Sample Output 2

187
167
101
0

Sample Input 3

4
12 13 1
44 17 17
66 4096 64

Sample Output 3

4162
4162
4162
0


a=gets.to_i
b=gets.to_i
c=gets.to_i
d=gets.to_i
A=a+b
B=c+d
if A>B
  puts "Left"
elsif A==B
  puts "Balanced"
else
  puts "Right"
end

Score : 100 points

Problem Statement

A balance scale tips to the left if L>R, where L is the total weight of the masses on the left pan and R is the total weight of the masses on the right pan. Similarly, it balances if L=R, and tips to the right if L<R.

Takahashi placed a mass of weight A and a mass of weight B on the left pan of a balance scale, and placed a mass of weight C and a mass of weight D on the right pan.

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Constraints

1\leq A,B,C,D \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Sample Input 1

3 8 7 1

Sample Output 1

Left

The total weight of the masses on the left pan is 11, and the total weight of the masses on the right pan is 8. Since 11>8, we should print Left.

Sample Input 2

3 4 5 2

Sample Output 2

Balanced

The total weight of the masses on the left pan is 7, and the total weight of the masses on the right pan is 7. Since 7=7, we should print Balanced.

Sample Input 3

1 7 6 4

Sample Output 3

Right

The total weight of the masses on the left pan is 8, and the total weight of the masses on the right pan is 10. Since 8<10, we should print Right.


s = gets.chomp.chars.map(&:ord).sort
t = gets.chomp.chars.map(&:ord).sort.reverse
s << 0
t << -1

t.length.times{ |i|
  s_min = s[i]
  t_max = t[i]
  if s[i].nil? || s_min < t_max
    puts 'Yes'
    break
  elsif s_min > t_max
    puts 'No'
    break
  end
}

Score : 200 points

Problem Statement

You are given strings s and t, consisting of lowercase English letters.
You will create a string s' by freely rearranging the characters in s.
You will also create a string t' by freely rearranging the characters in t.
Determine whether it is possible to satisfy s' < t' for the lexicographic order.

Notes

For a string a = a_1 a_2 ... a_N of length N and a string b = b_1 b_2 ... b_M of length M, we say a < b for the lexicographic order if either one of the following two conditions holds true:

N < M and a_1 = b_1, a_2 = b_2, ..., a_N = b_N.

There exists i (1 \leq i \leq N, M) such that a_1 = b_1, a_2 = b_2, ..., a_{i - 1} = b_{i - 1} and a_i < b_i. Here, letters are compared using alphabetical order.

For example, xy < xya and atcoder < atlas.

Constraints

The lengths of s and t are between 1 and 100 (inclusive).

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If it is possible to satisfy s' < t', print Yes; if it is not, print No.

Sample Input 1

yx
axy

Sample Output 1

Yes

We can, for example, rearrange yx into xy and axy into yxa. Then, xy < yxa.

Sample Input 2

ratcode
atlas

Sample Output 2

Yes

We can, for example, rearrange ratcode into acdeort and atlas into tslaa. Then, acdeort < tslaa.

Sample Input 3

cd
abc

Sample Output 3

No

No matter how we rearrange cd and abc, we cannot achieve our objective.

Sample Input 4

w
ww

Sample Output 4

Yes

Sample Input 5

zzz
zzz

Sample Output 5

No


a = gets.chomp.split("").sort
b = gets.chomp.split("").sort.reverse
c = a.join("")
d = b.join("")
if c < d
  puts "Yes"
else
  puts "No"
end


s = gets.chomp.chars.sort.join
t = gets.chomp.chars.sort{|a, b| b <=> a}.join
puts s < t ? "Yes" : "No"


s =gets.split('')
t =gets.split('')

S = s.sort
T = t.sort

if -1 == ( S <=> T )
  puts 'Yes'
else
  puts 'No'
end


s=gets.chomp.split("").sort.join
t=gets.chomp.split("").sort.reverse.join
puts s<t ? :Yes : :No


require 'pp'

S,dum=gets.chomp.split(' ').map{|n| n}
X,Y=gets.chomp.split(' ').map{|n| n.to_i}

rf = [0]
rolf = []
uodf = []

dir = "r"
flen = 0

# translate S
0.upto(S.size-1){|i|
	case S[i]
	when "F"
		flen += 1
		puts "after F:"
		pp "flen:#{flen}"
	when "T"
		if(flen != 0)
			case dir
			when "rol"
				rolf << flen
			when "uod"
				uodf << flen
			when "r"
				rf = [flen]
			end
			flen = 0
		end
		case dir
		when "rol"
			dir = "uod"
		when "uod"
			dir = "rol"
		when "r"
			dir = "uod"
		end
	end
}
if(flen != 0)
	case dir
	when "rol"
		rolf << flen
	when "uod"
		uodf << flen
	when "r"
		rf = [flen]
	end
	flen = 0
end

puts "rf"
pp rf
puts "rolf"
pp rolf
puts "uodf"
pp uodf

flg=true
tmprolf = rolf.inject([rf[0]]){|prod, flen| prod.product([flen, -flen]).collect{|set| set[0]+set[1]}}.uniq
puts "rolf"
pp tmprolf
if(tmprolf.include?(X))
	flg=true
else
	flg=false
end
if(flg)
	tmpuodf = uodf.inject([0]){|prod, flen| prod.product([flen, -flen]).collect{|set| set[0]+set[1]}}.uniq
	puts "uodf"
	pp tmpuodf
	if(tmpuodf.include?(Y))
		puts "Yes"
	else
		puts "No"
	end
else
	puts "No"
end

Score : 500 points

Problem Statement

A robot is put at the origin in a two-dimensional plane.
Initially, the robot is facing in the positive x-axis direction.

This robot will be given an instruction sequence s.
s consists of the following two kinds of letters, and will be executed in order from front to back.

F : Move in the current direction by distance 1.

T : Turn 90 degrees, either clockwise or counterclockwise.

The objective of the robot is to be at coordinates (x, y) after all the instructions are executed.
Determine whether this objective is achievable.

Constraints

s consists of F and T.

1 \leq |s| \leq 8 000

x and y are integers.

|x|, |y| \leq |s|

Input

Input is given from Standard Input in the following format:

s
x y

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

FTFFTFFF
4 2

Sample Output 1

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning clockwise in the second T.

Sample Input 2

FTFFTFFF
-2 -2

Sample Output 2

Yes

The objective can be achieved by, for example, turning clockwise in the first T and turning clockwise in the second T.

Sample Input 3

FF
1 0

Sample Output 3

No

Sample Input 4

TF
1 0

Sample Output 4

No

Sample Input 5

FFTTFF
0 0

Sample Output 5

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning counterclockwise in the second T.

Sample Input 6

TTTT
1 0

Sample Output 6

No


n = gets.to_i
nums = get.split
as = []
n.times do |i|
  as << nums[i].to_i
end

def division(array)
  count_even = 0
  array.each do |num|
    if num.even?
      count_even += 1
    end
  end
  return false, 0 if count_even != array.length

  array.map do |num|
    num / 2
  end
  return true, array
end

count_divide = 0
30.times do |i|
  flag, as = division(as)
  if flag
    count_divide += 1
  else
    break
  end
end

puts count_divide

Score : 200 points

Problem Statement

There are N positive integers written on a blackboard: A_1, ..., A_N.

Snuke can perform the following operation when all integers on the blackboard are even:

Replace each integer X on the blackboard by X divided by 2.

Find the maximum possible number of operations that Snuke can perform.

Constraints

1 \leq N \leq 200

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of operations that Snuke can perform.

Sample Input 1

3
8 12 40

Sample Output 1

2

Initially, [8, 12, 40] are written on the blackboard.
Since all those integers are even, Snuke can perform the operation.

After the operation is performed once, [4, 6, 20] are written on the blackboard.
Since all those integers are again even, he can perform the operation.

After the operation is performed twice, [2, 3, 10] are written on the blackboard.
Now, there is an odd number 3 on the blackboard, so he cannot perform the operation any more.

Thus, Snuke can perform the operation at most twice.

Sample Input 2

4
5 6 8 10

Sample Output 2

0

Since there is an odd number 5 on the blackboard already in the beginning, Snuke cannot perform the operation at all.

Sample Input 3

6
382253568 723152896 37802240 379425024 404894720 471526144

Sample Output 3

8


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

result = 0
while a.all?(&:even?)
  a = a.map{|x| x / 2}
  result += 1
end
print result


# frozen_string_literal: true

item_count = gets.chomp.to_i

return puts 0 if item_count < 1

items = gets.chomp.split(' ').map(&:to_i)

division_count = 0

while items.reject(&:even?).empty?
  items = items.map do |item|
    division_count += 1
    item / 2
  end
end

puts division_count


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

flg = true
cnt = 0

while flg
  a.map! do |i|
    if i %2 == 0
      i/2
    else
      flg = false
      i
    end
  end
  cnt = cnt + 1
end

puts cnt


n=gets().to_i
A=gets().chomp.split(" ").map(&:to_i)
e=0
ans=0

while true
    for i in 0..n-1
        if A[i]%2!=0
            e=1
        end
    end
    if e==1
        break
    end
    for i in 0..n-1
        A[i]=A[i]/2
    end
    ans+=1
end

puts ans


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

i = 0
m = 0
logs = []

while
  y = i + 1
  break unless nums[y]
  unless nums[i] <= nums[y]
    if nums[i] >= 0
      nums[y] += nums[i]
      logs << [i + 1, y + 1]
    else
      nums[i] += nums[y]
      logs << [y + 1, i + 1]
    end
    m += 1
  else
    i += 1
  end
end

puts m
logs.each { |x, y| puts "#{x} #{y}" }

Score : 600 points

Problem Statement

Snuke has an integer sequence, a, of length N. The i-th element of a (1-indexed) is a_{i}.

He can perform the following operation any number of times:

Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.

He would like to perform this operation between 0 and 2N times (inclusive) so that a satisfies the condition below. Show one such sequence of operations.
It can be proved that such a sequence of operations always exists under the constraints in this problem.

Condition: a_1 \leq a_2 \leq ... \leq a_{N}

Constraints

2 \leq N \leq 50

-10^{6} \leq a_i \leq 10^{6}

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{N}

Output

Let m be the number of operations in your solution. In the first line, print m.
In the i-th of the subsequent m lines, print the numbers x and y chosen in the i-th operation, with a space in between.
The output will be considered correct if m is between 0 and 2N (inclusive) and a satisfies the condition after the m operations.

Sample Input 1

3
-2 5 -1

Sample Output 1

2
2 3
3 3

After the first operation, a = (-2,5,4).

After the second operation, a = (-2,5,8), and the condition is now satisfied.

Sample Input 2

2
-1 -3

Sample Output 2

1
2 1

After the first operation, a = (-4,-3) and the condition is now satisfied.

Sample Input 3

5
0 0 0 0 0

Sample Output 3

0

The condition is satisfied already in the beginning.


n, a, b = gets.chomp.split.map(&:to_i)
puts [n*a, b].min

Score : 100 points

Problem Statement

You are parking at a parking lot. You can choose from the following two fee plans:

Plan 1: The fee will be A×T yen (the currency of Japan) when you park for T hours.

Plan 2: The fee will be B yen, regardless of the duration.

Find the minimum fee when you park for N hours.

Constraints

1≤N≤20

1≤A≤100

1≤B≤2000

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

When the minimum fee is x yen, print the value of x.

Sample Input 1

7 17 120

Sample Output 1

119

If you choose Plan 1, the fee will be 7×17=119 yen.

If you choose Plan 2, the fee will be 120 yen.

Thus, the minimum fee is 119 yen.

Sample Input 2

5 20 100

Sample Output 2

100

The fee might be the same in the two plans.

Sample Input 3

6 18 100

Sample Output 3

100


n = gets
f = n.chars.map(&:to_i).reduce(:+)
(n.to_i % f == 0) ? puts('Yes') : puts('No')

Score : 200 points

Problem Statement

An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10.

Given an integer N, determine whether it is a Harshad number.

Constraints

1?N?10^8

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print Yes if N is a Harshad number; print No otherwise.

Sample Input 1

12

Sample Output 1

Yes

f(12)=1+2=3. Since 12 is divisible by 3, 12 is a Harshad number.

Sample Input 2

57

Sample Output 2

No

f(57)=5+7=12. Since 57 is not divisible by 12, 12 is not a Harshad number.

Sample Input 3

148

Sample Output 3

No


#input of int(split by space)
def get_i()
  return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
  return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
  return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
  return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
  return bool ? y : n
end
#create of array
def array(size1,init=nil,size2=-1)
  if size2==-1
      return Array.new(size1){init}
  else
      return Array.new(size2){Array.new(size1){init}}
  end
end

def max(a,b)
    return a>b ? a : b
end

def min(a,b)
    return a>b ? b : a
end

INF=Float::INFINITY

N,C=get_i
table=array(10**5,0)
N.times do|i|
  s,t,c=get_i
  s-=1
  t-=1
  table[s]+=1
  table[t+1]-=1
end
imos=array(10**5+1,0)
ans=0
(10**5).times do|i|
    imos[i+1]+=imos[i]+table[i]
    ans=max(ans,imos[i+1])
end
#p imos[0..20]
puts ans

Score : 400 points

Problem Statement

Joisino is planning to record N TV programs with recorders.

The TV can receive C channels numbered 1 through C.

The i-th program that she wants to record will be broadcast from time s_i to time t_i (including time s_i but not t_i) on Channel c_i.

Here, there will never be more than one program that are broadcast on the same channel at the same time.

When the recorder is recording a channel from time S to time T (including time S but not T), it cannot record other channels from time S-0.5 to time T (including time S-0.5 but not T).

Find the minimum number of recorders required to record the channels so that all the N programs are completely recorded.

Constraints

1≤N≤10^5

1≤C≤30

1≤s_i<t_i≤10^5

1≤c_i≤C

If c_i=c_j and i≠j, either t_i≤s_j or s_i≥t_j.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N C
s_1 t_1 c_1
:
s_N t_N c_N

Output

When the minimum required number of recorders is x, print the value of x.

Sample Input 1

3 2
1 7 2
7 8 1
8 12 1

Sample Output 1

2

Two recorders can record all the programs, for example, as follows:

With the first recorder, record Channel 2 from time 1 to time 7. The first program will be recorded. Note that this recorder will be unable to record other channels from time 0.5 to time 7.

With the second recorder, record Channel 1 from time 7 to time 12. The second and third programs will be recorded. Note that this recorder will be unable to record other channels from time 6.5 to time 12.

Sample Input 2

3 4
1 3 2
3 4 4
1 4 3

Sample Output 2

3

There may be a channel where there is no program to record.

Sample Input 3

9 4
56 60 4
33 37 2
89 90 3
32 43 1
67 68 3
49 51 3
31 32 3
70 71 1
11 12 3

Sample Output 3

2


puts gets =~ /^A?KIHA?BA?RA?$/ ? 'YES' : 'NO'

Score : 300 points

Problem Statement

You are given a string S.

Takahashi can insert the character A at any position in this string any number of times.

Can he change S into AKIHABARA?

Constraints

1 \leq |S| \leq 50

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If it is possible to change S into AKIHABARA, print YES; otherwise, print NO.

Sample Input 1

KIHBR

Sample Output 1

YES

Insert one A at each of the four positions: the beginning, immediately after H, immediately after B and the end.

Sample Input 2

AKIBAHARA

Sample Output 2

NO

The correct spell is AKIHABARA.

Sample Input 3

AAKIAHBAARA

Sample Output 3

NO


S = gets.chomp
["+", "-"].repeated_permutation(3) do |t|
  formula = S.chars.zip(t).join
  if eval(formula) == 7
    puts "#{formula}=7"
    exit
  end
end

Score : 300 points

Problem Statement

Sitting in a station waiting room, Joisino is gazing at her train ticket.

The ticket is numbered with four digits A, B, C and D in this order, each between 0 and 9 (inclusive).

In the formula A op1 B op2 C op3 D = 7, replace each of the symbols op1, op2 and op3 with + or - so that the formula holds.

The given input guarantees that there is a solution. If there are multiple solutions, any of them will be accepted.

Constraints

0≤A,B,C,D≤9

All input values are integers.

It is guaranteed that there is a solution.

Input

Input is given from Standard Input in the following format:

ABCD

Output

Print the formula you made, including the part =7.

Use the signs + and -.

Do not print a space between a digit and a sign.

Sample Input 1

1222

Sample Output 1

1+2+2+2=7

This is the only valid solution.

Sample Input 2

0290

Sample Output 2

0-2+9+0=7

0 - 2 + 9 - 0 = 7 is also a valid solution.

Sample Input 3

3242

Sample Output 3

3+2+4-2=7


a, b, c, d = gets.chomp.split("").map(&:to_i)
op = []
flag = false
(0..1).each do |i|
    (0..1).each do |j|
        (0..1).each do |k|
            (0..1).each do |l|
                if (i*2-1)*a + (j*2-1)*b + (k*2-1)*c + (l*2-1)*d == 7
                    op.push(i, j, k, l)
                    flag = true
                end
                break if flag
            end
            break if flag
        end
        break if flag
    end
    break if flag
end
(0..3).each do |i|
    if op[i] == 1
        op[i] = '+'
    else
        op[i] = '-'
    end
end

puts "#{a}#{op[0]}#{b}#{op[1]}#{c}#{op[2]}#{d}#{op[3]}=7"


abcd = gets.chomp

(1..8).each do |x|
  s = abcd.dup
  2.downto(0) do |i|
    o = (x & (1 << i)).zero? ? "-" : "+"
    s[i+1, 0] = o
  end
  if eval(s) == 7
    puts s + "=7"
    exit
  end
end


h, w = gets.split.map(&:to_i)
c = 10.times.map {gets.split.map(&:to_i)}
c << [0, 0]

10.times do |i|
    10.times do |j|
        c[i][1] = c[i][j] + c[j][1] if c[i][1] > c[i][j] + c[j][1]
    end
end

ans = 0
h.times {gets.split.each {|e| ans += c[e.to_i][1]}}
puts ans

Score : 400 points

Problem Statement

Joisino the magical girl has decided to turn every single digit that exists on this world into 1.

Rewriting a digit i with j (0≤i,j≤9) costs c_{i,j} MP (Magic Points).

She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digit between 0 and 9 (inclusive).

You are given A_{i,j} that describes the square at the i-th row from the top and j-th column from the left, as follows:

If A_{i,j}≠-1, the square contains a digit A_{i,j}.

If A_{i,j}=-1, the square does not contain a digit.

Find the minimum total amount of MP required to turn every digit on this wall into 1 in the end.

Constraints

1≤H,W≤200

1≤c_{i,j}≤10^3 (i≠j)

c_{i,j}=0 (i=j)

-1≤A_{i,j}≤9

All input values are integers.

There is at least one digit on the wall.

Input

Input is given from Standard Input in the following format:

H W
c_{0,0} ... c_{0,9}
:
c_{9,0} ... c_{9,9}
A_{1,1} ... A_{1,W}
:
A_{H,1} ... A_{H,W}

Output

Print the minimum total amount of MP required to turn every digit on the wall into 1 in the end.

Sample Input 1

2 4
0 9 9 9 9 9 9 9 9 9
9 0 9 9 9 9 9 9 9 9
9 9 0 9 9 9 9 9 9 9
9 9 9 0 9 9 9 9 9 9
9 9 9 9 0 9 9 9 9 2
9 9 9 9 9 0 9 9 9 9
9 9 9 9 9 9 0 9 9 9
9 9 9 9 9 9 9 0 9 9
9 9 9 9 2 9 9 9 0 9
9 2 9 9 9 9 9 9 9 0
-1 -1 -1 -1
8 1 1 8

Sample Output 1

12

To turn a single 8 into 1, it is optimal to first turn 8 into 4, then turn 4 into 9, and finally turn 9 into 1, costing 6 MP.

The wall contains two 8s, so the minimum total MP required is 6×2=12.

Sample Input 2

5 5
0 999 999 999 999 999 999 999 999 999
999 0 999 999 999 999 999 999 999 999
999 999 0 999 999 999 999 999 999 999
999 999 999 0 999 999 999 999 999 999
999 999 999 999 0 999 999 999 999 999
999 999 999 999 999 0 999 999 999 999
999 999 999 999 999 999 0 999 999 999
999 999 999 999 999 999 999 0 999 999
999 999 999 999 999 999 999 999 0 999
999 999 999 999 999 999 999 999 999 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Sample Output 2

0

Note that she may not need to change any digit.

Sample Input 3

3 5
0 4 3 6 2 7 2 5 3 3
4 0 5 3 7 5 3 7 2 7
5 7 0 7 2 9 3 2 9 1
3 6 2 0 2 4 6 4 2 3
3 5 7 4 0 6 9 7 6 7
9 8 5 2 2 0 4 7 6 5
5 4 6 3 2 3 0 5 4 3
3 6 2 3 4 2 4 0 8 9
4 6 5 4 3 5 3 2 0 8
2 1 3 4 5 7 8 6 4 0
3 5 2 6 1
2 5 3 2 1
6 9 2 5 6

Sample Output 3

47


def get_i() #空白区切の入力を数値(整数)の配列で返す
  return gets.chomp.split(" ").map(&:to_i)
end
def get_f() #空白区切の入力を数値(実数)の配列で返す
  return gets.chomp.split(" ").map(&:to_f)
end
def get() #空白区切の入力を文字列の配列で返す
  return gets.chomp.split(" ")
end
def get_nsp() #入力されたものを一文字ずつに区切った文字列の配列で返す
  return gets.chomp.split("")
end
def yn_judge(bool,y="Yes",n="No") #boolに真偽を投げることで、trueならy、falseならnの値を出力する
  return bool ? y : n
end
def array(size1,init=nil,size2=-1) #size2に二次元配列時の最初の要素数、size1に次の配列の大きさ、initに初期値を投げることでその配列を返す
  if size2==-1
    return Array.new(size1){init}
  else
    return Array.new(size2){Array.new(size1){init}}
  end
end

X,Y,Z=get_i
puts (X-Z)/(Y+Z)

Score : 200 points

Problem Statement

We have a long seat of width X centimeters.
There are many people who wants to sit here. A person sitting on the seat will always occupy an interval of length Y centimeters.

We would like to seat as many people as possible, but they are all very shy, and there must be a gap of length at least Z centimeters between two people, and between the end of the seat and a person.

At most how many people can sit on the seat?

Constraints

All input values are integers.

1 \leq X, Y, Z \leq 10^5

Y+2Z \leq X

Input

Input is given from Standard Input in the following format:

X Y Z

Output

Print the answer.

Sample Input 1

13 3 1

Sample Output 1

3

There is just enough room for three, as shown below:

Figure

Sample Input 2

12 3 1

Sample Output 2

2

Sample Input 3

100000 1 1

Sample Output 3

49999

Sample Input 4

64146 123 456

Sample Output 4

110

Sample Input 5

64145 123 456

Sample Output 5

109


Score : 200 points

Problem Statement

Find the largest square number not exceeding N. Here, a square number is an integer that can be represented as the square of an integer.

Constraints

1 \leq N \leq 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the largest square number not exceeding N.

Sample Input 1

10

Sample Output 1

9

10 is not square, but 9 = 3 × 3 is. Thus, we print 9.

Sample Input 2

81

Sample Output 2

81

Sample Input 3

271828182

Sample Output 3

271821169


def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def r_sort(a) a.sort{|a,b|b<=>a} end

def b_ser(bot, top, a, target, u_r_f = nil, mm = nil)
  mid = (bot + top)/2
  if(a[mid] == target)
    if(u_r_f == nil)
      return mid
    else
      return mid if(bot == mid)
      return b_ser(bot, mid, a, target, u_r_f, mid)
    end
  end
  if(bot == mid)
    return nil if(u_r_f == nil)
    return mid + ((a[mid] < target)? 1 : 0)
  end
  return (a[mid] > target)? b_ser(bot, mid, a, target, u_r_f, mm) : b_ser(mid, top, a, target, u_r_f, mm)
end

n = inp[0]
a = inp.sort
b = inp.sort
c = inp.sort
abt = []
a.size.times do |i|
  abt[i] = b_ser(0,n,b,a[i]+1,true)
end
bct = []
b.size.times do |i|
  bct[i] = b_ser(0,n,c,b[i]+1,true)
end

bcs = na(n,0)
sum = 0
n.times do |i|
  i = n-i-1
  sum += n - bct[i]
  bcs[i] = sum
end
ans = 0
abt.each do |d|
  break if d >= n
  ans += bcs[d]
end
p ans

Score : 300 points

Problem Statement

The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.

He has N parts for each of the three categories. The size of the i-th upper part is A_i, the size of the i-th middle part is B_i, and the size of the i-th lower part is C_i.

To build an altar, the size of the middle part must be strictly greater than that of the upper part, and the size of the lower part must be strictly greater than that of the middle part. On the other hand, any three parts that satisfy these conditions can be combined to form an altar.

How many different altars can Ringo build? Here, two altars are considered different when at least one of the three parts used is different.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9(1\leq i\leq N)

1 \leq B_i \leq 10^9(1\leq i\leq N)

1 \leq C_i \leq 10^9(1\leq i\leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N
B_1 ... B_N
C_1 ... C_N

Output

Print the number of different altars that Ringo can build.

Sample Input 1

2
1 5
2 4
3 6

Sample Output 1

3

The following three altars can be built:

Upper: 1-st part, Middle: 1-st part, Lower: 1-st part

Upper: 1-st part, Middle: 1-st part, Lower: 2-nd part

Upper: 1-st part, Middle: 2-nd part, Lower: 2-nd part

Sample Input 2

3
1 1 1
2 2 2
3 3 3

Sample Output 2

27

Sample Input 3

6
3 14 159 2 6 53
58 9 79 323 84 6
2643 383 2 79 50 288

Sample Output 3

87


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

res = b.inject(0) do |r, bi|
  ai = a.bsearch_index{ |x| x >= bi }
  ci = c.bsearch_index{ |x| x > bi }

  if ai and ci
    r + (ai)*(n-ci)
  else
    r
  end
end

puts res


N = gets.to_i
A = gets.split.map &:to_i
p 3**N-2**A.count(&:even?)

Score : 200 points

Problem Statement

We will say that two integer sequences of length N, x_1, x_2, ..., x_N and y_1, y_2, ..., y_N, are similar when |x_i - y_i| \leq 1 holds for all i (1 \leq i \leq N).

In particular, any integer sequence is similar to itself.

You are given an integer N and an integer sequence of length N, A_1, A_2, ..., A_N.

How many integer sequences b_1, b_2, ..., b_N are there such that b_1, b_2, ..., b_N is similar to A and the product of all elements, b_1 b_2 ... b_N, is even?

Constraints

1 \leq N \leq 10

1 \leq A_i \leq 100

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the number of integer sequences that satisfy the condition.

Sample Input 1

2
2 3

Sample Output 1

7

There are seven integer sequences that satisfy the condition:

1, 2

1, 4

2, 2

2, 3

2, 4

3, 2

3, 4

Sample Input 2

3
3 3 3

Sample Output 2

26

Sample Input 3

1
100

Sample Output 3

1

Sample Input 4

10
90 52 56 71 44 8 13 30 57 84

Sample Output 4

58921


a, b, c = gets.chomp.split(" ").map(&:to_i)
if a == b
	puts c
elsif a == c
	puts b
else
	puts a
end

Score : 100 points

Problem Statement

You are given three integers, A, B and C.

Among them, two are the same, but the remaining one is different from the rest.

For example, when A=5,B=7,C=5, A and C are the same, but B is different.

Find the one that is different from the rest among the given three integers.

Constraints

-100 \leq A,B,C \leq 100

A, B and C are integers.

The input satisfies the condition in the statement.

Input

Input is given from Standard Input in the following format:

A B C

Output

Among A, B and C, print the integer that is different from the rest.

Sample Input 1

5 7 5

Sample Output 1

7

This is the same case as the one in the statement.

Sample Input 2

1 1 7

Sample Output 2

7

In this case, C is the one we seek.

Sample Input 3

-100 100 100

Sample Output 3

-100


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

  p = [nil] * n
  x = [nil] * n
  y = [nil] * n
  n.times do |i|
    (x[i], y[i]) = gets.chomp.split(' ').map(&:to_i)
    p[i] = {:x => x[i], :y => y[i]}
  end
  x.sort!
  y.sort!

  s_min = 1e+20.to_i
  n.times do |ix|
    x_min = x[ix]

    n.times do |iy|
      y_min = y[iy]

      n.times do |jx|
        x_max = x[jx]
        next if x_min >= x_max

        n.times do |jy|
          y_max = y[jy]
          next if y_min >= y_max

          c = 0
          n.times do |l|
            if x_min <= p[l][:x] && p[l][:x] <= x_max then
              if y_min <= p[l][:y] && p[l][:y] <= y_max then
                c += 1
              end
            end
          end

          if c >= k then
            s_min = [s_min, (x_max - x_min) * (y_max - y_min)].min
          end
        end
      end
    end
  end

  puts s_min.to_s
end

if self.to_s == 'main' then
  main(ARGV)
end

Score : 400 points

Problem Statement

We have N points in a two-dimensional plane.

The coordinates of the i-th point (1 \leq i \leq N) are (x_i,y_i).

Let us consider a rectangle whose sides are parallel to the coordinate axes that contains K or more of the N points in its interior.

Here, points on the sides of the rectangle are considered to be in the interior.

Find the minimum possible area of such a rectangle.

Constraints

2 \leq K \leq N \leq 50

-10^9 \leq x_i,y_i \leq 10^9 (1 \leq i \leq N)

x_i≠x_j (1 \leq i<j \leq N)

y_i≠y_j (1 \leq i<j \leq N)

All input values are integers. (Added at 21:50 JST)

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1
:
x_{N} y_{N}

Output

Print the minimum possible area of a rectangle that satisfies the condition.

Sample Input 1

4 4
1 4
3 3
6 2
8 1

Sample Output 1

21

One rectangle that satisfies the condition with the minimum possible area has the following vertices: (1,1), (8,1), (1,4) and (8,4).

Its area is (8-1) × (4-1) = 21.

Sample Input 2

4 2
0 0
1 1
2 2
3 3

Sample Output 2

1

Sample Input 3

4 3
-1000000000 -1000000000
1000000000 1000000000
-999999999 999999999
999999999 -999999999

Sample Output 3

3999999996000000001

Watch out for integer overflows.


Score : 300 points

Problem Statement

You are given an integer N.

Find a triple of positive integers h, n and w such that 4/N = 1/h + 1/n + 1/w.

If there are multiple solutions, any of them will be accepted.

Constraints

It is guaranteed that, for the given integer N, there exists a solution such that h,n,w \leq 3500.

Inputs

Input is given from Standard Input in the following format:

N

Outputs

Print a triple of positive integers h, n and w that satisfies the condition, in the following format:

h n w

Sample Input 1

2

Sample Output 1

1 2 2

4/2 = 1/1 + 1/2 + 1/2.

Sample Input 2

3485

Sample Output 2

872 1012974 1539173474040

It is allowed to use an integer exceeding 3500 in a solution.

Sample Input 3

4664

Sample Output 3

3498 3498 3498


Score : 200 points

Problem Statement

We have a grid with N rows and M columns of squares. Initially, all the squares are white.

There is a button attached to each row and each column.
When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa.
When a button attached to a column is pressed, the colors of all the squares in that column are inverted.

Takahashi can freely press the buttons any number of times. Determine whether he can have exactly K black squares in the grid.

Constraints

1 \leq N,M \leq 1000

0 \leq K \leq NM

Input

Input is given from Standard Input in the following format:

N M K

Output

If Takahashi can have exactly K black squares in the grid, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

Press the buttons in the order of the first row, the first column.

Sample Input 2

2 2 1

Sample Output 2

No

Sample Input 3

3 5 8

Sample Output 3

Yes

Press the buttons in the order of the first column, third column, second row, fifth column.

Sample Input 4

7 9 20

Sample Output 4

No


Score : 700 points

Problem Statement

We have a grid with H rows and W columns of squares.
We will represent the square at the i-th row from the top and j-th column from the left as (i,\ j).
Also, we will define the distance between the squares (i_1,\ j_1) and (i_2,\ j_2) as |i_1 - i_2| + |j_1 - j_2|.

Snuke is painting each square in red, yellow, green or blue.
Here, for a given positive integer d, he wants to satisfy the following condition:

No two squares with distance exactly d have the same color.

Find a way to paint the squares satisfying the condition.
It can be shown that a solution always exists.

Constraints

2 ≤ H, W ≤ 500

1 ≤ d ≤ H + W - 2

Input

Input is given from Standard Input in the following format:

H W d

Output

Print a way to paint the squares satisfying the condition, in the following format. If the square (i,\ j) is painted in red, yellow, green or blue, c_{ij} should be R, Y, G or B, respectively.

c_{11}c_{12}...c_{1W}
:
c_{H1}c_{H2}...c_{HW}

Sample Input 1

2 2 1

Sample Output 1

RY
GR

There are four pairs of squares with distance exactly 1.
As shown below, no two such squares have the same color.

(1,\ 1), (1,\ 2) : R, Y

(1,\ 2), (2,\ 2) : Y, R

(2,\ 2), (2,\ 1) : R, G

(2,\ 1), (1,\ 1) : G, R

Sample Input 2

2 3 2

Sample Output 2

RYB
RGB

There are six pairs of squares with distance exactly 2.
As shown below, no two such squares have the same color.

(1,\ 1) , (1,\ 3) : R , B

(1,\ 3) , (2,\ 2) : B , G

(2,\ 2) , (1,\ 1) : G , R

(2,\ 1) , (2,\ 3) : R , B

(2,\ 3) , (1,\ 2) : B , Y

(1,\ 2) , (2,\ 1) : Y , R


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

sum = 0
x.each do |x|
  if x < (x - K).abs
    sum += 2 * x
  else
    sum += (x - K).abs * 2
  end
end
puts sum

Score : 200 points

Problem Statement

There are N balls in the xy-plane. The coordinates of the i-th of them is (x_i, i).
Thus, we have one ball on each of the N lines y = 1, y = 2, ..., y = N.

In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B.
Then, he placed the i-th type-A robot at coordinates (0, i), and the i-th type-B robot at coordinates (K, i).
Thus, now we have one type-A robot and one type-B robot on each of the N lines y = 1, y = 2, ..., y = N.

When activated, each type of robot will operate as follows.

When a type-A robot is activated at coordinates (0, a), it will move to the position of the ball on the line y = a, collect the ball, move back to its original position (0, a) and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

When a type-B robot is activated at coordinates (K, b), it will move to the position of the ball on the line y = b, collect the ball, move back to its original position (K, b) and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

Snuke will activate some of the 2N robots to collect all of the balls. Find the minimum possible total distance covered by robots.

Constraints

1 \leq N \leq 100

1 \leq K \leq 100

0 < x_i < K

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N
K
x_1 x_2 ... x_N

Outputs

Print the minimum possible total distance covered by robots.

Sample Input 1

1
10
2

Sample Output 1

4

There are just one ball, one type-A robot and one type-B robot.

If the type-A robot is used to collect the ball, the distance from the robot to the ball is 2, and the distance from the ball to the original position of the robot is also 2, for a total distance of 4.

Similarly, if the type-B robot is used, the total distance covered will be 16.

Thus, the total distance covered will be minimized when the type-A robot is used. The output should be 4.

Sample Input 2

2
9
3 6

Sample Output 2

12

The total distance covered will be minimized when the first ball is collected by the type-A robot, and the second ball by the type-B robot.

Sample Input 3

5
20
11 12 9 17 12

Sample Output 3

74


=begin
－－－－－－－－－－－－－－
A = 100*A 水
B = 100*B 水
C,D = １回の投入可能砂糖量
E = 100(g)あたりに溶かすことのできる砂糖量
F = ビーカー許容量(水 + 砂糖 = 総質量)
sugar = F 質量内でできる砂糖の質量を格納(Ci + Dj を組み合わせてできる質量の列挙)
water = F 質量内でできる水の質量を格納(100Ai + 100Bjの組み合わせでできる質量の列挙)
sum = water[i]とsugar[j]の総質量
pos = water[i] に溶かせる砂糖量
con = sugar[j]*100 / (sugar[j] + water[i])  の砂糖濃度(%)
ans = 答え
－－－－－－－－－－－－－－
=end

A,B,C,D,E,F = gets.split.map(&:to_i);

tmp = {};
tmp[:waters] = [];
(0..30).each{|i|
  (0..30).each{|j|
    x = (100*A*i) + (100*B*j);
    tmp[:waters] << x if x <= F;
  }
}
tmp[:waters].sort!.uniq!;

tmp[:sugars] = []
(0..30).each{|i|
  (0..30).each{|j|
    y = C * i + D * j;
    tmp[:sugars] << y if y <= F;
  }
}
tmp[:sugars].sort!.uniq!;

sum_ans = 0;
sugar_ans = 0;
dif = -1;
con = 0.0;

tmp[:waters].each{|w|
  pos = w / 100 * E;
  tmp[:sugars].each{|s|
    sum = w + s;
    next if pos < s || F < sum

    con = (s*100) / (s + w).to_f;
    if dif < con
      sum_ans = sum;
      sugar_ans = s;
      dif = con;
    end
  }
}

puts "#{sum_ans} #{sugar_ans}"

Score : 300 points

Problem Statement

Snuke is making sugar water in a beaker.
Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.

Operation 1: Pour 100A grams of water into the beaker.

Operation 2: Pour 100B grams of water into the beaker.

Operation 3: Put C grams of sugar into the beaker.

Operation 4: Put D grams of sugar into the beaker.

In our experimental environment, E grams of sugar can dissolve into 100 grams of water.

Snuke will make sugar water with the highest possible density.

The beaker can contain at most F grams of substances (water and sugar combined), and there must not be any undissolved sugar in the beaker.
Find the mass of the sugar water Snuke will make, and the mass of sugar dissolved in it.
If there is more than one candidate, any of them will be accepted.

We remind you that the sugar water that contains a grams of water and b grams of sugar is \frac{100b}{a + b} percent.
Also, in this problem, pure water that does not contain any sugar is regarded as 0 percent density sugar water.

Constraints

1 \leq A < B \leq 30

1 \leq C < D \leq 30

1 \leq E \leq 100

100A \leq F \leq 3 000

A, B, C, D, E and F are all integers.

Inputs

Input is given from Standard Input in the following format:

A B C D E F

Outputs

Print two integers separated by a space.
The first integer should be the mass of the desired sugar water, and the second should be the mass of the sugar dissolved in it.

Sample Input 1

1 2 10 20 15 200

Sample Output 1

110 10

In this environment, 15 grams of sugar can dissolve into 100 grams of water, and the beaker can contain at most 200 grams of substances.

We can make 110 grams of sugar water by performing Operation 1 once and Operation 3 once.
It is not possible to make sugar water with higher density.
For example, the following sequences of operations are infeasible:

If we perform Operation 1 once and Operation 4 once, there will be undissolved sugar in the beaker.

If we perform Operation 2 once and Operation 3 three times, the mass of substances in the beaker will exceed 200 grams.

Sample Input 2

1 2 1 2 100 1000

Sample Output 2

200 100

There are other acceptable outputs, such as:

400 200

However, the output below is not acceptable:

300 150

This is because, in order to make 300 grams of sugar water containing 150 grams of sugar, we need to pour exactly 150 grams of water into the beaker, which is impossible.

Sample Input 3

17 19 22 26 55 2802

Sample Output 3

2634 934


a = gets.chomp.split(//)
puts a.include?("9") ? "Yes" : "No"

Score : 100 points

Problem Statement

It is September 9 in Japan now.

You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N?

Constraints

10≤N≤99

Input

Input is given from Standard Input in the following format:

N

Output

If 9 is contained in the decimal notation of N, print Yes; if not, print No.

Sample Input 1

29

Sample Output 1

Yes

The one's digit of 29 is 9.

Sample Input 2

72

Sample Output 2

No

72 does not contain 9.

Sample Input 3

91

Sample Output 3

Yes


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

dp = Array.new(n+1).map{Array.new(n+1,10**9)}
m.times do
    a,b,c = gets.split.map(&:to_i)
    dp[a][b] = c
    dp[b][a] = c
end

1.upto(n) do |k|
    1.upto(n) do |s|
        1.upto(n) do |f|
            if dp[s][f] > dp[s][k] + dp[k][f]
                dp[s][f] = dp[s][k] + dp[k][f]
            end
        end
    end
end

ans = 10**9
r.permutation do |arr|
    count = 0
    (R-1).times do |i|
        count += dp[arr[i]][arr[i+1]]
    end
    ans = count if ans > count
end

puts ans

Score : 400 points

Problem Statement

There are N towns in the State of Atcoder, connected by M bidirectional roads.

The i-th road connects Town A_i and B_i and has a length of C_i.

Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in this order).

She will fly to the first town she visits, and fly back from the last town she visits, but for the rest of the trip she will have to travel by road.

If she visits the towns in the order that minimizes the distance traveled by road, what will that distance be?

Constraints

2≤N≤200

1≤M≤N×(N-1)/2

2≤R≤min(8,N) (min(8,N) is the smaller of 8 and N.)

r_i≠r_j (i≠j)

1≤A_i,B_i≤N, A_i≠B_i

(A_i,B_i)≠(A_j,B_j),(A_i,B_i)≠(B_j,A_j) (i≠j)

1≤C_i≤100000

Every town can be reached from every town by road.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M

Output

Print the distance traveled by road if Joisino visits the towns in the order that minimizes it.

Sample Input 1

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

Sample Output 1

2

For example, if she visits the towns in the order of 1, 2, 3, the distance traveled will be 2, which is the minimum possible.

Sample Input 2

3 3 2
1 3
2 3 2
1 3 6
1 2 2

Sample Output 2

4

The shortest distance between Towns 1 and 3 is 4. Thus, whether she visits Town 1 or 3 first, the distance traveled will be 4.

Sample Input 3

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

Sample Output 3

3


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

res = 0
if x > t
  res = x -t
end

puts res

Score : 100 points

Problem Statement

We have a sandglass that runs for X seconds. The sand drops from the upper bulb at a rate of 1 gram per second. That is, the upper bulb initially contains X grams of sand.

How many grams of sand will the upper bulb contains after t seconds?

Constraints

1≤X≤10^9

1≤t≤10^9

X and t are integers.

Input

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

X t

Output

Print the number of sand in the upper bulb after t second.

Sample Input 1

100 17

Sample Output 1

83

17 out of the initial 100 grams of sand will be consumed, resulting in 83 grams.

Sample Input 2

48 58

Sample Output 2

0

All 48 grams of sand will be gone, resulting in 0 grams.

Sample Input 3

1000000000 1000000000

Sample Output 3

0


ss = gets.chomp.split('')

ss.select!.with_index(1) { |s, i| i.odd? }
puts ss.join

Score : 200 points

Problem Statement

You are given a string s consisting of lowercase English letters. Extract all the characters in the odd-indexed positions and print the string obtained by concatenating them. Here, the leftmost character is assigned the index 1.

Constraints

Each character in s is a lowercase English letter.

1≤|s|≤10^5

Input

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

s

Output

Print the string obtained by concatenating all the characters in the odd-numbered positions.

Sample Input 1

atcoder

Sample Output 1

acdr

Extract the first character a, the third character c, the fifth character d and the seventh character r to obtain acdr.

Sample Input 2

aaaa

Sample Output 2

aa

Sample Input 3

z

Sample Output 3

z

Sample Input 4

fukuokayamaguchi

Sample Output 4

fkoaaauh


io = STDIN
n=io.gets.to_i
a=io.gets.split.map(&:to_i)
hash={}
hash.default=0
a.each do |aa|
  hash[aa]+=1
end
ans=0
(1..10**5).each_cons(3) do |x,y,z|
  ans=[ans,hash[x]+hash[y]+hash[z]].max
end
puts ans

Score : 300 points

Problem Statement

You are given an integer sequence of length N, a_1,a_2,...,a_N.

For each 1≤i≤N, you have three choices: add 1 to a_i, subtract 1 from a_i or do nothing.

After these operations, you select an integer X and count the number of i such that a_i=X.

Maximize this count by making optimal choices.

Constraints

1≤N≤10^5

0≤a_i<10^5 (1≤i≤N)

a_i is an integer.

Input

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

N
a_1 a_2 .. a_N

Output

Print the maximum possible number of i such that a_i=X.

Sample Input 1

7
3 1 4 1 5 9 2

Sample Output 1

4

For example, turn the sequence into 2,2,3,2,6,9,2 and select X=2 to obtain 4, the maximum possible count.

Sample Input 2

10
0 1 2 3 4 5 6 7 8 9

Sample Output 2

3

Sample Input 3

1
99999

Sample Output 3

1


q, h, s, d = gets.chomp.split(' ').map(&:to_i)
n = gets.chomp.to_i

min1 = [8 * q, 4 * h, 2 * s, d].min
min2 = [8 * q, 4 * h, 2 * s].min

if min1 == min2 || n % 2 == 0
  puts n * min1 / 2
else
  puts n / 2 * d + min2 / 2
end

Score : 300 points

Problem Statement

You've come to your favorite store Infinitesco to buy some ice tea.

The store sells ice tea in bottles of different volumes at different costs.
Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen.
The store has an infinite supply of bottles of each type.

You want to buy exactly N liters of ice tea. How many yen do you have to spend?

Constraints

1 \leq Q, H, S, D \leq 10^8

1 \leq N \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

Q H S D
N

Output

Print the smallest number of yen you have to spend to buy exactly N liters of ice tea.

Sample Input 1

20 30 70 90
3

Sample Output 1

150

Buy one 2-liter bottle and two 0.5-liter bottles. You'll get 3 liters for 90 + 30 + 30 = 150 yen.

Sample Input 2

10000 1000 100 10
1

Sample Output 2

100

Even though a 2-liter bottle costs just 10 yen, you need only 1 liter.
Thus, you have to buy a 1-liter bottle for 100 yen.

Sample Input 3

10 100 1000 10000
1

Sample Output 3

40

Now it's better to buy four 0.25-liter bottles for 10 + 10 + 10 + 10 = 40 yen.

Sample Input 4

12345678 87654321 12345678 87654321
123456789

Sample Output 4

1524157763907942


q, h, s, d = gets.chomp.split(' ').map(&:to_i)
n = gets.chomp.to_i

min1 = [8 * q, 4 * h, 2 * s, d].min
min2 = [8 * q, 4 * h, 2 * s].min

if min1 == min2 || n % 2 == 0
  puts n * (min1 / 2)
else
  puts n / 2 * d + min2 / 2
end


x, a, b = gets.split.map(&:to_i)
puts (x-a).abs < (x-b).abs ? 'A' : 'B'

Score : 100 points

Problem Statement

Snuke lives at position x on a number line.
On this line, there are two stores A and B, respectively at position a and b, that offer food for delivery.

Snuke decided to get food delivery from the closer of stores A and B.
Find out which store is closer to Snuke's residence.

Here, the distance between two points s and t on a number line is represented by |s-t|.

Constraints

1 \leq x \leq 1000

1 \leq a \leq 1000

1 \leq b \leq 1000

x, a and b are pairwise distinct.

The distances between Snuke's residence and stores A and B are different.

Input

Input is given from Standard Input in the following format:

x a b

Output

If store A is closer, print A; if store B is closer, print B.

Sample Input 1

5 2 7

Sample Output 1

B

The distances between Snuke's residence and stores A and B are 3 and 2, respectively.
Since store B is closer, print B.

Sample Input 2

1 999 1000

Sample Output 2

A


n = gets.to_i
as = gets.split
  .each_with_object(Hash.new(0)) { |a, h| h[a.to_i] += 1 }
  .select { |_, v| v >= 2 }

ans = 0
prev = 0

as.keys.sort.each do |k|
  v = as[k]
  s = v >= 4 ? [prev * k, k ** 2].max : prev * k

  ans = s if s >= ans
  prev = k
end

puts ans

Score : 300 points

Problem Statement

We have N sticks with negligible thickness.
The length of the i-th stick is A_i.

Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides.
Find the maximum possible area of the rectangle.

Constraints

4 \leq N \leq 10^5

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible area of the rectangle.
If no rectangle can be formed, print 0.

Sample Input 1

6
3 1 2 4 2 1

Sample Output 1

2

1 \times 2 rectangle can be formed.

Sample Input 2

4
1 2 3 4

Sample Output 2

0

No rectangle can be formed.

Sample Input 3

10
3 3 3 3 4 4 4 5 5 5

Sample Output 3

20