n = gets().to_i
aibi = []
n.times{|i|
	aibi[i] = gets().split(' ').map(&:to_i)
}

aibi.sort_by!{|a|
	a[1]
}

tm = 0
result = true
aibi.each{|a|
	ai = a[0]
	bi = a[1]

	tm += ai
	if tm > bi
		result = false
		break
	end
}

puts (result ? "Yes" : "No")

Score: 400 points

Problem Statement

Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs.

Let the current time be time 0. Kizahashi has N jobs numbered 1 to N.

It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B_i, and he must complete the job before or at this time.

Kizahashi cannot work on two or more jobs simultaneously, but when he completes a job, he can start working on another immediately.

Can Kizahashi complete all the jobs in time? If he can, print Yes; if he cannot, print No.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
.
.
.
A_N B_N

Output

If Kizahashi can complete all the jobs in time, print Yes; if he cannot, print No.

Sample Input 1

5
2 4
1 9
1 8
4 9
3 12

Sample Output 1

Yes

He can complete all the jobs in time by, for example, doing them in the following order:

Do Job 2 from time 0 to 1.

Do Job 1 from time 1 to 3.

Do Job 4 from time 3 to 7.

Do Job 3 from time 7 to 8.

Do Job 5 from time 8 to 11.

Note that it is fine to complete Job 3 exactly at the deadline, time 8.

Sample Input 2

3
334 1000
334 1000
334 1000

Sample Output 2

No

He cannot complete all the jobs in time, no matter what order he does them in.

Sample Input 3

30
384 8895
1725 9791
170 1024
4 11105
2 6
578 1815
702 3352
143 5141
1420 6980
24 1602
849 999
76 7586
85 5570
444 4991
719 11090
470 10708
1137 4547
455 9003
110 9901
15 8578
368 3692
104 1286
3 4
366 12143
7 6649
610 2374
152 7324
4 7042
292 11386
334 5720

Sample Output 3

Yes


_, x = gets.split.map(&:to_i)
ls = gets.split.map(&:to_i)

cum_sum = ls.inject([0]) { |a, n| a << a.last.to_i + n }
p count = cum_sum.take_while { |n| n <= x }.size

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

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.

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, x = gets.split.map(&:to_i)
l = gets.split.map(&:to_i)
cnt = 1
d = 0
(0...l.size).each do |i|
    d += l[i]
    if d <= x
        cnt += 1
    end
end
puts cnt


n,x = gets.split.map(&:to_i)
ls = gets.split.map(&:to_i)
d = 0
cnt = 1
ls.each{|l|
  d += l
  cnt += 1 if x >= d
}
puts cnt


Score : 300 points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

1 \leq W,H \leq 10^9

0\leq x\leq W

0\leq y\leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

W H x y

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line x=1 gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1


p,q,r=gets.chomp.split(" ").map(&:to_i)

puts [p+q, r+p, q+r].min

Score : 100 points

Problem Statement

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

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

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

What is the minimum possible sum of the flight times?

Constraints

1 \leq P,Q,R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

P Q R

Output

Print the minimum possible sum of the flight times.

Sample Input 1

1 3 4

Sample Output 1

4

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

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

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

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

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

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

The minimum of these is 4 hours.

Sample Input 2

3 2 3

Sample Output 2

5


n, m = gets.chomp.split.map(&:to_i)
a = []
m.times do |i|
  a[i] = gets.chomp.to_i
end

sum = Array.new(n+1, -2)
sum[0] = 1
a.each do |i|
  sum[i] = -1
end

1.upto(n) do |i|
  if i == 1
    if sum[i] == -1
      sum[i] = 0
    else
      sum[i] = 1
    end
  else
    if sum[i] == -1
      sum[i] = 0
    elsif a.include?(i-1)
      sum[i] = sum[i-2]
    else
      sum[i] = sum[i-2] + sum[i-1]
    end
  end
  sum[i] %= 1000000007
end
p sum[n] % 1000000007

Score : 300 points

Problem Statement

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

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

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

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

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

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

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

Sample Input 1

6 1
3

Sample Output 1

4

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

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

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

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

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

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

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

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


n, m = gets.strip.split.map(&:to_i)
a = readlines.map {|line| line.strip.to_i }.sort

MOD = 10**9+7
#p n
#p a
dp=[0]*(n+1)

a.each do |hall|
  dp[hall] = -1
end

dp[0]=1
n.times do |index|
  next if dp[index]==-1

  if (0..n)===(index+1) && dp[index+1]>=0
    dp[index+1]=(dp[index]+dp[index+1])%MOD
  end
  if (0..n)===(index+2) && dp[index+2]>=0
    dp[index+2]=(dp[index]+dp[index+2])%MOD
  end
end

 p dp[n]%MOD


N,M = gets.chomp.split(" ").map(&:to_i)
arr = readlines.map{|n| n.chomp.to_i}
# p arr

class Integer
    def combination(k)
      return 1 if k.zero?

      (self - k + 1..self).inject(:*) / k.factorial
    end

    def permutation(k)
      return 1 if k.zero?

      (self - k + 1..self).inject(:*)
    end

    def factorial
      return 1 if self.zero?

      (1..self).inject(:*)
    end
end

def step_sum(step)
    sum = 0
    return 1 if step == 0
    step.times do |i|
        one = i
        two = step - i
        break if step/2 > two
        sum += two.combination one
    end
    return sum
end

prev = 0
ans = 1
arr << N+1
arr.each do |cur|
    if prev == cur
        ans = 0
        break
    end
    step = cur-1-prev

    ans*=step_sum(step)
    # p [step, ans]
    prev = cur+1
end

puts ans % 1000000007


require 'pp'

n, m = gets.chomp!.split(" ").map!(&:to_i)
a = Array.new(0, n + 2)

before = -1
z = false

memo_a = {}

a[0]= 0
1.upto(m) do |i|
    a[i] = gets.chomp!.to_i
    memo_a[a[i]] = a[i]
    if before + 1 == a[i]
        z = true
        break
    end
    before = a[i]
end
a[m+1]=n+1

tree = {
    1 => 1,
    2 => 2
}

if z
    puts 0
else
    dan_max = 0
    dan = a.each_cons(2).map do |s, e|
        d = (e-s)-2
        if d > dan_max
            dan_max = d
        end
        d
    end

    if dan_max >= 3
        3.upto(dan_max) do |x|
            tree[x] = tree[x-1] + tree[x-2]
        end
    end

    #pp tree
    #pp dan

    sum = (dan.inject(1) {|sum, x|
        if x < 0
            sum
        else
            sum *= tree[x]
        end
    })

    puts sum % 1_000_000_007
end


Score : 600 points

Problem Statement

There is an arithmetic progression with L terms: s_0, s_1, s_2, ... , s_{L-1}.

The initial term is A, and the common difference is B. That is, s_i = A + B \times i holds.

Consider the integer obtained by concatenating the terms written in base ten without leading zeros. For example, the sequence 3, 7, 11, 15, 19 would be concatenated into 37111519. What is the remainder when that integer is divided by M?

Constraints

All values in input are integers.

1 \leq L, A, B < 10^{18}

2 \leq M \leq 10^9

All terms in the arithmetic progression are less than 10^{18}.

Input

