Victor has a 24-hour clock that shows the time in the format "HH:MM" (00 $$$\le$$$ HH $$$\le$$$ 23, 00 $$$\le$$$ MM $$$\le$$$ 59). He looks at the clock every $$$x$$$ minutes, and the clock is currently showing time $$$s$$$. How many different palindromes will Victor see in total after looking at the clock every $$$x$$$ minutes, the first time being at time $$$s$$$?For example, if the clock starts out as 03:12 and Victor looks at the clock every $$$360$$$ minutes (i.e. every $$$6$$$ hours), then he will see the times 03:12, 09:12, 15:12, 21:12, 03:12, and the times will continue to repeat. Here the time 21:12 is the only palindrome he will ever see, so the answer is $$$1$$$.A palindrome is a string that reads the same backward as forward. For example, the times 12:21, 05:50, 11:11 are palindromes but 13:13, 22:10, 02:22 are not.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of each test case follows. The only line of each test case contains a string $$$s$$$ of length $$$5$$$ with the format "HH:MM" where "HH" is from "00" to "23" and "MM" is from "00" to "59" (both "HH" and "MM" have exactly two digits) and an integer $$$x$$$ ($$$1 \leq x \leq 1440$$$) — the number of minutes Victor takes to look again at the clock.

For each test case, output a single integer — the number of different palindromes Victor will see if he looks at the clock every $$$x$$$ minutes starting from time $$$s$$$.

NoteThe first test case is explained in the statement.

def solve(time, period)
  period = period.to_i
  h, m = time.split(":").map(&:to_i)
  a = h * 60 + m

  hash = Hash.new(false)

  result = 0

  while !hash[a]
    result += 1 if palindrome?(a)
    hash[a] = true
    a = (a + period) % 1440
  end

  result
end

def palindrome?(n)
  a = n / 60
  b = n - 60 * a

  a = a.to_s
  while a.size < 2
    a = "0" + a
  end

  b = b.to_s
  while b.size < 2
    b = "0" + b
  end

  s = [a, b].join

  s.reverse == s
end

n = gets.to_i

n.times do
  time, period = gets.split

  p solve(time, period)
end

$cnt = []

def solve
    s = gets.split('')
    hh = []
    mm = []
    hh.append(s[0])
    hh.append(s[1])
    mm.append(s[3])
    mm.append(s[4])
    h = 0
    m = 0
    k = 0
    i = 6
    hh.each do |x|
        h = h * 10
        dig = x.to_i
        h = h + dig
    end
    mm.each do |x|
        m = m * 10
        dig = x.to_i
        m = m + dig
    end
    while i < s.length - 1
        k = k * 10
        dig = s[i].to_i
        k = k + dig
        i = i + 1
    end
    guy = (h * 100) + m
    ans = 0
    while $cnt[guy] == 0
        $cnt[guy] = 1
        s = []
        if h < 10
            s.append(0)
            s.append(h)
        else
            s.append(h / 10)
            s.append(h % 10)
        end
        if m < 10
            s.append(0)
            s.append(m)
        else
            s.append(m / 10)
            s.append(m % 10)
        end
        if s[0] == s[3] and s[1] == s[2]
            ans = ans + 1
        end
        m = m + k
        h = h + (m / 60)
        h = h % 24
        m = m % 60
        guy = (h * 100) + m
    end
    puts ans
    while $cnt[guy] != 0
        $cnt[guy] = 0
        m = m + k
        h = h + (m / 60)
        h = h % 24
        m = m % 60
        guy = (h * 100) + m
    end
end

maxn = 100005
maxn.times do
    $cnt.append(0)
end
gets.to_i.times do
    solve
end

gets.to_i.times do
  t, n = gets.chomp.split(" ")
  n = n.to_i
  h = n / 60
  m = n % 60
  hash = {}
  ans = 0
  i = 0
  while hash[t].nil?
    hash[t] = i
    ans += 1 if t == t.reverse
    s1 = (t[0,2].to_i + h) % 24
    s2 = (t[3,2].to_i + m)
    if s2 >= 60
      s1 += 1
      s1 %= 24
      s2 %= 60
    end
    if s1 / 10 == 0
      s1 = '0' + s1.to_s
    else
      s1 = s1.to_s
    end
    if s2 / 10 == 0
      s2 = '0' + s2.to_s
    else
      s2 = s2.to_s
    end
    t[0,2] = s1
    t[3,2] = s2
    i += 1
  end
  puts ans
end

gets.to_i.times do
  ans = 0
  a, b = gets.chomp.split
  h, m = a.split(':').map(&:to_i)
  hh = h
  mm = m
  b = b.to_i

  loop do
    g = ''
    g += '0' if h < 10
    g += h.to_s
    g += '0' if m < 10
    g += m.to_s
    ans += 1 if g == g.reverse

    h = (h + (m + b) / 60) % 24
    m = (m + b) % 60

    break if h == hh && m == mm
  end
  puts ans
end

require "set"
palindromes = Set.new

0.upto(23).each do |h|
  0.upto(59).each do |m|
    time = "%02d:%02d" % [h, m]
    if time == time.reverse
      palindromes << h * 60 + m
    end
  end
end

gets.to_i.times do
  s, x = gets.split
  h, m = s.split(":").map(&:to_i)
  x = x.to_i
  start = h * 60 + m
  now = start
  count = 0
  loop do
    count += 1 if palindromes.include?(now)
    now += x
    now %= 1440
    break if now == start
  end
  p count
end

main = -> {
  times = []
  (0 ... 24).each do |h|
      h0 = h / 10
      h1 = h % 10
      (0 ... 60).each do |m|
          m0 = m / 10
          m1 = m % 10
          times << (h0 == m1 && h1 == m0)
      end
  end

  t = int
  t.times do
      c, _x = strings
      x = _x.to_i
      time = c[0, 2].to_i * 60 + c[3, 2].to_i
      visited = [false] * (24 * 60)
      count = 0
      until visited[time]
        visited[time] = true
        count += 1 if times[time]
        time = (time + x) % (24 * 60)
      end
      puts count
  end
}

DEBUG = false
MOD = 10**9+7
INF = 10**18
$yesno = %w(No Yes)
$YesNo = %w(No Yes)
$YESNO = %w(NO YES)

require "set"
require "prime"

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def strings; gets.to_s.split end
def rep(n, &b); Array.new(n, &b) end
def yes; puts $yesno[1] end
def no; puts $yesno[0] end
def yesno t; puts $yesno[t ? 1 : 0] end
def YesNo t; puts $YesNo[t ? 1 : 0] end
def YESNO t; puts $YESNO[t ? 1 : 0] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * y.mod_inv(mod) % mod end
  def mod_nCr(r, mod = MOD); x = y = 1; (1..r).each { |i| x = x * (self + 1 - i) % mod; y = y * i % mod }; x.mod_div(y, mod); end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
  def compress(kinds = uniq.sort!); map { |x| kinds.bsearch_index { _1 >= x } }; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main[]


A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.Formally we will assume that segment [a, b] covers segment [c, d], if they meet this condition a ≤ c ≤ d ≤ b.

The first line contains integer n (1 ≤ n ≤ 105) — the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ 109) — the borders of the i-th segment. It is guaranteed that no two segments coincide.

Print a single integer — the number of the segment that covers all other segments in the set. If there's no solution, print -1. The segments are numbered starting from 1 in the order in which they appear in the input.

#CF Round 149. Div II Prob. B - Big Segment
n = gets.chomp.to_i
seg, curr = gets.chomp.split(/ /).map(&:to_i), 1
min, max = seg[0], seg[1]
(2..n).each {|i|
    nextSeg = gets.chomp.split(/ /).map(&:to_i)
    min, max = [min, nextSeg[0]].min, [max, nextSeg[1]].max
    seg, curr = nextSeg, i if seg[0]> nextSeg[0] || seg[1] < nextSeg[1]
}
puts (min < seg[0] || max > seg[1]) ? "-1" : curr.to_s

n = gets.strip.to_i

min = nil
max = nil
array = []

1.upto(n) do
  left, right = gets.strip.split(' ').map(&:to_i)

  min ||= left
  max ||= right

  min = left if left  < min
  max = right if right > max

  array << [left, right]
end

result = -1
array.each_with_index do |row, index|
  if row[0] <= min and row[1] >= max
    result =  index + 1
    break
  end
end

puts result

gets
a = readlines.map(&:chomp).map(&:split).each {|x| x.map!(&:to_i)}
i = a.index [a.transpose[0].min, a.transpose[1].max]
puts i.nil? ? -1 : i+1

# Link: http://codeforces.com/problemset/problem/242/B
# Ý tưởng:
# Mỗi segment sẽ là 1 array [l, r], lưu hết segments vào 1 array.
# Đầu tiên ta gắn min_l, max_r lần lượt là l và r của segments đầu tiên.
# Lặp từ phần tử thứ 2 tới cuối mảng segments để tìm ra min_l và max_r.
# Tiếp tục lặp lần nữa từ đầu tới cuối mảng, kiểm tra xem trong mảng có phần tử nào có l, r
# bằng với min_l và max_r vừa tìm được không.
# Nếu có tồn tại ta ngay lập tức trả về index của phần tử đó + thêm 1 (vì thứ tự của segment trong input bắt đầu từ 1).
# Nếu không tìm ra phần tử nào thì trả về -1

num_of_segments = gets.chomp.to_i
segments_description = []

# save descriptions of the segments ([left, right]) into an array
for i in 0..(num_of_segments - 1)
  segment = gets.chomp.split.map(&:to_i)
  segments_description << segment
end

def index_of_segment_container(segments)
  min_l, max_r = segments[0][0], segments[0][1]

  for i in 1..(segments.length - 1)
    min_l = segments[i][0] if segments[i][0] < min_l
    max_r = segments[i][1] if segments[i][1] > max_r
  end

  for i in 0..(segments.length - 1)
    return i + 1 if segments[i][0] == min_l && segments[i][1] == max_r
  end

  return -1
end

puts index_of_segment_container(segments_description)

num_of_segments = gets.chomp.to_i
segments_description = []

# save descriptions of the segments ([left, right]) into an array
for i in 0..(num_of_segments - 1)
  segment = gets.chomp.split.map(&:to_i)
  segments_description << segment
end

def index_of_segment_container(segments)
  min_l = segments[0][0]
  max_l = segments[0][1]

  for i in 1..(segments.length - 1)
    min_l = segments[i][0] if segments[i][0] < min_l
    max_l = segments[i][1] if segments[i][1] > max_l
  end

  for i in 0..(segments.length - 1)
    return i + 1 if segments[i][0] == min_l && segments[i][1] == max_l
  end

  return -1