Input is given from Standard Input in the following format:

L A B M

Output

Print the remainder when the integer obtained by concatenating the terms is divided by M.

Sample Input 1

5 3 4 10007

Sample Output 1

5563

Our arithmetic progression is 3, 7, 11, 15, 19, so the answer is 37111519 mod 10007, that is, 5563.

Sample Input 2

4 8 1 1000000

Sample Output 2

891011

Sample Input 3

107 10000000000007 1000000000000007 998244353

Sample Output 3

39122908


s = gets.chomp.split("")
count = Hash.new(0)

s.each do |elem|
    count[elem] += 1
end

if s.length < 8
    puts "YES"
elsif 15 - s.length + count["o"] >= 8
    puts "YES"
else
    puts "NO"
end

Score : 200 points

Problem Statement

Takahashi is competing in a sumo tournament.
The tournament lasts for 15 days, during which he performs in one match per day.
If he wins 8 or more matches, he can also participate in the next tournament.

The matches for the first k days have finished.
You are given the results of Takahashi's matches as a string S consisting of o and x.
If the i-th character in S is o, it means that Takahashi won the match on the i-th day; if that character is x, it means that Takahashi lost the match on the i-th day.

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO if there is no such possibility.

Constraints

1 \leq k \leq 15

S is a string of length k consisting of o and x.

Input

Input is given from Standard Input in the following format:

S

Output

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO otherwise.

Sample Input 1

oxoxoxoxoxoxox

Sample Output 1

YES

Takahashi has 7 wins and 7 losses before the last match. If he wins that match, he will have 8 wins.

Sample Input 2

xxxxxxxx

Sample Output 2

NO


# util functions

# debug
$debugFlag = ( ARGV[0] != nil )
p "==== DEBUG MODE ====" if $debugFlag

def pd(str)
  p str if $debugFlag
end

# input
inputs = []
lc = 0
nn = 0
scores = []
edge = []
while l = $stdin.gets do
  if lc == 0
    nn = l.chomp.to_i
    initedgev = [0]*nn
    nn.times do
      edge << initedgev
    end
  elsif lc < nn
    tmp_edge = l.chomp.split(" ").map(&:to_i)
    tmp_a = tmp_edge[0] - 1
    tmp_b = tmp_edge[1] - 1
    edge[tmp_a][tmp_b] = 1
    edge[tmp_b][tmp_a] = 1
  else # lc == nn
    scores = l.chomp.split(" ").map(&:to_i)
  end
  lc += 1
end
scores = scores.sort.reverse

pd nn
edge.each do |x_i|
  pd x_i
end
pd scores
pd ans_val = scores[1..-1].inject(:+)

# input check
if $debugFlag
  p "--- INPUT (begin) ---"
  inputs.each do |l_i|
    p l_i
  end
  p "--- INPUT (end) ---"
  print "\n"
end

# body
if $debugFlag
end

ans = []
queue = [0]
while queue != []
  print "queue: " if $debugFlag
  pd queue
  node = queue.shift
  ans[node] = scores.shift
  break if node == nn - 1
  for i in node+1..nn-1
    queue.push(i) if edge[node][i] == 1
  end
end
pd ans

str = ""
ans.each do |a_i|
  str += "#{a_i} "
end

puts ans_val
puts str.chomp

Score : 500 points

Problem Statement

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

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

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

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

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

Constraints

1 \leq N \leq 10000

1 \leq a_i,b_i \leq N

1 \leq c_i \leq 10^5

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

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

Output

Use the following format:

M
d_1 \ldots d_N

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

Sample Input 1

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

Sample Output 1

10
1 2 3 4 5

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

Sample Input 2

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

Sample Output 2

197
59 26 3141 59 53

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


a,p=gets.split.map &:to_i
puts (a*3+p)/2

Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

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

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

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

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

Sample Input 1

1 3

Sample Output 1

3

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

Sample Input 2

0 1

Sample Output 2

0

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

Sample Input 3

32 21

Sample Output 3

58


A,P = gets.split.map(&:to_i)
puts (A*3+P)/2


# util functions

# debug
$debugFlag = ( ARGV[0] != nil )
p "==== DEBUG MODE ====" if $debugFlag

def pd(str)
  p str if $debugFlag
end

# input
inputs = []
lc = 0
while l = $stdin.gets do
  if false
    inputs << l.chomp.split(" ").map(&:to_s)
  else
    inputs << l.chomp.split(" ").map(&:to_i)
  end
  lc += 1
end

# input check
if $debugFlag
  p "--- INPUT (begin) ---"
  inputs.each do |l_i|
    p l_i
  end
  p "--- INPUT (end) ---"
  print "\n"
end

aa = inputs[0][0]
pp = inputs[0][1]

# body
if $debugFlag
  p aa
  p pp
end

puts (aa*3 + pp)/2


n = gets.to_i
sps = n.times.map { |i| [(i + 1), *gets.split] }

sps.sort_by! { |x| [x[1], -x[2].to_i] }.each do |i, _k, _v|
  puts i
end

Score : 200 points

Problem Statement

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

You want to introduce the restaurants in the following order:

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

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

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

Constraints

1 ≤ N ≤ 100

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

0 ≤ P_i ≤ 100

P_i is an integer.

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

Input

Input is given from Standard Input in the following format:

N
S_1 P_1
:
S_N P_N

Output

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

Sample Input 1

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

Sample Output 1

3
4
6
1
5
2

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

Sample Input 2

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

Sample Output 2

10
9
8
7
6
5
4
3
2
1


puts (1..gets.to_i)
  .map {|i| gets.chomp.split(" ") << i}
  .sort_by {|a, b| [a, -b.to_i]}
  .map(&:last)


N = gets.to_i
S, P = [], []
(0..N-1).each do |i|
  S[i], P[i] = gets.split.map(&:to_s)
end
hash = []
(0..N-1).each do |i|
  hash.push([i+1, S[i], P[i]])
end
hash.sort{|a, b| (a[1] <=> b[1]).nonzero? || (b[2] <=> a[2])
}.each do|key, valS, valP|
  puts key.to_i
end


n = gets.to_i

rs = []
names = []
n.times do |i|
    name, score = gets.split
    rs.push([name, score.to_i, i+1])
    names.push(name)
end

names.uniq!.sort!

names.each do |name|
    targets = rs.find_all { |i| i[0] == name }
    targets.sort! {|a, b| b[1]  <=> a[1] }
    targets.each {|i| puts i[2] }
end


#N=gets.to_i
#S=gets.chomp
#A=(0...N).map{gets.to_i}
#sum=A.inject(&:+)
#B=gets.split.map(&:to_i)

N=gets.to_i

dict=[]

N.times do |i|
  s,pi=gets.split
  pi=pi.to_i
  dict << [s,-pi,i+1]
end
puts dict.sort.map{|a,b,c| c}


n,m = gets.split.map(&:to_i)
k = []
m.times do |i|
  d,*s = gets.split.map(&:to_i)
  k[i] = s
end
p = gets.split.map(&:to_i)
ans = 0

(0..n).each do |j|
  [*0...n].combination(j) do |num|
  ans += 1 if (0...m).all?{ |i| (k[i] & num).size % 2 == p[i] }
  end
end

puts ans

Score : 300 points