end

puts index_of_segment_container(segments_description)

require 'set'

def read_next_line
  gets.split.map { |x| x.to_i }
end

min, max = 10 ** 9 + 1, 0
mins, maxs = Set.new, Set.new
for i in 1..gets.to_i
  a, b = read_next_line
  if a < min
    min = a
    mins.clear
    mins << i
  elsif a == min
    mins << i
  end
  if b > max
    max = b
    maxs.clear
    maxs << i
  elsif b == max
    maxs << i
  end
end
r = mins & maxs
puts(r.empty? ? -1 : r.first)

def check(number)
  segments = []
  (1..number.to_i).each do |i|
    segments << gets.split().map(&:to_i)
  end

  step_1 = 0
  step_2 = 0

  for i in (0..segments.size - 1)
    next unless segments[i + 1]
    if (segments[step_1][0] >= segments[i + 1][0]) && (segments[step_2][1] <= segments[i + 1][1])
      step_1 = i + 1
      step_2 = i + 1
    elsif segments[step_2][1] < segments[i + 1][1]
      step_2 = i + 1
    elsif segments[step_1][0] > segments[i + 1][0]
      step_1 = i + 1
    end
  end

  puts (step_1 == step_2) ? step_1 + 1 : -1
end

check(gets)

a=Array.new{|el| el=Array.new}
gets.to_i.times{a<<gets.split.map(&:to_i)}
a.include?([a.min_by{|e|e[0]}[0],a.max_by{|e|e[1]}[1]])? (puts a.index([a.min_by{|e|e[0]}[0],a.max_by{|e|e[1]}[1]])+1):(puts -1)

a=Array.new{|el| el=Array.new}
gets.to_i.times{a<<gets.split.map(&:to_i)}
k,l=a.min_by{|e|e[0]}[0],a.max_by{|e|e[1]}[1]
a.include?([k,l])? (puts a.index([k,l])+1):(puts -1)

n = gets.to_i
min = 1000000001
max = 0
seg = -1
x, y = [0, 0]
for i in 1..n
  l, r = gets.split.map(&:to_i)
  if l <= min && r >= max
    seg = i
	x = l
	y = r
  elsif l < x || r > y
    seg = -1
  end
  min = [l, min].min
  max = [r, max].max
end
print seg

n = gets.to_i
ar = []
n.times{ar<<gets.split.map(&:to_i)}
min_ar = []
max_ar = []
ar.each{|a,b| min_ar << a; max_ar << b}
min = min_ar.min
max = max_ar.max
res = ar.rindex{|a,b| a==min && b==max}
puts res ? res+1 : -1

segment_number = gets.to_i

left_coordinates = []
right_coordinates = []
segments = []

for i in (0..segment_number - 1)
  segment = gets.split(' ')
  left_coordinate = segment[0].to_i
  right_coordinate = segment[1].to_i
  left_coordinates << left_coordinate
  right_coordinates << right_coordinate
  segments << [left_coordinate, right_coordinate]
end

min_left = left_coordinates.min
max_right = right_coordinates.max

check_result = [min_left, max_right]

result = (segments.find_index(check_result) || -2) + 1

puts result

segment_number = gets.to_i

segments = []

for i in (0..segment_number - 1)
  segment = gets.split(' ')
  left_coordinate = segment[0].to_i
  right_coordinate = segment[1].to_i
  segments << [left_coordinate, right_coordinate]
end

min_left = -1
max_right = -1

segments.each do |segment|
  min_left = segment[0] if segment[0] < min_left || min_left < 0
  max_right = segment[1] if segment[1] > max_right || max_right < 0
end

check_result = [min_left, max_right]

result = (segments.find_index(check_result) || -2) + 1

puts result

segment_number = gets.to_i

segments = []

for i in (0..segment_number - 1)
  segment = gets.split(' ')
  left_coordinate = segment[0].to_i
  right_coordinate = segment[1].to_i
  segments << [left_coordinate, right_coordinate]
end

min_left = -1
max_right = -1

segments.each do |segment|
  min_left = segment[0] if segment[0] < min_left || min_left < 0
  max_right = segment[1] if segment[1] > max_right || max_right < 0
end

check_result = [min_left, max_right]

result = (segments.index { |segment| segment[0] == check_result[0] && segment[1] == check_result[1] } || -2) + 1

puts result

segment_number = gets.to_i

segments = []

for i in (0..segment_number - 1)
  segment = gets.split(' ')
  left_coordinate = segment[0].to_i
  right_coordinate = segment[1].to_i
  segments << [left_coordinate, right_coordinate]
end

min_left = segments.map(&:first).min
max_right = segments.map(&:last).max

check_result = [min_left, max_right]

result = (segments.find_index(check_result) || -2) + 1

puts result

def check(number)
  segments = []
  (1..number.to_i).each do |i|
    segments << gets.split().map(&:to_i)
  end

  step = 1
  current_1 = segments[0].min
  current_2 = segments[0].max
  for i in (1..segments.size - 1)
    break if segments[i + 1].nil?
    if (segments[i].min <= current_1 ) && (segments[i].max >= current_2)
      current_1 = segments[i].min
      current_2 = segments[i].max
      step = i + 1
    else
      step = -1
    end
  end
  puts step
end

check(gets)

def check(number)
  segments = []
  (1..number.to_i).each do |i|
    segments << gets.split().map(&:to_i)
  end

  step = 1
  current_1 = segments[0].min
  current_2 = segments[0].max
  for i in (1..segments.size - 1)
    break if segments[i + 1].nil?
    if (segments[i].min <= current_1 ) && (segments[i].max >= current_2)
      current_1 = segments[i].min
      current_2 = segments[i].max
      step = i + 1
    elsif (segments[i].min > current_1 ) && (segments[i].max > current_2)
      step = -1
    end
  end
  puts step
end

check(gets)

def check(number)
  segments = []
  (1..number.to_i).each do |i|
    segments << gets.split().map(&:to_i)
  end

  step = -1
  current_1 = segments[0].min
  current_2 = segments[0].max
  for i in (1..segments.size - 1)
    break if segments[i + 1].nil?
    if (segments[i].min <= current_1 ) && (segments[i].max >= current_2)
      current_1 = segments[i].min
      current_2 = segments[i].max
      step = i + 1
    end
  end
  puts step
end

check(gets)

def check(number)
  segments = []
  (1..number.to_i).each do |i|
    segments << gets.split().map(&:to_i)
  end

  step_1 = 0
  step_2 = 0

  for i in (0..segments.size - 1)
    next unless segments[i + 1]
    if (segments[step_1][0] >= segments[i + 1][0]) && (segments[step_2][1] < segments[i + 1][1])
      step_1 = i + 1
      step_2 = i + 1
    elsif segments[step_2][1] < segments[i + 1][1]
      step_2 = i + 1
    elsif segments[step_1][0] > segments[i + 1][0]
      step_1 = i + 1
    end
  end

  puts (step_1 == step_2) ? step_1 + 1 : -1
end

check(gets)

n = gets.to_i
min = 1000000001
max = 0
seg = -1
x, y = [0, 0]
for i in 1..n
  l, r = gets.split.map(&:to_i)
  if l <= min && r >= max
    seg = i
	x = l
	y = r
  elsif l < x && r > y
    seg = -1
  end
  min = [l, min].min
  max = [r, max].max
end
print seg

#CF Round 149. Div II Prob. B - Big Segment
n = gets.chomp.to_i
seg, curr, min, max = gets.chomp.split(/ /).map(&:to_i), 1, 1000000000, 0;
(2..n).each {|i|
    nextSeg = gets.chomp.split(/ /).map(&:to_i)
    min, max = [min, nextSeg[0]].min, [max, nextSeg[1]].max
    seg, curr = nextSeg, i if seg[0]> nextSeg[0] || seg[1] < nextSeg[1]
}
puts (min < seg[0] || max > seg[1]) ? "-1" : curr.to_s


Polycarpus is an amateur programmer. Now he is analyzing a friend's program. He has already found there the function rangeIncrement(l, r), that adds 1 to each element of some array a for all indexes in the segment [l, r]. In other words, this function does the following: function rangeIncrement(l, r)    for i := l .. r do        a[i] = a[i] + 1Polycarpus knows the state of the array a after a series of function calls. He wants to determine the minimum number of function calls that lead to such state. In addition, he wants to find what function calls are needed in this case. It is guaranteed that the required number of calls does not exceed 105.Before calls of function rangeIncrement(l, r) all array elements equal zero.

The first input line contains a single integer n (1 ≤ n ≤ 105) — the length of the array a[1... n].  The second line contains its integer space-separated elements, a[1], a[2], ..., a[n] (0 ≤ a[i] ≤ 105) after some series of function calls rangeIncrement(l, r).  It is guaranteed that at least one element of the array is positive. It is guaranteed that the answer contains no more than 105 calls of function rangeIncrement(l, r).

Print on the first line t — the minimum number of calls of function rangeIncrement(l, r), that lead to the array from the input data. It is guaranteed that this number will turn out not more than 105. Then print t lines — the descriptions of function calls, one per line. Each line should contain two integers li, ri (1 ≤ li ≤ ri ≤ n) — the arguments of the i-th call rangeIncrement(l, r). Calls can be applied in any order. If there are multiple solutions, you are allowed to print any of them.

NoteThe first sample requires a call for the entire array, and four additional calls:  one for the segment [2,2] (i.e. the second element of the array),  three for the segment [5,5] (i.e. the fifth element of the array).

n = gets
seq = gets.split.map(&:to_i)
seq << 0
curr = 0
l = []
r = []
seq.each_with_index do |num, idx|
	while curr < num do
		l << idx+1
		curr += 1
	end
	while curr > num do
		r<< idx
		curr -= 1
	end
end

puts l.length
l.length.times do |idx|
	puts "#{l[idx]} #{r[idx]}"
end

gets;s=[];z=[];a=gets.split.map &:to_i;a<<0;0.upto(a.size-1){|i|(a[i-1]-a[i]).times{z<<[s.pop,i]};(a[i]-a[i-1]).times{s<<i}};p z.size;z.map{|i|puts i.join' '}


One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows:  two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$;  two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:  admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";  admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.

The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters.

In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.

NoteIn the second example hacker need to use any of the passwords to access the system.

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

require 'prime'

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

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

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

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

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

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

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

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

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

def sum(a) a.inject(:+) end

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

def small(a,b) return (a<b)? a:b end