Problem Statement

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

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

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

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

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

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

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

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

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

Sample Input 2

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

Sample Output 2

0

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

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

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

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

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


        solve(switches, idx + 1, conditions)
    end
end

candidates = {}

m.times do |i|
    inp = gets.split.map(&:to_i)
    inp.shift
    $bulbs.push(inp.map { |i| i-1 })
end

$bulbs.each { |i| cnt = [cnt, i.max].max }
switches = Array.new(cnt + 1, 0)

conditions = gets.split.map(&:to_i)
solve(switches, 0, conditions)

puts $res


N, M = gets.split.map(&:to_i)
SWITCH = M.times.map { gets.split.map(&:to_i) }
P = gets.split.map(&:to_i)

def all_on?(rump)
  i = -1

  SWITCH.all? do |_, *s|
    cnt = 0

    s.each do |idx|
      cnt += 1 if rump[idx - 1]
    end

    i += 1
    cnt % 2 == P[i]
  end
end

ans = 0

[false, true].repeated_permutation(N).each do |list|
  ans += 1 if all_on?(list)
end

puts ans


n,m=gets.split.map(&:to_i)
ss = m.times.map{gets.split.map(&:to_i).tap(&:shift).map{|x|x-1}}
ps = gets.split.map(&:to_i)

puts (1<<n).times.select{|s| ss.each_with_index.all?{|ss,i| ss.map{|ss|s[ss]}.inject(0,&:+)%2 == ps[i]}}.size


N,K=gets.split.map &:to_i
V=gets.split.map &:to_i
p 0.upto([N,K].min).map{|n|
  0.upto(n).map{|l|
    r = n - l
    d = [0] + V[0...l] + V[(V.size-r)...V.size]
    d.sort!
    (K-n).times{d.shift if d[0]<0}
    d.inject(:+)
  }.max
}.max

Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.


n = gets.split.map(&:to_i)
je = gets.split.map(&:to_i)
jewel = Array.new(n[0]).map{Array.new(2,0)}
for i in 0..n[0]-1
  jewel[i][0] = je[i]
  jewel[i][1] = i
end
jewel_s = jewel.sort
ans = 10**10
for i in n[0]-n[1]..n[0]
  check = Array.new(n[0],0)
  result1 = 0
  for j in 0..i-1
    check[j] = 1
    result1 += jewel[j][0]
  end
  count = 0
  result2 = 0
  for j in 0..n[0]-1
    break if count >= i-(n[0]-n[1])
    if check[jewel_s[j][1]] == 0 && jewel_s[j][0] < 0
      result2 += jewel_s[j][0]
      count += 1
    end
  end
  ans = result1 + result2 if ans > result1 + result2
  for k in i..n[0]-1
    check[k-i] = 0
    result1 -= jewel[k-i][0]
    check[k] = 1
    result1 += jewel[k][0]
    count = 0
    result2 = 0
    for j in 0..n[0]-1
      break if count >= i-(n[0]-n[1])
      if check[jewel_s[j][1]] == 0 && jewel_s[j][0] < 0
        result2 += jewel_s[j][0]
        count += 1
      end
      ans = result1 + result2 if ans > result1 + result2
    end
  end
end
final = 0
n[0].times{|i| final += jewel[i][0]}
puts final - ans


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

ans = 0

0.upto(k) do |i|
  break if i > n
  0.upto(i) do |r| #右からr
    l = i - r
    tmp = []
    l.times do |x|
      tmp << v[x]
    end
    r.times do |x|
      tmp << v[n-1-x]
    end
    tmp = tmp.sort_by{|e| e}
    (k-i).times do |x|
      if !tmp.empty?
        tmp.shift if tmp[0] < 0
      end
    end
    sum = tmp.inject(:+) if !tmp.empty?
    ans = sum if !sum.nil? && sum > ans
  end
end
puts ans


class Heap
  def initialize(n)
    @nodes = Array.new(n)
    @index = Hash.new
    @size = 0
  end

  def push(x)
    i = @size
    @size += 1
    while i > 0 do
      #親ノードのindex
      t = (i-1)>>1
      # 親より自分が大きいなら、入れ替え不要
      break if @nodes[t] <= x
      # 親より自分が小さい時、入れ替え操作を行う
      @index[@nodes[t]] = i
      @nodes[i] = @nodes[t]
      i = t
    end
    @index[x] = i
    @nodes[i] = x
  end

  def delete(x)
    # 削除したい値のあるindexへ、最新nodeの値を入れる
    current_node_value = @nodes[@size - 1]
    return unless current_node_index = @index.delete(x)
    @size -= 1
    @nodes[current_node_index] = current_node_value
    @index[current_node_value] = current_node_index

    # 大小関係が正されるように、要素を入れ替える
    if x > current_node_value
      # 末端のほうが削除する値よりも小さかった場合は、親ノードへ入れ替えを確認していく
      parent_node_index = (current_node_index - 1) >> 1
      while @nodes[parent_node_index]&.< @nodes[current_node_index] do
        change(parent_node_index, current_node_index)
        current_node_index = parent_node_index
        current_node_value = @nodes[current_node_index]
        parent_node_index = (current_node_index - 1) >> 1
      end
    else
      # 末端のほうが大きかった場合は、子ノードへ入れ替えを確認していく
      # 末端のほうが削除する値よりも小さかった場合は、親ノードへ入れ替えを確認していく
      child_node_index_l = (current_node_index + 1) << 1
      child_node_index_r = child_node_index_l - 1
      child_node_value_l = @nodes[child_node_index_l]
      child_node_value_r = @nodes[child_node_index_r]
      if child_node_value_l&.>(child_node_value_r)
        min_child_info = [child_node_value_r , child_node_index_r]
      else
        min_child_info = [child_node_value_l , child_node_index_l]
      end
      while (min_child_info[0]&.<(current_node_value)) do
        change(current_node_index, min_child_info[1])
        current_node_index = min_child_info[1]
        current_node_value = min_child_info[0]
        child_node_index_l = (current_node_index + 1) << 1
        child_node_index_r = child_node_index_l - 1
        break if child_node_index_r >= @size
        child_node_value_l = @nodes[child_node_index_l]
        child_node_value_r = @nodes[child_node_index_r]
        min_child_info = (child_node_value_l&.>(child_node_value_r)) ? [child_node_value_r , child_node_index_r] : [child_node_value_l , child_node_index_l]
      end
    end
  end

  def top
    @size == 0 ? -1 : @nodes[0]
  end

  private

  def change(index_i, index_j)
    @nodes[index_i], @nodes[index_j] = @nodes[index_j], @nodes[index_i]
    @index[@nodes[index_i]] = index_i
    @index[@nodes[index_j]] = index_j
  end
end

nn, qq = gets.split.map(&:to_i)
events = []
temp = []

t = 0
nn.times do
  temp = gets.split.map(&:to_i)
  next if (t = temp[1] - temp[2]) <= 0

  events.push(
    ((temp[0] - temp[2]) << 32) +
    (2 << 30) +
    temp[2]
  )
  events.push(
    (t << 32) +
    temp[2]
  )
end

1.step(qq, 1) do |i|
  events.push(
    (gets.to_i << 32) +
    (3 << 30) +
    i
  )
end

# '30bit-2bit-30bit'
#  ソートするための区間 - タイプ - indexなどの情報
mask_3 = ((1 << 30) - 1)
mask_4 = ((1 << 18) - 1)

events.sort!

ss = Heap.new(qq)
ans = []

events.each do |event|
  if event[30] == 0
    if event[31] == 1
      ss.push(event & mask_3)
    else
      ss.delete(event & mask_3)
    end
  else
    ans[(event & mask_4)] = ss.top
  end
end

puts ans[1..-1]

Score : 500 points

Problem Statement

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

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

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

Find the distance each of the Q people will walk.

Constraints

All values in input are integers.

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

0 \leq S_i < T_i \leq 10^9

1 \leq X_i \leq 10^9

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

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

2
2
10
-1
13
-1

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

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

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


require 'set'

nn, qq = gets.split.map(&:to_i)
events = []
temp = []
1.step(nn, 1) do |_i|
  temp = gets.split.map(&:to_i)
  events.push([temp[0] - temp[2], 0, temp[2]])
  events.push([temp[1] - temp[2], 1, temp[2]])
end
1.step(qq, 1) do |i|
  events.push([gets.to_i, 2, i])
end
events.sort_by!(&:first)
ss = Set.new
ans = []
count = 0
events.each do |event|
  case event[1]
  when 2
    ss.size.zero? ? (ans[event[2]] = - 1) : (ans[event[2]] = ss.min)
    count += 1
    break if count == qq
  when 0
    ss.add event[2]
  else
    ss.delete event[2]
  end
end

puts ans[1..-1]


a,b = gets.split.map(&:to_i)
if a >= 13
    puts b
elsif a >= 6
    puts b / 2
else
    puts 0
end

Score : 100 points

Problem Statement

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

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

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

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

Sample Input 2

12 100

Sample Output 2

50

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

Sample Input 3

0 100

Sample Output 3

0

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


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

if a >= 13
  puts b

elsif a >= 6 && a <= 12
  puts b/2

elsif a < 5
  puts 0
end


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

if a >= 13
  puts (b)

elsif a >= 6 && a <= 12
  puts (b/2)

elsif a < 5
  puts 0
end

puts b


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

10.times do
  ans_weights << a * c - b
  c = ans_weights.last
end

puts ans_weights

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

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

x_{i+1} = rx_i - D

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

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

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

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

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

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


n,m = gets.split(' ').map(&:to_i)
can_pass = []
m.times do |a|
    l,r = gets.split(' ').map(&:to_i)
    can_pass<< (l..r).to_a
end
exisited = can_pass[0]
if can_pass.length >1
    1.upto(can_pass.length-1) do |a|
        exisited = can_pass[a] & exisited
    end

end
puts exisited.length

Score : 300 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

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

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

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

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

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

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

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

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


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

l = []
r = []
m.times do |i|
  a,b = gets.split.map(&:to_i)
  l << a
  r << b
end

ans = r.min - l.max

puts ans > 0 ? ans - 1 : 0


n, m = gets.split.map(&:to_i)
l = []
r = []
m.times do
  tmp = gets.split.map(&:to_i)
  l.push tmp[0]
  r.push tmp[1]
end

ans = []
if m > 1
  tmp = (l[0]..r[0]).to_a
  m.times { |i| tmp = tmp & (l[i]..r[i]).to_a }
  ans = tmp
else
  ans = (l[0]..r[0]).to_a
end

puts ans.size


N, M = gets.chomp.split.map(&:to_i)
l_max = 1
r_min = N
M.times do
  p, q = gets.chomp.split.map(&:to_i)
  l_max = p if (l_max < p)
  r_min = q if (q < r_min)
end
puts [r_min - l_max + 1, 0].max


n,m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
ope = readlines.map{|line| line.split.map(&:to_i)}
a.sort!
ope.sort!{|e,f| f[1] <=> e[1]}

sum = 0

ope.each do |i|
  if a[0] == nil
      break
  elsif a[0] >= i[1]
    sum += a.inject(:+)
    a = [0]
    break
  end
  i[0].times do
    if a[0] == nil
        break
    elsif a[0] < i[1]
      a.shift
      sum += i[1]
    else
      break
    end
  end
end

if a[0] == nil
    puts sum
else
    puts sum + a.inject(:+)
end

Score : 400 points

Problem Statement

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

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

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

Sample Input 2

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

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

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

Sample Output 4

10000000001

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


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

a.sort!
m.times do
  b, c = gets.split.map(&:to_i)
  count = 0
  (0...b).each do |i|
    if a[i] < c
      count += 1
    end
  end
  a.shift(count)
  n = a.find_index{|v| v > c}
  if n.nil?
    a += [c] * count
  else
    a.insert(n, *([c]*count))
  end
end
puts a.reduce(:+)


n, m = gets.split.map(&:to_i)
cards = gets.split.map(&:to_i)
m.times do
  b, c = gets.split.map(&:to_i)
  cards += Array.new(b, c)
end
puts cards.sort[-n..-1].inject(:+)


n, k = gets.split.map(&:to_i)
s = gets.chomp.chars
n.times do |i|
  s[i].downcase! if k - 1 == i
end
puts s.join

Score : 100 points

Problem Statement

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

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

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

Input

Input is given from Standard Input in the following format:

N K
S

Output

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

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


S = gets.chomp
MM = ["01","02","03","04","05","06","07","08","09","10","11","12"]
pre = MM.include?(S.slice(0..1))
suf = MM.include?(S.slice(2..3))
if pre && suf
  puts "AMBIGUOUS"
elsif !pre && suf
  puts "YYMM"
elsif pre && !suf
  puts "MMYY"
else
  puts "NA"
end

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


n = gets.split("").map(&:to_i)
count = 0
if n[0]*10+n[1] == 0
elsif n[0]*10+n[1] > 12
else
  count += 1
end
if n[2]*10+n[3] == 0
elsif n[2]*10+n[3] > 12
else
  count += 2
end

if count == 0
  puts "NA"
elsif count == 1
  puts "MMYY"
elsif count == 2
  puts "YYMM"
elsif count == 3
  puts "AMBIGUOUS"
end


N, K = gets.split.map &:to_f
dp = Array.new(K+1){0}

1.upto(N) do |i|
  dp[[i, K].min] += 1.0 / N
end

1000.times do
  nex = Array.new(K+1){0}
  nex[K] = dp[K]
  1.upto(K-1) do |i|
    nex[[2*i, K].min] += dp[i] * 0.5
  end
  dp = nex
end

p dp[K]

Score : 300 points

Problem Statement

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

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

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

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

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

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

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

Sample Input 1

3 10

Sample Output 1

0.145833333333

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

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

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

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

Sample Input 2

100000 5

Sample Output 2

0.999973749998


#!/usr/bin/ruby

require 'pp'

N = gets.chomp.to_i

queue = []
table = [nil]*(N)
1.upto(N-1){|e|

u,v,w = gets.chomp.split(" ").map(&:to_i)
   if table[u] == nil
        table[u] = {color: -1, neibours: [] }
   end

   if table[v] == nil
        table[v] = {color: -1, neibours: [] }
   end

   table[u][:neibours] << [v,w]
   table[v][:neibours] << [u,w]

   if e == 1
      queue << u
      table[u][:color] = 0
   end
}