def dfs(i)
  @used[i] = true
  (0...26).each do |j|
    if @link[i][j] and !@used[j]
      dfs(j)
    end
  end
end

link = na2(26,26,false)
fl = na(26,false)
base = "a".ord
t = inp[0]
t.times do
  s = gets.chomp
  ss = s[0].ord - base
  s.each_char do |c|
    td = c.ord - base
    fl[td] = true
    link[td][ss] = true
    link[ss][td] = true
  end
end
syu = []
@used = na(26,false)
@link = link
ans = 0
fl.each.with_index do |f,i|
  next unless f
  unless @used[i]
    dfs(i)
    ans += 1
  end
end
p ans


Fox Ciel has a board with n rows and n columns. So, the board consists of n × n cells. Each cell contains either a symbol '.', or a symbol '#'.A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.Ciel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell.Please, tell Ciel if she can draw the crosses in the described way.

The first line contains an integer n (3 ≤ n ≤ 100) — the size of the board. Each of the next n lines describes one row of the board. The i-th line describes the i-th row of the board and consists of n characters. Each character is either a symbol '.', or a symbol '#'.

Output a single line with "YES" if Ciel can draw the crosses in the described way. Otherwise output a single line with "NO".

NoteIn example 1, you can draw two crosses. The picture below shows what they look like.In example 2, the board contains 16 cells with '#', but each cross contains 5. Since 16 is not a multiple of 5, so it's impossible to cover all.

def cross? (board, x, y, n)
	if (x == 0) or (x == n) or (y > n-2)
		return false
	elsif ( board[(y+1)*(n+1)+x] != "#" or
		    board[(y+2)*(n+1)+x] != "#" or
		    board[(y+1)*(n+1)+(x-1)] != "#" or
		    board[(y+1)*(n+1)+(x+1)] != "#" )
		return false
	else
		return true
	end
end

def check_board (board, n)
	for y in 0..n
		for x in 0..n
			if (board[y*(n+1)+x] == "#")
				if (cross?(board, x, y, n))
					board[(y+1)*(n+1)+x] = "."
					board[(y+2)*(n+1)+x] = "."
					board[(y+1)*(n+1)+(x-1)] = "."
					board[(y+1)*(n+1)+(x+1)] = "."
				else
					return "NO"
				end
			end
		end
	end
	return "YES"
end

board = []
n = (gets()).to_i - 1
for i in 0..n
	(gets()).each_char{ |c| board << c}
	board.pop
end

puts check_board(board, n)


The Hedgehog likes to give presents to his friend, but no less he likes to receive them.Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he choose, how large should it be?In order to get to know this, the Hedgehog asks you to write him a program that will count the estimated number of presents that he will receive during the following N days. Besides, he is guided by the principle:   on each holiday day the Hedgehog will necessarily receive a present,  he receives presents at least every K days (i.e., if he received a present on the i-th day, he will receive the next present no later than on the i + K-th day).  For the given N and K, as well as the list of holidays among the following N days count the minimal number of presents that could be given to the Hedgehog. The number of today's day is zero, and you should regard today's present as already given (i.e., you shouldn't count it in the answer).

The first line contains integers N and K (1 ≤ N ≤ 365, 1 ≤ K ≤ N). The second line contains a number C which represents the number of holidays (0 ≤ C ≤ N). Then in the same line follow C numbers ranging from 1 to N which are the numbers of holiday days. The numbers are given in the increasing order, without repeating numbers among them.

Print a single number — the minimal number of presents the Hedgehog will receive over the following N days.

n,k=gets.split.map(&:to_i)
t=gets.split.map(&:to_i)
t.shift;
t.push(n+100)
back=0;ans=0
for i in 1..n
        if t[0]==i then
                back=i
                ans+=1
                t.shift
        elsif i-back>=k then
                back=i
                ans+=1
        end
end
p ans

#!/usr/bin/env ruby

input = gets.chomp.split

N = Integer input[0]
K = Integer input[1]
input = gets.chomp.split

C = Integer input[0]

numbers = Array.new
for i in 0...C do
  numbers[i] = Integer input[i+1]
end
numbers[C] = N + 1

last_present = 0
ans = 0
for i in 0..C do
  if (numbers[i] - last_present > K)
    ans += (numbers[i] - 1 - last_present) / K
  end
  last_present = numbers[i]
end

ans += C
puts ans

N, K = gets.split.map(&:to_i)
t, *H = gets.split.map(&:to_i)
h = Array.new(N+1, false)
H.each { |i| h[i] = true }
ret = 0
p = 1
(1..N).each do |i|
  if p >= K
    p = 0
    ret += 1
  elsif h[i]
    ret += 1
    p = 0
  end
  p += 1
end
puts ret

n,k=gets.split.map(&:to_i)
t=gets.split.map(&:to_i)
t.shift;
t.push(n+100)
back=0;ans=0
for i in 1..n
        if t[0]==i then
                back=i
                ans+=1
        elsif i-back>=k then
                back=i
                ans+=1
        end
end
p ans

N, K = gets.split.map(&:to_i)
t, *H = gets.split.map(&:to_i)
h = Array.new(N, false)
h[0] = true
H.each { |i| h[i] = true }
ret = 0
p = 0
(0...N).each do |i|
  if p >= K
    p = 0
    ret += 1
  elsif h[i]
    ret += 1
    p = 0
  end
  p += 1
end
puts ret


Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1, m), then goes down 2 rows to (3, m), then goes left to (3, 1) and so on.Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').Consider sample tests in order to understand the snake pattern.

The only line contains two integers: n and m (3 ≤ n, m ≤ 50).  n is an odd number.

Output n lines. Each line should contain a string consisting of m characters. Do not output spaces.

R,C=gets.split.map(&:to_i)
R.times{|i|
	if i%4==1
		puts '.'*(C-1)+'#'
	elsif i%4==3
		puts '#'+'.'*(C-1)
	else
		puts '#'*C
	end
}

class Snake
  def initialize(n, m)
    @n, @m = n, m
  end

  def draw
    rows.each { |row| puts row.join }
  end

  private

  def rows
    [].tap do |rows|
      @n.times do |idx|
        case
        when idx.even?
          rows << ['#'] * @m
        when rows[idx - 2].nil?, rows[idx - 2].first == '#'
          rows << ['.'] * (@m - 1) + ['#']
        else
          rows << ['#'] + ['.'] * (@m - 1)
        end
      end
    end
  end
end

n, m = gets.chomp.split.map(&:to_i)
snake = Snake.new(n, m)
snake.draw

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

n.times do |i|
	#puts i
	m.times do |j|
		#print "#{j} "
		if i%2==0
			print "#"
		elsif i/2%2==0 && j==m-1
			print "#"
		elsif i/2%2==1 && j==0
			print "#"
		else
			print "."
		end
	end
	print "\n"
end

n, m = gets.split.map(&:to_i)
f = 1
for i in 0...n
	if(i % 2 == 0)
		m.times do
			print "#"
		end
	else
		if(f == 1)
			(m - 1).times do
				print "."
			end
			print "#"
			f = 0
		else
			print "#"
			(m - 1).times do
				print "."
			end
			f = 1
		end
	end
	puts ""
end

n,m = gets.split.map(&:to_i)
table = []
n.times do
	table.push(['.']*m)
end

for i in 0...n
	if (i%2==0)
		for j in 0...m
			table[i][j] = '#'
		end
	else
		if (i/2)%2 == 0
			table[i][-1] = '#'
		else
			table[i][0] = '#'
		end
	end
end

for i in 0...n
	for j in 0...m
		print table[i][j]
	end
	puts
end

def string_to_int(string, delim = " ")
  result = []
  string = string.split(delim)
  for i in 0...string.length
    result[i] = string[i].to_i
  end
  return result
end

input = string_to_int(gets.chomp)
n = input[0]
m = input[1]

snake = Array.new(n){Array.new(m){"."}}
for i in 0...snake.length
	for j in 0...snake[0].length
		if (i+1)%4 == 0
			snake[i][0] = "#"
			break
		elsif (i+1)%2 == 0
			snake[i][snake[0].length - 1] = "#"
			break
		else
			snake[i][j] = "#"
		end
	end
end

for i in 0...snake.length
	for j in 0...snake[0].length
		if j != snake[0].length - 1
			print snake[i][j]
		else
			puts snake[i][j]
		end
	end
end

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

a = []
counter = 0
for i in 0..n-1
  a[i] = []
  for j in 0..m-1
    if i%2 == 0
      a[i][j] = "#"
    else
      a[i][j] = "."
    end
  end

  counter+=1 if i%2 != 0

  if counter%2 == 0
    a[i][0] = "#"
  else
    a[i][-1] = "#"
  end
end

for i in 0..n-1
  for j in 0..m-1
    print "#{a[i][j]}"
  end
  puts
end

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

d = 0
for i in 1..n
    case d
    when 0,2
        m.times {print '#'}
    when 1
        (m-1).times {print '.'}
        print '#'
    when 3
        print '#'
        (m-1).times {print '.'}
    end
    puts ''
    d = (d+1)%4
end

#!/usr/bin/ruby
# coding: utf-8

n, m = gets.split.map(&:to_i)
n.times {|i|
  if i % 2 == 0
    puts '#' * m
  elsif i % 4 == 1
    puts '.' * (m - 1) + '#'
  elsif
    puts '#' + '.' * (m - 1)
  end
}

n, m = gets.split.map(&:to_i)
right_or_left = 0
n.times do |i|
  x = if i % 2 == 0
        '#' * m
      elsif right_or_left % 2 == 0
        result = '.' * m
        result[-1] = '#'
        right_or_left += 1
        result
      else
        result = '.' * m
        result[0] = '#'
        right_or_left += 1
        result
      end
      puts x
end

n, m = gets.chomp.split.map &:to_i
ind = 'r'
n.times do |x|
  if (x + 1) % 2 != 0
    m.times do
      print "#"
    end
    puts
  else
    if ind == 'r'
      (m - 1).times do
        print '.'
       end
    print '#'
    puts
    ind = 'l'
    else
      print '#'
      (m - 1).times do
        print '.'
      end
      puts
      ind = 'r'
    end
  end
end

n, m = gets.split.map(&:to_i)
(1..n).each { |i|
  (1..m).each { |j|
    if i&1==1
      print '#'
    else
      if (i&3==2 && j==m) || (i&3==0 && j==1)
        print '#'
      else
        print '.'
      end
    end
  }
  print "\n"
}

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

(0..n-1).each do |i|
  line = ""
  (0..m-1).each do |j|
    if i.even? || (j == m - 1) && (i % 4 == 1) || (j == 0) && (i % 4 == 3)
      line += "#"
    else
      line += "."
    end
  end
  puts line
end

n, m = gets.chomp.split(/ /).map(&:to_i)
left = true
right = false
(1..n).each do |row|
    line = nil
    if row.odd?
        line = Array.new(m, "#")
    else
        line = Array.new(m, ".")
        if left && !right
            line[m - 1] = "#"
            left = false
            right = true
        elsif right && !left
            line[0] = "#"
            left = true
            right = false
        end
    end
    puts line.join
end

a=gets.chomp.split(" ")
tok=0
a[0]=a[0].to_i
a[1]=a[1].to_i
hash=""
a[1].times do
    hash=hash+"#"
end
to=""
(a[1]-1).times do
    to=to+"."
end
to=to+"#"
four="#"
(a[1]-1).times do
    four=four+"."
end
1.upto(a[0]) do |i|
if (i%2==1)
    puts "#{hash}"
elsif (i%2==0 and tok==0)
    puts "#{to}"
    tok=1
else
    puts "#{four}"
    tok=0
end
end

h,w=gets.chomp.split.map{|e| e.to_i}

h.times{|i|
	if i%2==0 then
		puts ("#"*w)
	elsif i%4==1 then
		puts (("."*(w-1))+"#")
	else
		puts ("#"+("."*(w-1)))
	end
}

n,m = gets.chomp.split.map(&:to_i)
j = 0
n.times.each do |i|
  if i % 2 ==0
    puts '#' * m
  else
    s = '.' * m
    if j % 2 == 0
      s[m-1] = '#'
    else
      s[0] = '#'
    end
    j += 1
    puts s
  end
end

n, m = gets.split.map { |e| e.to_i }

for i in 1..n do
  puts '#'.rjust(m, '#') if i.odd?
  puts '#'.rjust(m, '.') if i%4 != 0 and i.even?
  puts '#'.ljust(m, '.') if i%4 == 0
end

#!/usr/bin/ruby

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

def filled(input)
  puts '#' * input.last
end

def points_left(input)
  puts "#{ '.' * (input.last - 1)}#"
end

def points_right(input)
  puts "##{ '.' * (input.last - 1 )}"
end

sign = -1

input.first.times do |i|
  if i % 2 == 0
    filled input
  elsif sign > 0
    sign *= -1
    points_right input
  else
    sign *= -1
    points_left input
  end
end

n,m=gets.split(" ").map {|x| x.to_i}
i = 1
while i<=n do
  if i%4==0
    print "#"
    j = 2
    while j<=m do
      print "."
      j+=1
    end
  elsif i%4==2
    j=1
    while j<m do
      print "."
      j+=1
    end
    print "#"
  else
    j=1
    while j<=m do
      print "#"
      j+=1
    end
  end
  puts("")
  i+=1
end

a = gets.split(" ")
n = a[0].to_i
m = a[1].to_i
k = 0
for i in 1..n do
    if i % 2 == 0 then
        k = k + 1
        if k % 2 == 1 then
            puts "." * (m - 1) + "#"
        else
            puts "#" + "." * (m - 1)

        end
    else
        puts "#" * m
    end
end

input = gets.chomp
snake = input.split

rows = snake[0].to_i
cells = snake[1].to_i

spaces = []
for i in (1..rows)
	if i%2 == 0
		spaces << i
	end
end

for i in (1..rows)
	if i%2 != 0
		for cell in (1..cells)
			if cell == cells
				puts "#"
			else
				print "#"
			end
		end
	else
		x = spaces.find_index(i)
		if (x+1)%2 != 0
			for space in (1..cells)
				if space == cells
					puts "#"
				else
					print "."
				end
			end
		else
			for space in (1..cells)
				if space == 1
					print "#"
				elsif space > 1 && space < cells
					print "."
				else
					puts "."
				end
			end
		end
	end
end

n,m = gets.split(" ").map(&:to_i)
flip = 0
res = []
(1..n).each do |i|
  if i % 2 != 0
    res << ["#"] * m
  else
    row = ["."] * (m - 1)
    if flip == 1
      row.unshift("#")
    else
      row << "#"
    end
    res << row
    flip ^= 1
  end
end
res.each do |r|
  puts r.join
end

$n,$m=STDIN.gets.split.map{|n|n.to_i}

def getLine(i)
  return "#"*$m if i%2==0
  return "."*($m-1)+"#" if i%4==1
  return "#"+"."*($m-1)
end

puts Array.new($n) {|i| getLine(i)+"\n"}.inject(:+)

n, m = gets.split.map(&:to_i)
a = Array.new(n){Array.new(m, ".")}
for i in 0...n
  if i % 2 == 0
    a[i] = Array.new(m, "#")
  elsif i % 4 == 1
    a[i][m - 1] = "#"
  elsif i % 4 == 3
    a[i][0] = "#"
  end
end
puts a.map{|x| x.join("")}

input = gets.chomp.split
n = input[0].to_i
m = input[1].to_i

arr = []
for i in 0..n-1
    arr[i] = Array.new(m)
    arr[i].fill('.')
end

i = 0
while i < n do
    arr[i].fill('#')
    i += 2
end

right = true
i = 1
while i < n do
    if right
        arr[i][m-1] = '#'
    else
        arr[i][0] = '#'
    end
    right = !right
    i += 2
end

arr.each do |row|
    puts row.join
end

#!/usr/bin/env ruby

input = ARGF.gets

n, m = input.split " "
n = n.to_i
m = m.to_i

right = true

ni = 0
n.times do
    if ni.even?
        puts '#' * m
    else
        if right
            right = false
            print '.' * (m - 1)
            puts '#'
        else
            right = true
            print '#'
            puts '.' * (m-1)
        end

    end

    ni += 1

end

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

1.upto(n) do |i|
  case i.modulo(4)
  when 1, 3
    puts '#'*m
  when 2
    puts "#{'.'*(m-1)}\#"
  when 0
    puts "\##{'.'*(m-1)}"
  end
end

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

right = true
n.times do |i|
  if i%2 == 0
    puts '#' * m
  else
    str = '.' * (m - 1)
    str.insert(right ? -1 : 0, '#' )
    right = !right
    puts str
  end
end

a=Array.new
str=gets.to_s
a=str.split
n=a[0].to_i
m=a[1].to_i
i=h=0
while i<n
  j=0
  while j<m
    print "#"
    j+=1
  end
  puts
  i+=1
  if i>=n
    break
  end
  if h==0
    j=0
    while j<m-1
      print "."
      j+=1
    end
    puts "#"
    h=1
  elsif h==1
    j=0
    print "#"
    while j<m-1
      print "."
      j+=1
    end
    puts
    h=0
  end
  i+=1
 end

n,m=gets.split().map{|i| Integer(i)}
count=0
for i in (0...n)
	if i%2==0
		puts "#"*m
	else
		count+=1
		if count%2!=0
			puts "."*(m-1)+"#"
		else
			puts "#"+"."*(m-1)
		end
	end
end

n, m = gets.chomp.split(' ').map { |i| i.to_i }
n.times do |iter|
    if iter.even?
        m.times { print '#' }
    else
        print '#' if iter % 4 == 3
        (m - 1).times { print '.' }
        print '#' if iter % 4 == 1
    end

    puts ''
end

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

a = []
counter = 0
for i in 0..n-1
  a[i] = []
  for j in 0..m-1
    if i%2 == 0
      a[i][j] = "#"
    else
      a[i][j] = "."
    end
  end

  counter+=1 if i%2 != 0

  if counter%2 == 0
    a[i][0] = "#"
  else
    a[i][-1] = "#"
  end
end

puts
for i in 0..n-1
  for j in 0..m-1
    print "#{a[i][j]}"
  end
  puts
end

input = gets.chomp.split
n = input[0].to_i
m = input[1].to_i

arr = []
for i in 0..n-1
    arr[i] = Array.new(m)
    arr[i].fill(".")
end

i = 0
while i < n do
    arr[i].fill("#")
    i += 2
end

right = true
i = 1
while i < n do
    if right
        arr[i][m-1] = "#"
    else
        arr[i][0] = "#"
    end
    right = !right
    i += 2
end

arr.each do |row|
    p row.join
end

n, m = gets.chomp.split(' ').map { |i| i.to_i }
n.times do |iter|
    if iter.even?
        m.times { print '#' }
    else
        print '#' if iter % 3 == 1
        (m - 1).times { print '.' }
        print '#' if iter % 3 == 0
    end

    puts ''
end

n, m = gets.chomp.split(' ').map { |i| i.to_i }
n.times do |iter|
    if iter.even?
        m.times { print '#' }
    else
        print '#' if iter % 4 == 1
        (m - 1).times { print '.' }
        print '#' if iter % 4 == 3
    end

    puts ''
end

n, m = gets.chomp.split(' ').map { |i| i.to_i }
n.times do |iter|
    if iter.even?
        m.times { print '#' }
    else
        print '#' if iter % 3 == 0
        (m - 1).times { print '.' }
        print '#' if iter % 3 >= 1
    end

    puts ''
end

n, m = gets.chomp.split(' ').map { |i| i.to_i }
n.times do |iter|
    if iter.even?
        m.times { print '#' }
    else
        print '#' if iter % 3 == 0
        (m - 1).times { print '.' }
        print '#' if iter % 3 == 1
    end

    puts ''
end


Filya just learned new geometry object — rectangle. He is given a field consisting of n × n unit cells. Rows are numbered from bottom to top with integer from 1 to n. Columns are numbered from left to right with integers from 1 to n. Cell, located at the intersection of the row r and column c is denoted as (r, c). Filya has painted two rectangles, such that their sides are parallel to coordinate axes and each cell lies fully inside or fully outside each of them. Moreover, no cell lies in both rectangles.Later, hedgehog Filya became interested in the location of his rectangles but was unable to find the sheet of paper they were painted on. They were taken by Sonya and now she wants to play a little game with Filya. He tells her a query rectangle and she replies with the number of initial rectangles that lie fully inside the given query rectangle. The query rectangle should match the same conditions as initial rectangles. Rectangle lies fully inside the query if each o its cells lies inside the query.Filya knows Sonya really well, so is sure that if he asks more than 200 questions she will stop to reply.

The first line of the input contains an integer n (2 ≤ n ≤ 216) — size of the field. For each query an integer between 0 and 2 is returned — the number of initial rectangles that lie fully inside the query rectangle.