while !queue.empty? do
    i = queue.shift
    c = table[i][:color]
    table[i][:neibours].each{|node|
       if table[ node[0] ][:color] == -1
          table[ node[0] ][:color] = (node[1]%2 == 0 ? c : c^1)
          queue << node[0]
       end
    }
end

1.upto(N){|n|
  puts table[n][:color]
}

Score : 400 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

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

Output

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

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

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

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

Sample Output 2

1
0
1
0
1


n = gets.to_i
v=$<.map{|s|s.split.map &:to_i}.sort.map{|m|[m[0]-1,m[1]-1,m[2]]}
@p = Array.new(n,nil)
@r = Array.new(n,0)
@w = Array.new(n,0)

# 検索
def find(x)
    if @p[x] == nil
        return x
    else
        y = find(@p[x])
        @w[x] += @w[@p[x]]
        @p[x] = y
        return y
    end
end

# 併合
def union(x, y, w)
    rx = find(x)
    ry = find(y)
    @p[rx] = ry
    @w[rx] = w - @w[x] + @w[y]
end

v.each do |e|
    union(e[1],e[0],e[2])
end

(0...n/2).each{|t| find(t)}

puts @w.map{|m| m%2}


N = gets.to_i

v_table = {}
(N - 1).times{
	u, v, w = gets.strip.split(/ /).collect(&:to_i)
	if table = v_table[u]
		table[v] = w
	else
		v_table[u] = { v => w }
	end
	if table = v_table[v]
		table[u] = w
	else
		v_table[v] = { u => w }
	end
}

def color(v_table)
	queue = [1]
	col_table = { 1 => 0 }
	while cur = queue.pop
		col = col_table[cur]
		v_table[cur].each{|v, w|
			if col_table[v] == nil
				if w % 2 == 0
					col_table[v] = col
				else
					col_table[v] = 1 - col
				end
				queue << v
			end
		}
	end
	col_table
end

col_table = color(v_table)

(1..N).each{|n|
	puts col_table[n]
}


n,m=gets.split.map(&:to_i)
l=[nil]
n.times do
  l << []
end
m.times do
  x,y,z=gets.split.map(&:to_i)
  l[x] << y
  l[y] << x
end
v=[0]*(n+1)
c=0
1.upto(n) do |i|
  next if v[i]==1
  c+=1
  s=[i]
  while s!=[]
    z=[]
    s.each do |j|
      l[j].each do |lj|
        if v[lj]==0
          v[lj]=1
          z << lj
        end
      end
    end
    s=z.dup
  end
end
puts c

Score : 500 points

Problem Statement

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

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

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

You know the following facts:

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

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

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3 1
1 2 1

Sample Output 1

2

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

Sample Input 2

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

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


class UnionFindTree
  class Node
    attr_accessor :parent, :rank

    def initialize(n)
      @parent = n
      @rank = 0
    end
  end

  attr_reader :nodes
  private :nodes

  def initialize(n)
    @nodes = Array.new(n) { |i| Node.new(i) }
  end

  def find(x)
    if nodes[x].parent == x
      x
    else
      # shortcut
      nodes[x].parent = find(nodes[x].parent)
    end
  end

  alias root find

  # whether in the same group
  def same?(a, b)
    find(a) == find(b)
  end

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

    # shortcut
    a, b = b, a if nodes[a].rank < nodes[b].rank
    nodes[a].rank += 1 if nodes[a].rank == nodes[b].rank

    nodes[b].parent = a
  end

  alias merge unite

  def roots
    nodes.map(&:parent)
  end
end

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

uft = UnionFindTree.new(n)

m.times do
  x, y, _ = gets.split.map(&:to_i)
  uft.merge(x - 1, y - 1)
end

require 'set'
p uft.roots.to_set.size


Score : 100 points

Problem Statement

Snuke has N integers: 1,2,\ldots,N.
He will choose K of them and give those to Takahashi.

How many ways are there to choose K consecutive integers?

Constraints

All values in input are integers.

1 \leq K \leq N \leq 50

Input

Input is given from Standard Input in the following format:

N K

Output

Print the answer.

Sample Input 1

3 2

Sample Output 1

2

There are two ways to choose two consecutive integers: (1,2) and (2,3).

Sample Input 2

13 3

Sample Output 2

11


r, g, b, n = gets.split.map(&:to_i)
ans = 0
0.step(n, r) do |i|
  0.step(n, g) do |j|
    next if n < i + j
    ans += 1 if (n - (i + j)) % b == 0
  end
end
puts ans


N = readline.to_i
last_a = 0
first_b = 0
count = 0
N.times do |i|
  s = readline.chomp
  first_b += 1 if s[0] == 'B'
  last_a += 1 if s[-1] == 'A'
  s.each_char.with_index do |c,i|
    count += 1 if c == 'A' and s[i+1] == 'B'
  end
end

n = [last_a,first_b].min
n -= 1 if n == N
puts count + n

Score : 400 points

Problem Statement

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

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

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

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

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


N = gets.to_i
s_list = []

start_b = 0
end_a = 0
both = 0

count = 0
N.times{
	s = gets.strip
	s_list << s
	s.scan(/AB/){
		count += 1
	}
	if s[0] == "B"
		if s[-1] == "A"
			both += 1
		else
			start_b += 1
		end
	elsif s[-1] == "A"
		end_a += 1
	end
}

if both >= 1
	count += (both - 1)
	if start_b > 0
		count += 1
		start_b -= 1
	end
	if end_a > 0
		count += 1
		end_a -= 1
	end
end

count += [start_b, end_a].min

puts count


N=$<.read.to_i

ret = 0
t = 1
d,m = (N-t).divmod(t)
while t < d
  if m == 0
    ret += d
  end
  t += 1
  d,m = (N-t).divmod(t)
end

p ret

Score : 500 points

Problem Statement

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

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

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

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

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


N = gets.to_i
ans = 0
1.upto((N**0.5).to_i) do |i|
  m = N/i - 1
  ans += m if m * i + i == N
  #p [N,i,m,N/m,N%m]
end
p ans


A, B, T = gets.split(' ').map(&:to_i)
puts (T / A) * B

Score : 100 points

Problem Statement

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

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

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

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

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

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

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


a,b,t = gets.split(' ').map{|a|a.to_i}
p (t.div(a)) * b


n=gets.to_i
juels=gets.split.map(&:to_i)
costs=gets.split.map(&:to_i)
costTotal=0
n.times do |index|
  cost = juels[index] - costs[index]
  costTotal += cost > 0 ? cost : 0
end
puts costTotal

Score : 200 points

Problem Statement

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

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

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

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

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

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

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


N,*A = `dd`.split.map &:to_i
B = A.map(&:abs)
p B.reduce(:+) - (A.count{ |a| a < 0 } % 2 == 0 ? 0 : B.min*2)

Score : 400 points

Problem Statement

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

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

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^5

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

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

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

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

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

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

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

Sample Output 3

10000000000

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


gets
s = gets.strip.split.map(&:to_i)

if s.count { |d| d < 0 }.odd?
  a, *b = s.map(&:abs).sort
  puts (b.inject(:+) - a)
else
  puts s.map(&:abs).inject(:+)