To make a query you have to print "? x1 y1 x2 y2" (without quotes) (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ n), where (x1, y1) stands for the position of the bottom left cell of the query and (x2, y2) stands for the up right cell of the query. You are allowed to ask no more than 200 queries. After each query you should perform "flush" operation and read the answer. In case you suppose you've already determined the location of two rectangles (or run out of queries) you should print "! x11 y11 x12 y12 x21 y21 x22 y22" (without quotes), where first four integers describe the bottom left and up right cells of the first rectangle, and following four describe the corresponding cells of the second rectangle. You can print the rectangles in an arbitrary order. After you have printed the answer, print the end of the line and perform "flush". Your program should terminate immediately after it print the answer.


You are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x).

The first line contains the single positive integer n (1 ≤ n ≤ 105) — the number of integers. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2.

NoteIn the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).In the second example all pairs of indexes (i, j) (where i < j) include in answer.

#!/usr/bin/ruby
h=Hash.new(0)
r=0
gets
gets.split.map(&:to_i).each{|e|h[e]+=1}
h.each{|k,v|
	x=2
	while x<=0x80000000
		y=x-k
		if k==y
			r+=v*(v-1)/2
		elsif k<y
			r+=v*h[y]
		end
		x*=2
	end
}
p r

n = gets.chomp.to_i
a = gets.chomp.split.map(&:to_i)
h = Hash.new { 0 }.tap do |hash|
  a.each { |k| hash[k] += 1 }
end
max = [1, a.max].max * 2
pows = (0..Math.log(max, 2).ceil).map { |i| 2**i }
ans = 0
h.keys.each do |k|
  pows.each do |pow|
    next if pow < k
    if h.key?(pow - k) && (pow - k) == k
      ans += h[k] * (h[pow - k] - 1)
    else
      ans += h[k] * h[pow - k]
    end
  end
end
puts ans / 2

n = gets.chomp.to_i
as = gets.chomp.split.map(&:to_i)
hs = Hash.new(0)
amax = 1

as.each do |a|
  hs[a] += 1
  amax = [amax, a].max
end

ans = 0
hs.each do |k, v|
  i = 1
  while 2 ** i <= amax * 2
    if k == 2 ** (i - 1)
      ans += v * (v - 1)
    else
      ans += v * hs[2**i - k]
    end

    i += 1
  end
end

puts ans / 2


There is a square field of size $$$n \times n$$$ in which two cells are marked. These cells can be in the same row or column.You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes.For example, if $$$n=4$$$ and a rectangular field looks like this (there are asterisks in the marked cells):$$$$$$ \begin{matrix} . & . & * & . \\ . & . & . & . \\ * & . & . & . \\ . & . & . & . \\ \end{matrix} $$$$$$Then you can mark two more cells as follows$$$$$$ \begin{matrix} * & . & * & . \\ . & . & . & . \\ * & . & * & . \\ . & . & . & . \\ \end{matrix} $$$$$$If there are several possible solutions, then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 400$$$). Then $$$t$$$ test cases follow. The first row of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 400$$$) — the number of rows and columns in the table. The following $$$n$$$ lines each contain $$$n$$$ characters '.' or '*' denoting empty and marked cells, respectively. It is guaranteed that the sums of $$$n$$$ for all test cases do not exceed $$$400$$$. It is guaranteed that there are exactly two asterisks on the field. They can be in the same row/column. It is guaranteed that the solution exists.

For each test case, output $$$n$$$ rows of $$$n$$$ characters — a field with four asterisks marked corresponding to the statements. If there multiple correct answers, print any of them.


One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size $$$1\times1$$$, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks. The blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.Rainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a chess coloring. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!Since the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.The chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of grids of the games.  Each of the next $$$T$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$): the size of the side of the grid of the game.

For each grid of the game print the minimum number of turns required to build a chess coloring pattern out of blocks on it.

NoteFor $$$3\times3$$$ grid ponies can make two following moves:

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  ans << (n+2)/2
end
ans.each do |x|
  puts x
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  if n == 1
    ans << 1
  elsif n == 2 || n == 3
    ans << 2
  else
    ans << (n+3)/2
  end
end
ans.each do |x|
  puts x
end


The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example:  $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$,  $$$1$$$ is a good number: $$$1 = 3^0$$$,  $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$,  but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$),  $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid),  $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).

For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end

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

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

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

def kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end

def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end

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

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

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

def bit(n) n.to_s(2).split("").map(&:to_i) end

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

t3 = []
(0..44).each{|d|t3<<3**d}

n = inp[0]
n.times do
  q = inp[0]
  t = []
  while (q > 0)
    t << q % 3
    q /= 3
  end
  t.reverse!
  ind = -1
  t.size.times do |i|
    if(t[i] == 2)
      ind = i + 1
      break
    end
  end
  t.unshift(0)
  ans = 0

  (0...(t.size)).reverse_each do |i|
    break if ind < 0
    if(ind <= i)
      t[i] = 0
    end
    if(ind > i)
      if(t[i] == 0)
        t[i] = 1
        break
      else
        t[i] = 0
      end
    end
  end

(0...(t.size)).each do |i|
    ans += t3[t.size-i-1] if(t[i] >= 1)
  end
  p ans
end

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end

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

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

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

def kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end

def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end

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

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

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

def bit(n) n.to_s(2).split("").map(&:to_i) end

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

def c(i, now)
  if(i==10)
    @anss << now
    return
  end
  c(i+1,now)
  c(i+1,now + @t3[i])
end

@t3 = []
(0..9).each{|d| @t3 << 3**d}
@anss = []
c(0,0)
@anss.sort!
n = inp[0]
n.times do
  q = inp[0]
  puts @anss.bsearch{|x| x >=  q }
end


A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?

The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1 ≤ |s1| ≤ 104, 1 ≤ |s2| ≤ 106).

If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.

class Array
  def findB
    x0 = 0
    x1 = size-1
    return self[x0] if yield(self[x0])
    return false unless yield(self[x1])

    while x1-x0 > 1
      x2 = (x0+x1)/2

      if yield(self[x2])
        x1 = x2
      else
        x0 = x2
      end
    end
    return self[x1]
  end
end

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

def solve(from, to)
  chrs = {}
  0.upto(from.size-1) do |i|
    chrs[from[i]] = true
  end

  unless to.each_char.all?{|x|chrs[x]}
    return -1
  end

  tbl = {}
  chrs.keys.each do |c|
    idx = 0
    o = tbl[c] = [0]*from.size
    0.upto(from.size*2-1) do |i|
      if from[i%from.size] == c
        idx.upto(i-1) do |j|
          o[j%from.size] = i%from.size
        end
        break if i >= from.size
        idx = i
      end
    end
  end

  result = 1
  pos = -1
  ptr = Hash.new(-1)
  to.each_char do |x|
    new_pos = tbl[x][pos]
    #p [x, pos, new_pos, result, tbl[x]]
    result += 1 if new_pos <= pos
    pos = new_pos
  end

  result
end

from = gets.chomp
to = gets.chomp
p solve(from, to)

def error
	p -1
	exit
end
s,t=gets.chomp,gets.chomp
next_pos={}
closest_pos={}
i,pos,ans=s.length,-1,1
s.reverse.each_byte{|b|
	i-=1
	closest_pos.each{|k,v|next_pos[(i<<7)+k]=v}
	closest_pos[b]=i
}
closest_pos.each{|k,v|next_pos[(-1<<7)+k]=v}

t.each_byte{|b|
	pos=next_pos[(pos<<7)+b]
	unless pos
		ans+=1
		pos=next_pos[(-1<<7)+b]
		error unless pos
	end
}
p ans

def error
	p -1
	exit
end
s,t=gets.chomp,gets.chomp
error if s.size>t.size
next_pos={}
closest_pos={}
i,pos,ans=s.length,-1,1
s.reverse.each_byte{|b|
	i-=1
	closest_pos.each{|k,v|next_pos[[k,i]]=v}
	closest_pos[b]=i
}
closest_pos.each{|k,v|next_pos[[k,-1]]=v}

t.each_byte{|b|
	pos=next_pos[[b,pos]]
	unless pos
		ans+=1
		pos=next_pos[[b,-1]]
		error unless pos
	end
}
p ans


Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps:  Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2.  Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not.

The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).

For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise.

NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly.

str = gets.chomp
ntest =  gets.to_i
tests=Array::new()
ntest.times{tests<<gets.split(" ").map{|s| s.to_i} }
ccnts = Array.new()
ccnts[0] = [0,0,0]
str.each_char{|c|
	a = ccnts[-1].clone
	if c=='x'
		a[0] += 1
	elsif c=='y'
		a[1] += 1
	elsif c=='z'
		a[2] += 1
	end
	ccnts.push(a.clone)
}
tests.each {|ct|
	if ct[1] - ct[0] < 2
		puts "YES"
	else
		xc = ccnts[ct[1]][0] - ccnts[ct[0]-1][0]
		yc = ccnts[ct[1]][1] - ccnts[ct[0]-1][1]
		zc = ccnts[ct[1]][2] - ccnts[ct[0]-1][2]
		d1 = (xc-yc).abs
		d2 = (yc-zc).abs
		d3 = (zc-xc).abs
		if d1<=1 && d2<=1 && d3<=1
			puts "YES"
		else
			puts "NO"
		end
	end
}

str = gets.chomp
ntest =  gets.to_i
tests=Array::new()
ntest.times{tests<<gets.split(" ").map{|s| s.to_i} }
ccnts = Array.new()
ccnts[0] = [0,0,0]
str.each_char{|c|
	a = ccnts[-1].clone
	if c=='x'
		a[0] += 1
	elsif c=='y'
		a[1] += 1
	elsif c=='z'
		a[2] += 1
	end
	ccnts.push(a.clone)
}
tests.each {|ct|
	if ct[1] - ct[0] < 3
		puts "YES"
	else
		xc = ccnts[ct[1]][0] - ccnts[ct[0]-1][0]
		yc = ccnts[ct[1]][1] - ccnts[ct[0]-1][1]
		zc = ccnts[ct[1]][2] - ccnts[ct[0]-1][2]
		d1 = (xc-yc).abs
		d2 = (yc-zc).abs
		d3 = (zc-xc).abs
		if d1<=1 && d2<=1 && d3<=1
			puts "YES"
		else
			puts "NO"
		end
	end
}

str = gets.chomp
ntest =  gets.to_i
tests=Array::new()
ntest.times{tests<<gets.split(" ").map{|s| s.to_i} }
ccnts = Array.new()
ccnts[0] = [0,0,0]
str.each_char{|c|
	a = ccnts[-1].clone
	if c=='x'
		a[0] += 1
	elsif c=='y'
		a[1] += 1
	elsif c=='z'
		a[2] += 1
	end
	ccnts.push(a.clone)
}
tests.each {|ct|
	xc = ccnts[ct[1]][0] - ccnts[ct[0]-1][0]
	yc = ccnts[ct[1]][1] - ccnts[ct[0]-1][1]
	zc = ccnts[ct[1]][2] - ccnts[ct[0]-1][2]
	d1 = (xc-yc).abs
	d2 = (yc-zc).abs
	d3 = (zc-xc).abs
	if d1<=1 && d2<=1 && d3<=1
		puts "YES"
	else
		puts "NO"
	end
}

str = gets.chomp
ntest =  gets.to_i
tests=Array::new()
ntest.times{tests<<gets.split(" ").map{|s| s.to_i} }
ccnts = Array.new()
ccnts[0] = [0,0,0]
str.each_char{|c|
	a = ccnts[-1].clone
	if c=='x'
		a[0] += 1
	elsif c=='y'
		a[1] += 1
	elsif c=='z'
		a[2] += 1
	end
	ccnts.push(a.clone)
}
ccnts.each{|e| puts e.to_s}
tests.each {|ct|
	xc = ccnts[ct[1]][0] - ccnts[ct[0]-1][0]
	yc = ccnts[ct[1]][1] - ccnts[ct[0]-1][1]
	zc = ccnts[ct[1]][2] - ccnts[ct[0]-1][2]
	d1 = (xc-yc).abs
	d2 = (yc-zc).abs
	d3 = (zc-xc).abs
	if d1<=1 && d2<=1 && d3<=1
		puts "YES"
	else
		puts "NO"
	end
}


On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.Help the child to find out, what is the minimum total energy he should spend to remove all n parts.

The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi). Consider all the parts are numbered from 1 to n.

Output the minimum total energy the child should spend to remove all n parts of the toy.

NoteOne of the optimal sequence of actions in the first sample is:  First, remove part 3, cost of the action is 20.  Then, remove part 2, cost of the action is 10.  Next, remove part 4, cost of the action is 10.  At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.In the second sample, the child will spend 400 no matter in what order he will remove the parts.

n, m = gets.split.collect{|i| i.to_i}
v = gets.split.collect{|i| i.to_i}
ans = 0
(1..m).each do
    tmp = gets.split.collect{|i| i.to_i}
    ans += [v[tmp[0]-1],v[tmp[1]-1]].min
end
puts ans

# Create reachability matrix
def reach(links,n)
    reachability = Array.new(n) {[]}
    for i in 0..(links.length - 1) do
        node = links[i].map{|c| c - 1}
        reachability[node[0]].push(node[1])
        reachability[node[1]].push(node[0])
    end
    return reachability
end

# Cost of removing a given node
def cost(node, energies, connections, dead_nodes)
    cost = 0
    for i in connections[node] do
        cost = cost + energies[i] unless dead_nodes[i]
    end
    return cost
end

# Initialize variables
links = []; energies = []; connections = []; dead_nodes = []; energy_needed = 0;

# Read input
n, m = gets.strip.split.map{|s| s.to_i}
energies = gets.strip.split.map{|s| s.to_i}
m.times {links.push(gets.strip.split.map{|s| s.to_i})}

# Create connectivity matrix
connections = reach(links, n)

# Initialize dead_node structures
dead_nodes = Array.new(n,false)

# Loop to find min total cost
order = energies.map.with_index.sort.reverse.map(&:last)
for i in 0..(order.length - 1) do
    energy_needed = energy_needed + cost(order[i], energies, connections, dead_nodes)
    dead_nodes[order[i]] = true
end
puts energy_needed

# Create reachability matrix
def reach(links,n)
    reachability = Array.new(n) {[]}
    for i in 0..(links.length - 1) do
        node = links[i].map{|c| c - 1}
        reachability[node[0]].push(node[1])
        reachability[node[1]].push(node[0])
    end
    return reachability
end

# Cost of removing a given node
def cost(node, energies, connections, dead_nodes)
    cost = 0
    for i in connections[node] do
        cost = cost + energies[i] unless dead_nodes[i]
    end
    return cost
end

# Initialize variables
links = []; energies = []; connections = []; dead_nodes = []; energy_needed = 0;

# Read input
n, m = gets.strip.split.map{|s| s.to_i}
energies = gets.strip.split.map{|s| s.to_i}
m.times {links.push(gets.strip.split.map{|s| s.to_i})}

# Create connectivity matrix
connections = reach(links, n)

# Initialize dead_node structures
dead_nodes = Array.new(n,false)

# Sorting of nodes by their energies
order = energies.map.with_index.sort.reverse.map(&:last)

# Loop over nodes to get min energy
for i in 0..(order.length - 1) do
    energy_needed = energy_needed + cost(order[i], energies, connections, dead_nodes)
    dead_nodes[order[i]] = true
end
puts energy_needed

require 'set'
r=lambda{ gets.split.map(&:to_i) }
n,m=r.call
a=r.call
g=Array.new(n){ Set.new }
m.times{
	x,y=r.call
	g[x-1].add(y-1)
	g[y-1].add(x-1)
}
s=0
a.map.with_index.sort_by(&:first).map(&:last).reverse.each{ |e|
	g[e].each{|v| s+=a[v];g[v].delete e}
}
p s

n, m = gets.split.map { |x| x.to_i }
f = gets.split.map { |x| x.to_i }
ans = 0

m.times do
	u, v = gets.split.map { |x| x.to_i }
	ans += [f[u-1], f[v-1]].min
end

print ans, ?\n

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

puts (0...m).map { |_|
	a,b = gets.split.map(&:to_i)
	[v[a-1], v[b-1]].min
}.inject(0, &:+)

# Create reachability matrix
def reach(links,n)
    reachability = Array.new(n) {[]}
    for i in 0..(links.length - 1) do
        node = links[i].map{|c| c - 1}
        reachability[node[0]].push(node[1])
        reachability[node[1]].push(node[0])
    end
    return reachability
end

# Cost of removing a given node
def cost(node, energies, connections, dead_nodes)
    cost = 0
    for i in connections[node] do
        cost = cost + energies[i] unless dead_nodes[i]
    end
    return cost
end

# Costs for removing each node in a given configuration
def run_round(energies, connections, dead_nodes)
    total_cost = 0; costs = Array.new(energies.length, 0);
    for i in 0..(energies.length - 1) do
        unless dead_nodes[i]
            costs[i] = cost(i, energies, connections, dead_nodes)
            total_cost = total_cost + costs[i]
        end
    end
    return total_cost, costs
end

def active_links(node, connections, dead_node_indices)
    return (connections[node] - dead_node_indices).length
end

# Initialize variables
links = []; energies = []; connections = []; energy_needed = 0;

# Read input
n, m = gets.strip.split.map{|s| s.to_i}
energies = gets.strip.split.map{|s| s.to_i}
m.times {links.push(gets.strip.split.map{|s| s.to_i})}

# Create connectivity matrix
connections = reach(links, n)

# Initialize dead_node structures
dead_nodes = Array.new(n,false); dead_node_indices = [];

# Loop to find min total cost
while dead_nodes.include?(false)
    total_cost, costs = run_round(energies, connections, dead_nodes)
    cost_ratio = Array.new(energies.length, Float::INFINITY);
    for i in 0..(n- 1) do
        unless dead_nodes[i]
            cost_ratio[i] = (costs[i] == 0) ? 0 : (1.0 * costs[i]) / (energies[i] * active_links(i, connections, dead_node_indices) + costs[i])
        end
    end
    best_bet = cost_ratio.index(cost_ratio.min)
    dead_nodes[best_bet] = true; dead_node_indices.push(best_bet);
    energy_needed = energy_needed + costs[cost_ratio.index(cost_ratio.min)]
end

puts energy_needed

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

puts (0...m).map { |_|
	a,b = gets.split.map(&:to_i)
	[v[a-1], v[b-1]].min
}.inject(&:+)


Little C loves number «3» very much. He loves all things about it.Now he has a positive integer $$$n$$$. He wants to split $$$n$$$ into $$$3$$$ positive integers $$$a,b,c$$$, such that $$$a+b+c=n$$$ and none of the $$$3$$$ integers is a multiple of $$$3$$$. Help him to find a solution.

A single line containing one integer $$$n$$$ ($$$3 \leq n \leq 10^9$$$) — the integer Little C has.

Print $$$3$$$ positive integers $$$a,b,c$$$ in a single line, such that $$$a+b+c=n$$$ and none of them is a multiple of $$$3$$$. It can be proved that there is at least one solution. If there are multiple solutions, print any of them.

n = gets.to_i

if n % 3 == 0
  puts "1 1 #{n-2}"
else
  puts "1 2 #{n-3}"
end

n=gets.to_i
fn=sn=tn=0
if n%2==0
	fn=2
	n-=2
else
	fn=1
	n-=1
end

sn=tn=n/2

if sn%3==0
	sn-=1
	tn+=1
end

puts "#{fn} #{sn} #{tn}"

n = gets.to_i

if n % 3 == 0
    puts "1 1 #{n - 2}"
else
    puts "1 2 #{n - 3}"
end

n = gets.to_i
if n%3==0
    print "1 1 #{n-2}"
else
    print "1 2 #{n-3}"
end


Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.

The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.

In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.

5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov

3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123

# f=File.new("out.txt","w")
# fi=File.open("in.txt","r")

n=gets
#f.puts(n)
db=Array.new;
n.to_i.times do | |
  s=gets
  names=s.split
  b=1
  if db.empty?
    db.push(Array.new)
    db.last.push(names[0])
    db.last.push(names[1])
  else
    db.each do |i|
      if i.last==names[0]
        i.push(names[1])
        b=0
      end
    end
    if b==1
      db.push(Array.new)
      db.last.push(names[0])
      db.last.push(names[1])
    end
  end

end

puts db.size
db.each do |i|
print i.first
print " "
puts i.last
end

q = gets.chomp.to_i
queries = []
q.times { queries << gets.chomp.split }

hash = Hash.new { |h, k| h[k] = [] }
queries.each do |old_name, new_name|
  root = hash.keys.select { |key| hash[key].last == old_name }.first
  if root.nil?
    hash[old_name] << new_name
  else
    hash[root] << new_name
  end
end

puts hash.keys.length
hash.keys.each { |key| puts "#{key} #{hash[key].last}" }