end


a,b,c = gets.split.map{:to_i}
if (a<c and c<b) or (b<c and c<a)
	p 'Yes'
else
	p 'No'
end

Score : 100 points

Problem Statement

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

Constraints

0\leq A,B,C\leq 100

A, B and C are distinct integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

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

Sample Input 1

3 8 5

Sample Output 1

Yes

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

Sample Input 2

7 3 1

Sample Output 2

No

Sample Input 3

10 2 4

Sample Output 3

Yes

Sample Input 4

31 41 59

Sample Output 4

No


#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=gets.to_i
S=get_nsp
if S.count("#")==N or S.count(".")==N
    puts 0
    exit
end
r=array(N,0)
l=array(N,0)
r[0]=1 if S[0]=="#"
(N-1).times do|i|
  r[i+1]=r[i]
  r[i+1]+=1 if S[i+1]=="#"
end

l[0]=1 if S[N-1]=="."
(N-1).times do|i|
    l[i+1]=l[i]
    l[i+1]+=1 if S[N-2-i]=="."
end
min=INF
N.times do|i|
  min=min(min,l[i]+r[i])
end
puts min

Score : 300 points

Problem Statement

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

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

Constraints

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

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

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

3
#.#

Sample Output 1

1

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

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


# 入力
n = gets.chomp.to_i
s = gets.chomp

arr = []
arr << s.count(".")
n.times do |i|
  arr << s[0..i].count("#") + s[(i+1)..-1].count(".")
end

# 出力
puts arr.min


gets.to_i
str = gets.chomp
str.slice!(/^[\.]*/)

puts [str.count('.'), str.count('#')].max


n = gets.chomp.to_i
s = gets.chomp.split('')
count_b = 0
count_w = 0
flag = false
s.each do |c|
  if !flag
    if c == '#'
      count_b += 1
      flag = true
    end
  else
    if c == '#'
      count_b += 1
    else
      count_w += 1
    end
  end
end
puts [count_w, count_b].min


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

c = a+(a-1)
d = a+b
e = b+(b-1)

puts [c,d,e].max

Score : 100 points

Problem Statement

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

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

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

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

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

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


a,b=gets .split .map &:to_i
puts [2*a-1,2*b-1,a+b].max


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

max = h[0]
ans = 0
h.each do |v|
  ans += 1 if max <= v
  max =[max, v].max
end

puts ans

Score : 200 points

Problem Statement

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

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

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

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

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

Sample Input 1

4
6 5 6 8

Sample Output 1

3

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

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


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

r=0
hs.each_with_index {|hi, i|
  if i==0
    r+=1
  else
    r+=1 if hs.slice(0,i).all? {|h| h<=hi}
  end
}

print(r)


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

umi = 1
hmax = h[0]

(1..N-1).each do |i|
  if hmax <= h[i]
    umi += 1
    hmax = h[i]
  end
end

puts umi


S = gets.chomp

ref = '0'
def count(init)
	count = 0
	ref = init
	S.each_char do |char|
		if ref == char
			count += 1
			ref = char == '0'? '1' : '0'
		else
			ref = char
		end
	end
	count
end

countA = count('0')
countB = count('1')

if countA < countB
	puts countA
else
	puts countB
end

Score : 300 points

Problem Statement

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

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

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

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

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

000

Sample Output 1

1

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

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


a = []
(0..5).each do
    b = gets.chomp
    a<<b.to_i
end
a.combination(2) do |c|
    if c[1]-c[0] >= a[5]
        puts ':('
        exit
    end
end
puts 'Yay!'

Score: 100 points

Problem Statement

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

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

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

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

Constraints

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

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

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

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

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

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

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

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

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

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

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

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

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

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

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

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

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

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


input = $stdin.readlines
input.map!{|a| a.chomp("\n").to_i}
k = input[5]
input.delete_at(5)
if input.max-input.min <= k then
  print "Yay!"
else
  print ":("
end


dishes = []
5.times do
  dishes.push(gets.to_i)
end
dishes_remainder = []
dishes_actual = []
dish_remainder = 0
dishes.each do |dish|
  dish_remainder = dish % 10
  if dish_remainder == 0
    dish_remainder += 10
  end
  dishes_remainder.push(dish_remainder)
  dishes_actual.push(dish)
end
shortcut = 10 - dishes_remainder.min
sum = dishes_actual.sum - shortcut
puts sum

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

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

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

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

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

This restaurant has the following rules on orders:

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

Only one dish can be ordered at a time.

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

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

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

Constraints

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

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

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

Sample Input 1

29
20
7
35
120

Sample Output 1

215

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

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

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

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

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

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

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

Sample Input 2

101
86
119
108
57

Sample Output 2

481

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

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

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

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

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

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

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

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


input = $stdin.readlines
input.map!{|a| a.chomp("\n").to_i}
hasu= input.map{|a| a%10}
hasu.sort!
k = hasu[0]
hasu.delete_at(0)
kai = hasu.map{|a| 10 - a }
print input.inject(:+) + kai.inject(:+) + k


n = gets.to_f
tra = []
5.times { tra << gets.to_i }
puts (n/tra.min).ceil + 4

Score: 300 points

Problem Statement

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

There are five means of transport in this empire:

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

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

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

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

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

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

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

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

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

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

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

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

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

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

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

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

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

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

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

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

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


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

A = gets.split.map(&:to_i).sort.reverse
B = gets.split.map(&:to_i).sort.reverse
C = gets.split.map(&:to_i).sort.reverse

s = []

for i in 0..X-1 do
  for j in 0..Y-1 do
    if (i+1)*(j+1) > K
      break
    end
    for k in 0..Z-1 do
      if (i+1)*(j+1)*(k+1) <= K
        s.push( A[i] + B[j] + C[k])
      else
        break
      end
    end
  end
end

s.sort!.reverse!

for i in 0..K-1 do
  puts s[i]
end

Score: 400 points

Problem Statement

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

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

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

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

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

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

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

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

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

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

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

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

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

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

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

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

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

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

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

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

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

Sample Input 2

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

Sample Output 2

400
310
310
301
301

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

Sample Input 3

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

Sample Output 3

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

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


(X, Y, Z, K), As, Bs, Cs = readlines.map{|l| l.split.map(&:to_i)}

class Array
  def srt
    self.sort.reverse.take(K)
  end
end

def go(xs, ys)
  xs.srt.product(ys.srt).map{|x, y| x + y}.srt
end

puts go(go(As, Bs), Cs)


X,Y,Z,K = (gets).split(" ").map {|i| i.to_i}

$cakes = []
$cakes[0] = (gets).split(" ").map {|i| i.to_i}
$cakes[1] = (gets).split(" ").map {|i| i.to_i}
$cakes[2] = (gets).split(" ").map {|i| i.to_i}
$cakes[0].sort!.reverse!
$cakes[1].sort!.reverse!
$cakes[2].sort!.reverse!
#p K
#p az

=begin
作戦
* priority queueを使う
* 基本的にある組み合わせの次においしさが大きい組み合わせは、事前の組み合わせから
  １つどこかを変えた組み合わせである
  + そういう組み合わせを最大３つずつキューに入れて取り出していく。すると全部の組み合わせを
    一度に見なくて済む
=end

$memo = []
def memo_check(p)
    x,y,z = p
    return true if not (x<X && y<Y && z<Z)
    m = $memo[x*Y*Z + y*Z + z]
    if m.nil? then
        #$memo[x*Y*Z+y*Z+z] = 0
        m = 0
        return false
    end
    if m != 0 then
        return true
    end
    return false
end
def memo_add(p)
    x,y,z = p
    $memo[x*Y*Z+y*Z+z] = 1
end

def cake_calc(ixs)
    return $cakes[0][ixs[0]] + $cakes[1][ixs[1]] + $cakes[2][ixs[2]]
end

que = [[cake_calc([0,0,0]), [0,0,0]]]
offset = [[1,0,0], [0,1,0], [0,0,1]]

K.times do
    #p que
    ix = que.index( que.max {|a,b| a[0] <=> b[0] } )
    puts que[ix][0]
    me = que[ix][1]
    que.delete_at(ix)
    # 次の候補を入れる
    ne = offset.map {|ofs| ofs.zip(me).map {|o,m| o+m} }
    #ne.select! { |n| n[0] < X && n[1] < Y && n[2] < Z } #計算省略のためにmemo_checkではじいてみる
    ne.each do |n|
        if not memo_check(n) then
            memo_add(n)
            que << [cake_calc(n), n]
        end
    end
end


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

tastes = []
A.each do |a|
  B.each do |b|
    tastes << a + b
  end
end
tastes.sort!{|a, b| b <=> a}
tastes = tastes[0...K]

ans = []
C.each do |c|
  tastes.each do |taste|
    ans << taste + c
  end
end
ans.sort!{|a, b| b <=> a}

ans[0...K].each do |item|
  puts item
end


a,b,c=gets.split.map(&:to_i)
if a==b and b==c
  puts "Yes"
else
  puts "NO"
end

Score : 100 points

Problem Statement

You are given three integers A, B and C.

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

Constraints

All values in input are integers.

1 \leq A,B,C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

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

Sample Input 1

2 2 2

Sample Output 1

Yes

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

Sample Input 2

3 4 5

Sample Output 2

No

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


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


t = gets.chomp.split(" ")
for i in 0..2
  t[i] = t[i].to_i
end
if t[0] == t[1] == t[2]
  puts "Yes"
else
  puts "No"
end


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

total = 0
S.permutation(N) { |arr|
    x = X
    arr.each { |i|
        x = x % i
    }
    total += x
}

puts total % (10**9 + 7)

Score : 600 points

Problem Statement

Snuke has a blackboard and a set S consisting of N integers.
The i-th element in S is S_i.

He wrote an integer X on the blackboard, then performed the following operation N times:

Choose one element from S and remove it.

Let x be the number written on the blackboard now, and y be the integer removed from S. Replace the number on the blackboard with x \bmod {y}.

There are N! possible orders in which the elements are removed from S.
For each of them, find the number that would be written on the blackboard after the N operations, and compute the sum of all those N! numbers modulo 10^{9}+7.

Constraints

All values in input are integers.

1 \leq N \leq 200

1 \leq S_i, X \leq 10^{5}

S_i are pairwise distinct.

Input

Input is given from Standard Input in the following format:

N X
S_1 S_2 \ldots S_{N}

Output

Print the answer.

Sample Input 1

2 19
3 7

Sample Output 1

3

There are two possible orders in which we remove the numbers from S.

If we remove 3 and 7 in this order, the number on the blackboard changes as follows: 19 \rightarrow 1 \rightarrow 1.

If we remove 7 and 3 in this order, the number on the blackboard changes as follows: 19 \rightarrow 5 \rightarrow 2.

The output should be the sum of these: 3.

Sample Input 2

5 82
22 11 6 5 13

Sample Output 2

288

Sample Input 3

10 100000
50000 50001 50002 50003 50004 50005 50006 50007 50008 50009

Sample Output 3

279669259

Be sure to compute the sum modulo 10^{9}+7.


p1 = %w[A T]
p2 = %w[C G]
letter = gets.chomp
if p1.include? letter
  puts (p1 - [letter])[0]
else
  puts (p2 - [letter])[0]
end

Score : 100 points

Problem Statement

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

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

Constraints

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

Input

Input is given from Standard Input in the following format:

b

Output

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

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


b = gets.to_s

case b
when "A"
    puts "T"
when "T"
    puts "A"
when "G"
    puts "C"
when "C"
    puts "G"
end


input = gets

if input == "A"
  puts "T"
elsif input == "T"
  puts "A"
elsif input == "G"
  puts "C"
elsif input == "C"
  puts "G"
end


s = gets.strip.split("")

ans = 0
cnt = 0

s.each do |s_i|
  if ["A", "C", "G", "T"].include?(s_i)
    cnt += 1
  else
    ans = [ans, cnt].max
    cnt = 0
  end
end

puts ans

Score : 200 points

Problem Statement

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

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

Notes

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

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

Constraints

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

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

ATCODER

Sample Output 1

3

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

Sample Input 2

HATAGAYA

Sample Output 2

5

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

Sample Input 3

SHINJUKU

Sample Output 3

0

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


N,Q = gets.chomp.split(" ").map(&:to_i)
S = gets
a = 0
arr = Array.new
arr[0] = 0
for j in 0..N-2 do
  if S[j] == "A" and S[j+1] == "C" then
    a += 1
  else
  end
  arr[j+1] = a
end
for i in 1..Q do
  l,r = gets.chomp.split(" ").map(&:to_i)
puts arr[r-1] - arr[l-1]
end

Score : 300 points

Problem Statement

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

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

Notes

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

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

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

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

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

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

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

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

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

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


def get_n(s, line)
  l , r = line.split(' ')
  l = l.to_i - 1
  r = r.to_i - 1
  sub_str = s[l..r]
  return sub_str.count('AC').size
end

gets
s = gets.chomp
while(line = gets)
  line = line.chomp
  n = get_n(s, line)
  puts n
end


n, q = gets.split.map(&:to_i)
s = gets.chomp
ans = 0
dp = Array.new(n,0)
for i in 0..s.size-1 do
  dp[i] = dp[i-1].to_i
  if s[i..i+1] == 'AC'
    dp[i] += 1
  end
end

q.times do |i|
  l, r = gets.split.map(&:to_i)
  lt = l < 2 ? 0 : dp[l-2]
  puts dp[r-2] - lt
end


require 'set'

N = gets.chomp.to_i

S = Set.new
def add(a, b)
  if (a > b)
    S << [b, a]
  else
    S << [a, b]
  end
end

if N % 2 == 0
  # Now, we make N/2 pairs.
  1.upto(N/2).each do |i|
    p = N+1-i
    # i is the pair of (N+1-i).
    # We make pair with all others.
    1.upto(N).each do |j|
      if (j != i) && (j != p)
        add(i, j)
        add(p, j)
      end
    end
  end
else # odd
  # Now, we make N/2 + 1 pairs
  # [1,N-1],[2,N-2],..[(N-1)/2,(N-1)/2+1], N
  1.upto(N/2).each do |i|
    # i is the pair of N-i.
    p = N-i
    1.upto(N-1).each do |j|
      if (i != j) && (p != j)
        add(i, j)
        add(p, j)
      end
    end
    add(i, N)
    add(p, N)
  end