n=gets.to_i
s=[]
cnt=0
n.times do
  s << gets.split(' ').map{|x| x.to_s}
  s.flatten!
  for i in 0...s.size-2
    if s[-2] == s[i] && i%2==1
      cnt+=1
      s[i]=s[-1]
      s.delete_at(-2)
      s.delete_at(-1)
    end
  end
end
i=0
puts n-cnt
while i < s.size
  print s[i]+" "+s[i+1]
  puts
  i+=2
end

q = STDIN.gets.to_i

users = {}
q.times do
  old, new = STDIN.gets.split(' ')

  if users.values.include?(old)
    initial = users.key(old)
    users[initial] = new
  else
    users[old] = new
  end

end

puts users.keys.count
users.each_pair do |old, new|
  puts "#{old} #{new}"
end

n = gets.to_i
names = {}
n.times do |i|
  before, after = gets.chomp.split
  if names[before] != nil
    names[after] = names[before]
    names.delete(before)
  else
    names[after] = before
  end
end

puts names.length
names.each do |after, before|
  puts [before, after].join(" ")
end

h = {}
n = gets.to_i
n.times{
    a,b = gets.split
    if h[a]
        h[b] = h[a]
        h.delete(a)
    else
        h[b] = a
    end
}
puts h.length
h.each { |a,b| puts "#{b} #{a}"}

q = gets.to_i

users = Hash.new

q.times do
    o, n = gets.split(" ")
    if users[o].nil? then
        users[n] = o
    else
        users[n] = users[o]
        users.delete(o)
    end
end

print "#{users.length}\n"
users.each do |v, k|
    print "#{k} #{v}\n"
end

n = gets.to_i
hash = {}
n.times do
	old,new = gets.split.map(&:chomp)
	if hash.key?(old)
		hash[new] = hash[old]
		hash.delete(old)
	else
		hash[new] = old
	end
end
p hash.length
hash.invert.sort_by{|key,val| key}.each{|val| puts "#{val[0]} #{val[1]}"}

#!/usr/bin/ruby

input_line = gets
amount = input_line.to_i

users = Hash.new
counter = 0
while (counter < amount)  do
    counter +=1
    input_line = gets.split(' ')
    if (users.has_value? input_line[0])
        users[users.key(input_line[0])] = input_line[1]
    else
        users[input_line[0]] = input_line[1]
    end
end

puts users.size

users.each_key do |key|
        puts key+' ' + users[key]
end

# @snippet<contest.rb#0.0.6:namespace.rb>
module Solution; end
# @snippet<contest.rb#0.0.6:header.rb>
require "scanf"
# @snippet<contest.rb#0.0.6:runner.rb>
class Solution::Runner

  def self.run(input_format, input_stream = STDIN, output_stream = STDOUT, &block)
    Solution::Solver.new(input_format, input_stream, output_stream) do
      input do |args|
        if block.nil?
          output solve(*args)
        else
          output block.call(*args)
        end
      end
    end
  end

end
# @snippet<contest.rb#0.0.6:solver.rb>
class Solution::Solver

  attr_reader :input_format
  attr_reader :input_stream
  attr_reader :output_stream

  def initialize(new_input_format, new_input_stream, new_output_stream, &block)
    @input_format = new_input_format
    @input_stream = new_input_stream
    @output_stream = new_output_stream

    instance_eval(&block) if block_given?
  end

  def input
    while s = gets
      break if s.nil?
      s.scanf(input_format) do |*args|
        yield(*args)
      end
    end
  end

  def output(res)
    puts res.size
    res.each do |key, value|
      puts "#{key} #{value}"
    end
  end

end
# @snippet<contest.rb#0.0.6:main.rb>

require "set"

class Disj

  attr_reader :parent
  attr_reader :root
  attr_reader :last_name

  def initialize
    @last_name = {}
    @parent = {}
    @root = Set.new
  end

  def size
    @root.size
  end

  def find(name)
    if parent[name].nil?
      name
    else
      find(parent[name])
    end
  end

  def parent?(name)
    find(name) === name
  end

  def update(old_name, new_name)
    if parent?(old_name)
      root.add old_name
    end
    last_name[find(old_name)] = new_name
    parent[new_name] = find(old_name)
  end

  def each
    root.each do |name|
      yield name, last_name[name]
    end
  end

end

input_format = "%d" # scanf(input_format)
Solution::Runner.run(input_format) do |q|
  disj = Disj.new

  list = (1..q).to_a.map do
    old, new = gets.split
    {:new => new, :old => old, }
  end

  list.inject(Set.new) do |set, info|
    disj.update info[:old], info[:new]
  end

  disj
end

# @snippet<contest.rb#0.0.6:namespace.rb>
module Solution; end
# @snippet<contest.rb#0.0.6:header.rb>
require "scanf"
# @snippet<contest.rb#0.0.6:runner.rb>
class Solution::Runner

  def self.run(input_format, input_stream = STDIN, output_stream = STDOUT, &block)
    Solution::Solver.new(input_format, input_stream, output_stream) do
      input do |args|
        if block.nil?
          output solve(*args)
        else
          output block.call(*args)
        end
      end
    end
  end

end
# @snippet<contest.rb#0.0.6:solver.rb>
class Solution::Solver

  attr_reader :input_format
  attr_reader :input_stream
  attr_reader :output_stream

  def initialize(new_input_format, new_input_stream, new_output_stream, &block)
    @input_format = new_input_format
    @input_stream = new_input_stream
    @output_stream = new_output_stream

    instance_eval(&block) if block_given?
  end

  def input
    while s = gets
      break if s.nil?
      s.scanf(input_format) do |*args|
        yield(*args)
      end
    end
  end

  def output(res)
    puts res.size
    res.each do |key, value|
      puts "#{key} #{value}"
    end
  end

end
# @snippet<contest.rb#0.0.6:main.rb>

require "set"

class Disj

  attr_reader :parent
  attr_reader :root
  attr_reader :last_name

  def initialize
    @last_name = {}
    @parent = {}
    @root = Set.new
  end

  def size
    @root.size
  end

  def find(name)
    if parent[name].nil?
      name
    else
      find(parent[name])
    end
  end

  def parent?(name)
    find(name) === name
  end

  def update(old_name, new_name)
    if parent?(old_name)
      root.add old_name
    end
    last_name[find(old_name)] = new_name
    parent[new_name] = find(old_name)
    self
  end

  def each
    root.each do |name|
      yield name, last_name[name]
    end
  end

end

input_format = "%d" # scanf(input_format)
Solution::Runner.run(input_format) do |q|
  (1..q).to_a.map do
    old, new = gets.split
    {:new => new, :old => old, }
  end.inject(Disj.new) do |disj, info|
    disj.update info[:old], info[:new]
  end
end

q = gets.to_i

oldies  = []
newies  = {}
changes = {}

q.times do
    old, new = gets.chomp.split

    oldies.push(old) if changes[old] == nil && newies[old] == nil
    changes[old] = new
    newies[new]  = true
end

puts oldies.size
oldies.each do |old|
    new = changes[old]
    while changes[new] != nil
        new = changes[new]
    end

    puts "#{old} #{new}"
end

n = gets.to_i

h = Hash.new

n.times do
    old_handle, new_handle = gets.split(' ')
    if h[old_handle].nil? then
        h[new_handle] = old_handle
    else
        h[new_handle] = h[old_handle]
        h.delete(old_handle)
    end
end

print "#{h.length}\n"
h.each do |k, v|
    print "#{v} #{k}\n"
end

q = gets.to_i

users = {}

for s in STDIN.each_line.take q
  old, new = s.split " "

  if users.has_value? old
    k = users.key(old)
    users[k] = new
  else
    users = users.merge!({old => new})
  end
end

puts users.length

users.each do |k, v|
  puts "#{k} #{v}"
end

pa=Array.new
ha=Hash.new  #ruby的哈希
hb=Hash.new  #ruby的哈希

n=gets.to_i
for i in 1..n
  str=gets.to_s
  pa=str.split
  stra=pa[0]
  strb=pa[1]
  ha[stra]=strb
end
#p ha

ha.each{|key,value|
  stt=key
  while ha[stt]!=nil
    stb=stt
    stt=ha[stt]
    ha.delete(stb)
  end
  hb[key]=stt
}
#p hb

puts hb.length
hb.each{|key,value|
  puts"#{key} #{value}"  #输出格式控制
}

# $f = File.open('input.txt', 'r')
$f = STDIN

def read_line
  $f.gets.chomp.split
end

def read_input(n)
  hash = {}
  n.times do
    sa, sb = read_line
    change = hash.key(sa) || sa

    hash[change] = sb
  end
  hash
end

def output(hash)
  puts hash.size
  hash.each do |k, v|
    puts "#{k} #{v}"
  end
end

def solve(n)
  output read_input(n)
end

while str = $f.gets
  n = str.chomp.to_i
  solve(n)
end

q = gets.to_i

users = Hash.new

q.times do
    o, n = gets.split(" ")
    p users[o]
    if users[o].nil? then
        users[n] = o
    else
        users[n] = users[o]
        users.delete(o)
    end
end

print "#{users.length}\n"
users.each do |v, k|
    print "#{k} #{v}\n"
end

pa=Array.new
ha=Hash.new  #ruby的哈希
hb=Hash.new  #ruby的哈希

n=gets.to_i
for i in 1..n
  str=gets.to_s
  pa=str.split
  stra=pa[0]
  strb=pa[1]
  ha[stra]=strb
end
#p ha

ha.each{|key,value|
  stt=key
  while ha[stt]!=nil
    stb=stt
    stt=ha[stt]
    ha.delete(stb)
  end
  hb[key]=stt
}
#p hb

hb.each{|key,value|
  puts"#{key} #{value}"#输出格式控制
}


Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online. The store contains k items. n customers have already used the above service. Each user paid for m items. Let aij denote the j-th item in the i-th person's order.Due to the space limitations all the items are arranged in one single row. When Ayush receives the i-th order he will find one by one all the items aij (1 ≤ j ≤ m) in the row. Let pos(x) denote the position of the item x in the row at the moment of its collection. Then Ayush takes time equal to pos(ai1) + pos(ai2) + ... + pos(aim) for the i-th customer.When Ayush accesses the x-th element he keeps a new stock in the front of the row and takes away the x-th element. Thus the values are updating.Your task is to calculate the total time it takes for Ayush to process all the orders.You can assume that the market has endless stock.

The first line contains three integers n, m and k (1 ≤ n, k ≤ 100, 1 ≤ m ≤ k) — the number of users, the number of items each user wants to buy and the total number of items at the market. The next line contains k distinct integers pl (1 ≤ pl ≤ k) denoting the initial positions of the items in the store. The items are numbered with integers from 1 to k. Each of the next n lines contains m distinct integers aij (1 ≤ aij ≤ k) — the order of the i-th person.

Print the only integer t — the total time needed for Ayush to process all the orders.

NoteCustomer 1 wants the items 1 and 5.pos(1) = 3, so the new positions are: [1, 3, 4, 2, 5].pos(5) = 5, so the new positions are: [5, 1, 3, 4, 2].Time taken for the first customer is 3 + 5 = 8.Customer 2 wants the items 3 and 1.pos(3) = 3, so the new positions are: [3, 5, 1, 4, 2].pos(1) = 3, so the new positions are: [1, 3, 5, 4, 2].Time taken for the second customer is 3 + 3 = 6.Total time is 8 + 6 = 14.Formally pos(x) is the index of x in the current row.

n, m, k = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
total_sum = 0
for i in 1..n do
  this_sum = 0
  order = gets.split.map(&:to_i)
  order.each_with_index do |val, i|
    for j in 0..k do
      if val == arr[j]
        o = arr.delete_at(j)
        this_sum += j + 1
        arr.unshift(o)
      end
    end
  end
  total_sum += this_sum
end
puts total_sum

n, m, k = readline.split(' ').collect(&:to_i)
arr = readline.split(' ').collect(&:to_i)
sum = 0
n.times do
  items = readline.split(' ').collect(&:to_i)
  items.each do |item|
    sum += arr.index(item) + 1
    arr.delete item
    arr.insert(0, item)
  end
end
puts sum

io = lambda {gets.split.map(&:to_i)}
n, m, k = io.call
p = io.call
r = 0

(0...n).each do |i|
  a = io.call
  a.each do |j|
    d = p.index(j)
    p.unshift(p.delete_at(d))
    r += d + 1
  end
end

puts r


You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays:   $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$;  $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$;  $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$;  $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$;  and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j < 0$$$. If there are no $$$j$$$ such that $$$p_j < 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.

Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j < 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.

NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j < 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k < 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.

def read
  gets.split.map &:to_i
end
gets.to_i.times do
  n = gets.to_i
  a, l = read, read
  v, res = [], [0] * n
  n.times do |i|
    if l[i] == 1
      res[i] = a[i]
    else
      v << a[i]
    end
  end
  v.sort!
  n.times do |i|
    if l[i].zero?
      res[i] = v[-1]
      v.pop
    end
  end
  puts res.join ' '
end


In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.The trajectory of a camel's spit is an arc, i.e. if the camel in position x spits d meters right, he can hit only the camel in position x + d, if such a camel exists.

The first line contains integer n (1 ≤ n ≤ 100) — the amount of camels in the zoo. Each of the following n lines contains two integers xi and di ( - 104 ≤ xi ≤ 104, 1 ≤ |di| ≤ 2·104) — records in Bob's notepad. xi is a position of the i-th camel, and di is a distance at which the i-th camel spitted. Positive values of di correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position.

If there are two camels, which spitted at each other, output YES. Otherwise, output NO.

n = gets.to_i

vers = []
targets = []
n.times do |i|
    s = gets.split.map{|i| i.to_i}
    targets << s[0] + s[1]
    vers << s[0]
end

if n < 2 then
    puts "NO"
else
    c = 0
    n.times do |i|
        if (k = vers.index(targets[i])) then
            if targets[k] == vers[i] then
                c = 2
            end
        end
    end
    if c > 1 then
        puts "YES"
    else
        puts "NO"
    end
end

n=gets.to_i
data=[]
n.times{data.push(gets.split.map(&:to_i)) }
data.each do |i|
        data.each do |j|
                if i[0]+i[1]==j[0] && j[0]+j[1]==i[0] then
                        puts "YES"
                        exit
                end
        end
end
puts "NO"

n = gets.to_i

mas = Array.new()
for i in 0..n-1
  s = gets.split(" ")
  mas[i] = [s[0].to_i, s[1].to_i]
end

for i in 0..n-1
  for j in 0..n-1
    if (i != j && (mas[i][0] + mas[i][1] == mas[j][0]) && (mas[j][0] + mas[j][1] == mas[i][0]))
      puts "YES"
      exit
    end
  end
end

puts "NO"


You have an array $$$a_1, a_2, \dots, a_n$$$. All $$$a_i$$$ are positive integers.In one step you can choose three distinct indices $$$i$$$, $$$j$$$, and $$$k$$$ ($$$i \neq j$$$; $$$i \neq k$$$; $$$j \neq k$$$) and assign the sum of $$$a_j$$$ and $$$a_k$$$ to $$$a_i$$$, i. e. make $$$a_i = a_j + a_k$$$.Can you make all $$$a_i$$$ lower or equal to $$$d$$$ using the operation above any number of times (possibly, zero)?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$d$$$ ($$$3 \le n \le 100$$$; $$$1 \le d \le 100$$$) — the number of elements in the array $$$a$$$ and the value $$$d$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$) — the array $$$a$$$.

For each test case, print YES, if it's possible to make all elements $$$a_i$$$ less or equal than $$$d$$$ using the operation above. Otherwise, print NO. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).

NoteIn the first test case, we can prove that we can't make all $$$a_i \le 3$$$.In the second test case, all $$$a_i$$$ are already less or equal than $$$d = 4$$$.In the third test case, we can, for example, choose $$$i = 5$$$, $$$j = 1$$$, $$$k = 2$$$ and make $$$a_5 = a_1 + a_2 = 2 + 1 = 3$$$. Array $$$a$$$ will become $$$[2, 1, 5, 3, 3]$$$.After that we can make $$$a_3 = a_5 + a_2 = 3 + 1 = 4$$$. Array will become $$$[2, 1, 4, 3, 3]$$$ and all elements are less or equal than $$$d = 4$$$.

t = gets.to_i
t.times do
  n, d = gets.split.map { |x| x.to_i }
  a = gets.split.map { |x| x.to_i }
  puts a.sort[0..1].sum <= d || a.max <= d ? "YES" : "NO"
end
#

gets.to_i.times do
  n,d=gets.split.map(&:to_i)
  a=gets.split.map(&:to_i).sort
  if a[-1]<=d
    puts "YES"
  elsif a[0]+a[1]<=d
    puts "YES"
  else
    puts "NO"
  end
end

gets.to_i.times do
  n, d = gets.split.map &:to_i
  a = gets.split.map &:to_i
  a.sort!
  if a[0] + a[1] <= d || a[-1] <= d
    puts "YES"
  else
    puts "NO"
  end
end

#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

T=gets.to_i
T.times do
    n,d=get_i
    a=get_i
    f=true
    n.times do|i|
      if a[i]>d
          f=false
          break
      end
    end
    if f
        puts "YES"
        next
    end
    is_find=false
    (n-1).times do|i|
        (i+1).upto(n-1) do|j|
          if a[i]+a[j]<=d
              is_find=true
              break
          end
        end
    end
    if is_find
        puts "YES"
    else
        puts "NO"
    end
end

def read
  gets.split.map &:to_i
end
gets.to_i.times do
  _, d = read
  a = read.sort!
  puts a[0] + a[1] <= d || a[-1] <= d ? "YES" :"NO"
end

t = gets.chomp.to_i
t.times do
  n, d = gets.chomp.split.map(&:to_i)
  arr = gets.chomp.split.map(&:to_i)
  arr = arr.sort
  puts arr[0] + arr[1] <= d || arr.all?{|el| el <= d} ? "YES" : "NO"
end

gets.to_i.times do
  n,d=gets.split.map(&:to_i)
  a=gets.split.map(&:to_i).sum
  if a<=d*n
    puts "YES"
  else
    puts "NO"
  end
end


Vasya has got $$$n$$$ books, numbered from $$$1$$$ to $$$n$$$, arranged in a stack. The topmost book has number $$$a_1$$$, the next one — $$$a_2$$$, and so on. The book at the bottom of the stack has number $$$a_n$$$. All numbers are distinct.Vasya wants to move all the books to his backpack in $$$n$$$ steps. During $$$i$$$-th step he wants to move the book number $$$b_i$$$ into his backpack. If the book with number $$$b_i$$$ is in the stack, he takes this book and all the books above the book $$$b_i$$$, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order $$$[1, 2, 3]$$$ (book $$$1$$$ is the topmost), and Vasya moves the books in the order $$$[2, 1, 3]$$$, then during the first step he will move two books ($$$1$$$ and $$$2$$$), during the second step he will do nothing (since book $$$1$$$ is already in the backpack), and during the third step — one book (the book number $$$3$$$). Note that $$$b_1, b_2, \dots, b_n$$$ are distinct.Help Vasya! Tell him the number of books he will put into his backpack during each step.

The first line contains one integer $$$n~(1 \le n \le 2 \cdot 10^5)$$$ — the number of books in the stack. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n~(1 \le a_i \le n)$$$ denoting the stack of books. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n~(1 \le b_i \le n)$$$ denoting the steps Vasya is going to perform. All numbers $$$a_1 \dots a_n$$$ are distinct, the same goes for $$$b_1 \dots b_n$$$.

Print $$$n$$$ integers. The $$$i$$$-th of them should be equal to the number of books Vasya moves to his backpack during the $$$i$$$-th step.

NoteThe first example is described in the statement.In the second example, during the first step Vasya will move the books $$$[3, 1, 4]$$$. After that only books $$$2$$$ and $$$5$$$ remain in the stack ($$$2$$$ is above $$$5$$$). During the second step Vasya will take the books $$$2$$$ and $$$5$$$. After that the stack becomes empty, so during next steps Vasya won't move any books.

# http://codeforces.com/contest/1073/problem/B

n = gets
array = gets.split(' ').map(&:to_i)
steps = gets.split(' ').map(&:to_i)

backpack = {}
result = []

steps.each do |step|
  if backpack[step]
    result << 0
  else
    count = 0
    begin
      num = array.shift
      count += 1
      backpack[num] = 1
    end while num != step

    result << count
  end
end

puts result.join(' ')

n = gets.strip.to_i

arr = gets.strip.split(' ').map(&:to_i)

query = gets.strip.split(' ').map(&:to_i)

max = nil

pos = Hash.new()

arr.each_with_index do |a, i|
    pos[a] = i + 1
end

out = []
query.each do |q|
    if max.nil?
        max = pos[q]
        out << max
    else
        val = pos[q]
        if val > max
            out << (val - max)
            max = val
        else
            out << 0
        end
    end
end

puts out.join(' ')