end

p S.size
S.each do |(i, j)|
  print "#{i} #{j}\n"
end

Score : 700 points

Problem Statement

You are given an integer N.
Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:

The graph is simple and connected.

There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.

It can be proved that at least one such graph exists under the constraints of this problem.

Constraints

All values in input are integers.

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.

The output will be judged correct if the graph satisfies the conditions.

Sample Input 1

3

Sample Output 1

2
1 3
2 3

For every vertex, the sum of the indices of the vertices adjacent to that vertex is 3.


N = gets.to_i
S = gets.chomp.chars

cnt = 0
(1..N).each do |i|
  S.combination(i).to_a.each do |a|
    if a.length == a.uniq.length
      cnt += 1
    end
  end
end

puts cnt

Score : 200 points

Problem Statement

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

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

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

4
abcd

Sample Output 1

15

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

Sample Input 2

3
baa

Sample Output 2

5

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

Sample Input 3

5
abcab

Sample Output 3

17


(h, w) = gets.chomp.split(' ').map(&:to_i)
(y, x) = gets.chomp.split(' ').map(&:to_i)
puts ((h - y) * (w - x)).to_s

Score : 100 points

Problem Statement

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

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

How many white cells will remain?

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

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

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

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


N , M , C = gets.split.map{|a| a.to_i}
B = gets.split.map{|a| a.to_i}
arr = Array.new(M)
count = 0

N.times do |i|

    arr = gets.split.map{|a| a.to_i}
    k = 0

    M.times do |j|
        k += arr[j] * B[j]
    end

    if k + C > 0
        count += 1
    end
end

puts count

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


n, m, c = gets.split.map(&:to_i)
bs = gets.split(nil, m).map(&:to_i)
results = n.times.map do
  as = gets.split(nil, m).map(&:to_i)
  (0..m-1).map {|i| as[i] * bs[i]}.inject(:+) + c > 0
end

puts results.count(true)


N,k = gets.split.map(&:to_i)
h={}
N.times do |i|
    a,b = gets.split.map(&:to_i)
    if h.has_key?(a)
        h[a]+=b
    else
        h[a]=b
    end
end
res = 0
h.sort.each do |price,num|
    if num <= k
        res += price * num
        k-=num
    else
        res += price * k
        k=0
    end
    break if k==0
end
puts res

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

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


attrs = Array.new
while line = $stdin.gets
    attrs << line.chomp.split.map{|v| v.to_i }
end

N_SHOPS = attrs[0][0]
NEEDS = attrs[0][1]
attrs.shift
shops = attrs.sort

cost = 0
having = 0

while true do
  if shops[0][1] < (NEEDS - having) then
    cost   += shops[0][0] * shops[0][1]
    having += shops[0][1]
    shops.shift
  else
    cost   += shops[0][0] * (NEEDS - having)
    break
  end
end

puts cost


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

count = 0
(1..a).each do |i|
    count += 1 if a % i == 0 && b % i == 0
    if count == k
        print i
        break
    end
end

Score : 200 points

Problem Statement

You are given positive integers A and B.

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

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

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

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

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

Sample Input 1

8 12 2

Sample Output 1

2

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

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


s = gets.chomp.sprit('')

a = s.count('0')
b = s.count('1')

puts s.length - ((a - b).abs)

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

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

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

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

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

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

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


$cache = {}

def union(x, y)
  xset = find(x)
  yset = find(y)
  if xset != yset
    if $rank[xset] > $rank[yset]
      xset, yset = yset, xset
    end

    $parent[xset] = yset
    $rank[yset] = $rank[xset] + 1
    $cache[xset] = yset
  end
end

def find(i)
  if $cache[i]
    return $cache[i]
  else
    if $parent[i] == -1
      return $cache[i] = i
    else
      return $cache[i] = find($parent[i])
    end
  end
end

def stat
  h = {}
  (1 .. $n).each do |i|
    next if i == 0

    h[find(i)] ||= 0
    h[find(i)] += 1
  end
  h
end

def inconv(s)
  total = s.values.inject(0, :+)
  s.values.map { |n|
    n * (total - n)
  }.inject(0, :+) / 2
end

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

bridges = $m.times.map { gets.split.map(&:to_i) }
$parent = Array.new($n + 1, -1)
$rank = Array.new($n + 1, 1)

ans = []
bridges.reverse_each do |x, y|
  ans << inconv(stat)
  union(x,y)
end

puts ans.reverse

Score : 400 points

Problem Statement

There are N islands and M bridges.

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

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

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

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

Sample Input 1

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

Sample Output 1

0
0
4
5
6

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

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


N, M = gets.split.map{|n| n.to_i}

A = Array.new(M)
B = Array.new(M)
c = Array.new(M)

for i in 1..M
    A[i-1], B[i-1] = gets.split.map{|n| n.to_i}
end

group = Array.new(N+1).map{Array.new}
for i in 1..N
    group[i][0] = i
end

c[M-1] = N * (N - 1) / 2
for i in 1..M-1

    if group[A[M-i]].include?(B[M-i]) || group[B[M-i]].include?(A[M-i])
        k = group[A[M-i]] | group[B[M-i]]
        k.each do |a|
            group[a] = k
        end
        c[M-i-1] = c[M-i]
        next
    end

    x = group[A[M-i]].size
    x = x * (x -1) / 2
    y = group[B[M-i]].size
    y = y * (y - 1) / 2

    k = group[A[M-i]] | group[B[M-i]]
    k.each do |a|
        group[a] = k
    end
    z = group[A[M-i]].size
    z = z * (z - 1) / 2

    c[M-i-1] = c[M-i] + x + y - z
end

puts c


require 'date'
puts Date.new(gets.split('/').map(&:to_i).join(','))<=Date.new(2019,4,30)?'Heisei':'TBD'

Score : 100 points

Problem Statement

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

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

Constraints

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

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


a = Date.parse(gets.to_s);
b = Date.parse("2019/4/30");

if a > b
  puts 'TBD'
else
  puts 'Heisei'
end


n = gets.chomp!.to_i
sum = 0.0
n.times do |i|
    x, u = gets.chomp!.split(" ")
    if u == "JPY"
        sum += x.to_i
    else
        sum += x.to_f * 380000.0
    end
end

puts sum

Score : 200 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 10

u_i = JPY or BTC.

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

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

Input

Input is given from Standard Input in the following format:

N
x_1 u_1
x_2 u_2
:
x_N u_N

Output

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

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

Sample Input 1

2
10000 JPY
0.10000000 BTC

Sample Output 1

48000.0

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

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

Sample Input 2

3
100000000 JPY
100.00000000 BTC
0.00000001 BTC

Sample Output 2

138000000.0038

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


n = gets.chomp!.to_i

jpy = 0
btc = 0

n.times do
  x, n = gets.chomp!.split(" ")
  if n == 'JPY'
    jpy += x.to_i
  else
    btc += x.to_f
  end
end
puts jpy + btc * 380_000


a,b=gets.split.map &:to_i;p b.send(b%a>0?:-: :+,a)

Score : 100 points

Problem Statement

You are given positive integers A and B.

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

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

4 12

Sample Output 1

16

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

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.