In 2013, the writers of Berland State University should prepare problems for n Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to n. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number i should be prepared by pi people for ti days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it.For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd.In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time.

The first line contains integer n — the number of Olympiads in 2013 (1 ≤ n ≤ 100). Each of the following n lines contains four integers mi, di, pi and ti — the month and day of the Olympiad (given without leading zeroes), the needed number of the jury members and the time needed to prepare the i-th Olympiad (1 ≤ mi ≤ 12, di ≥ 1, 1 ≤ pi, ti ≤ 100), di doesn't exceed the number of days in month mi. The Olympiads are given in the arbitrary order. Several Olympiads can take place in one day. Use the modern (Gregorian) calendar in the solution. Note that all dates are given in the year 2013. This is not a leap year, so February has 28 days. Please note, the preparation of some Olympiad can start in 2012 year.

Print a single number — the minimum jury size.

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
require 'date'
n=gets.to_i
h={}
n.times{
	n,d,p,t=gets.split.map(&:to_i)
	date=Date.new(2013,n,d)
	if h[date]
		h[date]+=p
	else
		h[date]=p
	end
	(t-1).times{
		date-=1
		if h[date]
			h[date]+=p
		else
			h[date]=p
		end
	}
}
p h.values.max

require 'Date'

line = File.read("input.txt").split("\n")

n = line[0].to_i
count = Hash.new(0)
line[1..-1].each do |l|
	m,d,j,t = l.split(" ").map(&:to_i)
	curr = Date.new(2013,m,d)
	finish = curr - 1
	start = curr - t
	(start..finish).each do |k|
		count[k] += j
	end
end

puts "#{count}"
File.open("output.txt", 'w') { |file|
	file.puts "#{count.values.max}"
}

line = File.read("input.txt").split("\n")

n = line[0].to_i
count = Hash.new(0)
line[1..-1].each do |l|
	m,d,j,t = l.split(" ").map(&:to_i)
	curr = (m * 30) + d
	finish = curr - 1
	start = curr - t
	(start..finish).each do |k|
		count[k] += j
	end
end

File.open("output.txt", 'w') { |file|
	file.puts "#{count.values.max}"
}

n = gets.to_i
count = Hash.new(0)
n.times do
	m,d,j,t = gets.split(" ").map(&:to_i)
	curr = (m * 30) + d
	finish = curr - 1
	start = curr - t
	(start..finish).each do |k|
		count[k] += j
	end
end

puts "#{count.values.max}"


You are given a string $$$s$$$ of length $$$n$$$ consisting of characters a and/or b.Let $$$\operatorname{AB}(s)$$$ be the number of occurrences of string ab in $$$s$$$ as a substring. Analogically, $$$\operatorname{BA}(s)$$$ is the number of occurrences of ba in $$$s$$$ as a substring.In one step, you can choose any index $$$i$$$ and replace $$$s_i$$$ with character a or b.What is the minimum number of steps you need to make to achieve $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$?Reminder:The number of occurrences of string $$$d$$$ in $$$s$$$ as substring is the number of indices $$$i$$$ ($$$1 \le i \le |s| - |d| + 1$$$) such that substring $$$s_i s_{i + 1} \dots s_{i + |d| - 1}$$$ is equal to $$$d$$$. For example, $$$\operatorname{AB}($$$aabbbabaa$$$) = 2$$$ since there are two indices $$$i$$$: $$$i = 2$$$ where aabbbabaa and $$$i = 6$$$ where aabbbabaa.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first and only line of each test case contains a single string $$$s$$$ ($$$1 \le |s| \le 100$$$, where $$$|s|$$$ is the length of the string $$$s$$$), consisting only of characters a and/or b.

For each test case, print the resulting string $$$s$$$ with $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$ you'll get making the minimum number of steps. If there are multiple answers, print any of them.

NoteIn the first test case, both $$$\operatorname{AB}(s) = 0$$$ and $$$\operatorname{BA}(s) = 0$$$ (there are no occurrences of ab (ba) in b), so can leave $$$s$$$ untouched.In the second test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 2$$$, so you can leave $$$s$$$ untouched. In the third test case, $$$\operatorname{AB}(s) = 1$$$ and $$$\operatorname{BA}(s) = 0$$$. For example, we can change $$$s_1$$$ to b and make both values zero.In the fourth test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 1$$$. For example, we can change $$$s_6$$$ to a and make both values equal to $$$1$$$.

def solve()
    s = string
    if s[0] != s[-1]
        s[0] = s[-1]
    end
    s
end

def main
  t = int
  t.times do
    puts solve
  end
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(No Yes)
INF = 10**9

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 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] 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 * mod_inv(y, mod) % 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
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


Furlo and Rublo play a game. The table has n piles of coins lying on it, the i-th pile has ai coins. Furlo and Rublo move in turns, Furlo moves first. In one move you are allowed to:  choose some pile, let's denote the current number of coins in it as x;  choose some integer y (0 ≤ y < x; x1 / 4 ≤ y ≤ x1 / 2) and decrease the number of coins in this pile to y. In other words, after the described move the pile will have y coins left. The player who can't make a move, loses. Your task is to find out, who wins in the given game if both Furlo and Rublo play optimally well.

The first line contains integer n (1 ≤ n ≤ 77777) — the number of piles. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 777777777777) — the sizes of piles. The numbers are separated by single spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

If both players play optimally well and Furlo wins, print "Furlo", otherwise print "Rublo". Print the answers without the quotes.

I =->{gets.split.map &:to_i}
RD =->{gets.to_i}

def sg(x)
    return 2 if(x>=2562991876)
    return 1 if(x>=45212176)
    return 1 if(x>=50626)
    return 3 if(x>=6724)
    return 0 if(x>=82)
    return 2 if(x>=16)
    return 1 if(x>=4)
    return 0
end
res = 0; n = RD[]; a = I[]; a.each{|ai|
    res ^= sg(ai)
}

puts res.zero? ? "Rublo" : "Furlo"

RD =->{gets.to_i}
def sg(x)
    return 2 if(x>=2562991876)
    return 1 if(x>=45212176)
    return 1 if(x>=50626)
    return 3 if(x>=6724)
    return 0 if(x>=82)
    return 2 if(x>=16)
    return 1 if(x>=4)
    return 0
end
res = 0; n = RD[]; n.times{
    res ^= sg(RD[])
}
puts res.zero? ? "Rublo" : "Furlo"

RD =->{gets.to_i}
def sg(x)
    return 2 if(x>=2562991876)
    return 1 if(x>=45212176)
    return 1 if(x>=50626)
    return 3 if(x>=6724)
    return 0 if(x>=82)
    return 2 if(x>=16)
    return 1 if(x>=4)
    return 0
end
res = 0; RD[].times{
    res ^= sg(RD[])
}
puts res.zero? ? "Rublo" : "Furlo"


Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:  a < b < c;  a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has  groups of three.Help Xenia, find the required partition or else say that it doesn't exist.

The first line contains integer n (3 ≤ n ≤ 99999) — the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3.

If the required partition exists, print  groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1.

cnt = gets.to_i
nums = gets.split.map(&:to_i)
n1=n2=n3=n4=n6=0
nums.each{|n|
	case n
	when 1; n1 += 1
	when 2; n2 += 1
	when 3; n3 += 1
	when 4; n4 += 1
	when 6; n6 += 1
	when 5, 7
		puts -1
		exit
	end
}
if n1 != cnt/3 || n2+n3 != cnt/3 || n4+n6 != cnt/3 || n2<n4 || n6<n3 || n6-n3 != n2-n4
	puts -1
	exit
end
n3.times {puts "1 3 6"}
n6 -= n3
n6.times {puts "1 2 6"}
n4.times {puts "1 2 4"}

class A
  def initialize
    n = gets.chomp.to_i
    num_list = Hash.new(0)

    list = gets.chomp.split(' ').map(&:to_i)
    answer = []

    list.each do |num|
      num_list[num] += 1
    end

    if num_list.has_key?(5) || num_list.has_key?(7)
      puts -1
      exit
    end

    while num_list[1] > 0 && num_list[2] > 0 && num_list[4] > 0
      answer << "1 2 4"
      num_list[1] -= 1
      num_list[2] -= 1
      num_list[4] -= 1
    end

    while num_list[1] > 0 && num_list[2] > 0 && num_list[6] > 0
      answer << "1 2 6"
      num_list[1] -= 1
      num_list[2] -= 1
      num_list[6] -= 1
    end

    while num_list[1] > 0 && num_list[3] > 0 && num_list[6] > 0
      answer << "1 3 6"
      num_list[1] -= 1
      num_list[3] -= 1
      num_list[6] -= 1
    end

    if answer.size == n/3
      puts answer
    else
      puts -1
    end
  end
end

a = A.new

a=gets.chomp.to_i
b=gets.chomp.split(" ")
k=b.include?("7")
l=b.include?("5")
if  k || l
puts "-1"
elsif
one=b.count("1")
two=b.count("2")
three=b.count("3")
four=b.count("4")
six=b.count("6")

if one!=two+three

puts "-1"

else

if two+three != four+six || three >six
puts "-1"
else

three.times do
puts "1 3 6"
end
four.times do
puts "1 2 4"
end
(two-four).times do
puts "1 2 6"
end

end
end
end

n=gets.to_i
a=gets.split.map(&:to_i)
na=a.count(1)
nb1=a.count(2)
nb2=a.count(3)
nc1=a.count(4)
nc2=a.count(6)
if na==n/3 && nb1+nb2==n/3 && nc1+nc2==n/3 && nb2<=nc2
  nb2.times {puts '1 3 6'}
  nc2-=nb2
  nc2.times {puts '1 2 6'}
  nc1.times {puts '1 2 4'}
else
  p -1
end

#!/usr/bin/env ruby

gets.chomp
arr = gets.chomp.split.map(&:to_i).sort

one   = arr.count(1)
two   = arr.count(2)
three = arr.count(3)
four  = arr.count(4)
six   = arr.count(6)

if one != arr.size / 3
  puts -1
  exit
end

two_four = [two, four].min
two  -= two_four
four -= two_four

three_six = [three, six].min
three -= three_six
six   -= three_six

two_six = [two, six].min
two -= two_six
six -= two_six

if (two_four + three_six + two_six) != (arr.size / 3)
  puts -1
  exit
end

two_four.times do
  puts [1, 2, 4].join(" ")
end

two_six.times do
  puts [1, 2, 6].join(" ")
end

three_six.times do
  puts [1, 3, 6].join(" ")
end

class A
  def initialize
    n = gets.chomp.to_i
    num_list = Hash.new(0)

    list = gets.chomp.split(' ').map(&:to_i)
    answer = []

    list.each do |num|
      num_list[num] += 1
    end

    if num_list.has_key?(3) || num_list.has_key?(5) || num_list.has_key?(7)
      puts -1
      exit
    end

    while num_list[1] > 0 && num_list[2] > 0 && num_list[4] > 0
      answer << "1 2 4"
      num_list[1] -= 1
      num_list[2] -= 1
      num_list[4] -= 1
    end

    while num_list[1] > 0 && num_list[2] > 0 && num_list[6] > 0
      answer << "1 2 6"
      num_list[1] -= 1
      num_list[2] -= 1
      num_list[6] -= 1
    end

    while num_list[1] > 0 && num_list[4] > 0 && num_list[6] > 0
      answer << "1 4 6"
      num_list[1] -= 1
      num_list[4] -= 1
      num_list[6] -= 1
    end

    while num_list[2] > 0 && num_list[4] > 0 && num_list[6] > 0
      answer << "2 4 6"
      num_list[2] -= 1
      num_list[4] -= 1
      num_list[6] -= 1
    end

    if answer.size == n/3
      puts answer
    else
      puts -1
    end
  end
end

a = A.new

a=gets.chomp.to_i
b=gets.chomp.split(" ")
k=b.include?("7")
l=b.include?("7")
if  k || l
puts "-1"
elsif
one=b.count("1")
two=b.count("2")
three=b.count("3")
four=b.count("4")
six=b.count("6")

if one!=two+three

puts "-1"

else

if two+three != four+six || three >six
puts "-1"
else

three.times do
puts "1 3 6"
end
four.times do
puts "1 2 4"
end
(two-four).times do
puts "1 2 6"
end

end
end
end

n=gets.to_i
a=gets.split.map(&:to_i)
na=a.count(1)
nb=a.count(2)
nc1=a.count(4)
nc2=a.count(6)
if na==n/3 && nb==n/3 && nc1+nc2==n/3
  nc1.times {puts '1 2 4'}
  nc2.times {puts '1 2 6'}
else
  p -1
end

#!/usr/bin/env ruby

gets.chomp
arr = gets.chomp.split.map(&:to_i).uniq.sort

printed = false
arr.permutation(3).each do |a,b,c|
  if (a % b == 0) && (b % c == 0)
    puts [c, b , a].join(' ')
    printed = true
  end
end

unless printed
  puts -1
end

#!/usr/bin/env ruby

gets.chomp
arr = gets.chomp.split.map(&:to_i).sort

arr = arr.permutation(3).to_a.map do |a,b,c|
  if (a % b == 0) && (b % c == 0) && (a > b) && (b > c)
    [c, b , a].join(' ')
  end
end

puts arr.compact.sort.uniq

#!/usr/bin/env ruby

gets.chomp
arr = gets.chomp.split.map(&:to_i).sort

one   = arr.count(1)
two   = arr.count(2)
three = arr.count(3)
four  = arr.count(4)
six   = arr.count(6)

if one != arr.size / 3
  puts -1
  exit
end

two_four = [two, four].min
two  -= two_four
four -= two_four

three_six = [three, six].min
three -= three_six
six   -= three_six

two_six = [two, six].min
two -= two_six
six -= two_six

if two_four + three_six + two_six != arr.size / 3
  puts -1
  exit
end

if two_four.nonzero?
  puts [1, 2, 4].join(" ")
end

if two_six.nonzero?
  puts [1, 2, 6].join(" ")
end

if three_six.nonzero?
  puts [1, 3, 6].join(" ")
end

#!/usr/bin/env ruby

gets.chomp
arr = gets.chomp.split.map(&:to_i).sort

arr = arr.permutation(3).to_a.map do |a,b,c|
  if (a % b == 0) && (b % c == 0) && (a > b) && (b > c)
    [c, b , a].join(' ')
  end
end

arr = arr.compact.sort.uniq

if arr.size.zero?
  puts -1
else
  puts arr
end


Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position.In the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions. It is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.

The first line of the input contains a single integer n (3 ≤ n ≤ 100 000). Each of the next n lines contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109). It is guaranteed that no two stars lie at the same point, and there does not exist a line such that all stars lie on that line.

Print three distinct integers on a single line — the indices of the three points that form a triangle that satisfies the conditions stated in the problem. If there are multiple possible answers, you may print any of them.

NoteIn the first sample, we can print the three indices in any order.In the second sample, we have the following picture.   Note that the triangle formed by starts 1, 4 and 3 doesn't satisfy the conditions stated in the problem, as point 5 is not strictly outside of this triangle (it lies on it's border).

def slope(x1, y1, x2, y2)
  p = y2 - y1
  q = x2 - x1
  g = p.gcd(q)
  p /= g
  q /= g

  [p, q]
end

n = gets.chomp.to_i
points = n.times.map.with_index { |i| [gets.chomp.split.map(&:to_i), i + 1]}

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

ans = [points[0][1], points[1][1]]
const = slope(*points[0][0], *points[1][0])

(2...n).each do |i|
  if slope(*points[0][0], *points[i][0]) != const then
    ans << points[i][1]
    break
  end
end

puts ans.join(' ')

n = gets.chomp.to_i
xs = []
ys = []
hs = Hash.new()
ans = []
for i in 1..n
  x, y = gets.chomp.split.map(&:to_i)
  xs << x
  ys << y
  hs[i] = (x - xs[0])**2 + (y - ys[0])**2
end

hs.sort { |(_, v1), (_, v2)| v1 <=> v2 }.each do |k, _|
  ans << k if ans.size < 3
  if ans.size == 3
    x0 = xs[ans[0] - 1]
    y0 = ys[ans[0] - 1]
    x1 = xs[ans[1] - 1]
    y1 = ys[ans[1] - 1]
    x2 = xs[ans[2] - 1]
    y2 = ys[ans[2] - 1]
    if (x1 - x0) * (y2 - y0) == (x2 - x0) * (y1 - y0)
      ans.delete_at(2)
    else
      break
    end
  end
end

puts ans.*' '


The polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y).  If the wind blows to the east, the boat will move to (x + 1, y).  If the wind blows to the south, the boat will move to (x, y - 1).  If the wind blows to the west, the boat will move to (x - 1, y).  If the wind blows to the north, the boat will move to (x, y + 1). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (ex, ey)?

The first line contains five integers t, sx, sy, ex, ey (1 ≤ t ≤ 105,  - 109 ≤ sx, sy, ex, ey ≤ 109). The starting location and the ending location will be different. The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).

If they can reach (ex, ey) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).

NoteIn the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.In the second sample, they cannot sail to the destination.

A = gets.chomp.split(' ').map{|c| c.to_i}
B = gets.chomp
y = A[3]-A[1]
x = A[4]-A[2]
for c in 0..(B.length-1)
	x -= 1 if x > 0 and B[c] == 'N'
	x += 1 if x < 0 and B[c] == 'S'
	y -= 1 if y > 0 and B[c] == 'E'
	y += 1 if y < 0 and B[c] == 'W'
	# puts "#{B[c]}: #{x} , #{y}"
	if x == 0 and y == 0
		puts c+1
		exit
	end
end
puts -1

_, x0, y0, x, y = gets.split.map(&:to_i)
x -= x0
y -= y0
gets.chomp.chars.each_with_index do |e, i|
  case e
  when 'E'
    x -= 1 if x > 0
  when 'S'
    y += 1 if y < 0
  when 'W'
    x += 1 if x < 0
  when 'N'
    y -= 1 if y > 0
  end
  if x == 0 && y == 0
    p i + 1
    exit
  end
end
p -1

n, sx, sy, ex, ey = gets.split(' ').map { |i| i.to_i }
wind = gets.chomp
tx = ex - sx
ty = ey - sy
for i in 0...wind.size
    tx -= 1 if tx > 0 && wind[i] == 'E'
    tx += 1 if tx < 0 && wind[i] == 'W'
    ty -= 1 if ty > 0 && wind[i] == 'N'
    ty += 1 if ty < 0 && wind[i] == 'S'
    if tx == 0 and ty == 0
        puts i + 1
        break
    end
end
if tx != 0 or ty != 0
    puts -1
end

def getdist(x1,y1,x2,y2)
	v1=(x1-x2).abs;
	v2=(y1-y2).abs;
	return Math.sqrt(v1**2+v2**2);
end

def main()
	inp=gets.chomp.strip.to_s.split(" ",5).map{|i| i.to_i};
	t=inp[0];
	sx=inp[1];
	sy=inp[2];
	ex=inp[3];
	ey=inp[4];
	wind=gets.chomp.strip.to_s;
	ix=sx;
	f=0;
	iy=sy;
	for i in 0..t-1
		wd=wind[i].chr;
		if wd=="E"
			if getdist(ix,iy,ex,ey)>getdist(ix+1,iy,ex,ey)
				ix=ix+1;
				iy=iy;
			end
		elsif wd=="S"
			if getdist(ix,iy,ex,ey)>getdist(ix,iy-1,ex,ey)
				ix=ix;
				iy=iy-1;
			end

		elsif wd=="N"
			if getdist(ix,iy,ex,ey)>getdist(ix,iy+1,ex,ey)
				ix=ix;
				iy=iy+1;
			end

		elsif wd=="W"
			if getdist(ix,iy,ex,ey)>getdist(ix-1,iy,ex,ey)
				ix=ix-1;
				iy=iy;
			end

		end
		if ix==ex and iy==ey
			f=1;
			puts i+1;
			break;
		end
	end

	if f==0
		puts "-1";
	end
end

main()

_, sx, sy, ex, ey = gets.split.map { |x| x.to_i }
ds = {E: ex - sx, W: sx - ex, N: ey - sy, S: sy - ey}.select { |__, v| v > 0 }
s = 0
gets.chomp.split('').each { |sw|
  w = sw.to_sym
  ds.delete(w) if ds.has_key?(w) && (ds[w] -= 1) == 0
  s += 1
  break if ds.empty?
}
puts(ds.empty? ? s : -1)

n, sx, sy, ex, ey = gets.split(' ').map { |i| i.to_i }
wind = gets.chomp
tx = ex - sx
ty = ey - sy
for i in 0...wind.size
    tx -= 1 if tx > 0 && wind[i] == 'E'
    tx += 1 if tx < 0 && wind[i] == 'W'
    ty -= 1 if ty > 0 && wind[i] == 'N'
    tx += 1 if ty < 0 && wind[i] == 'S'
    if tx == 0 and ty == 0
        puts i + 1
        break
    end
end
if tx != 0 or ty != 0
    puts -1
end


Xenia the vigorous detective faced n (n ≥ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right. Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is x, he can pass the note to another spy, either x - 1 or x + 1 (if x = 1 or x = n, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.But nothing is that easy. During m steps Xenia watches some spies attentively. Specifically, during step ti (steps are numbered from 1) Xenia watches spies numbers li, li + 1, li + 2, ..., ri (1 ≤ li ≤ ri ≤ n). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.You've got s and f. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy s to spy f as quickly as possible (in the minimum number of steps).

The first line contains four integers n, m, s and f (1 ≤ n, m ≤ 105; 1 ≤ s, f ≤ n; s ≠ f; n ≥ 2). Each of the following m lines contains three integers ti, li, ri (1 ≤ ti ≤ 109, 1 ≤ li ≤ ri ≤ n). It is guaranteed that t1 < t2 < t3 < ... < tm.

Print k characters in a line: the i-th character in the line must represent the spies' actions on step i. If on step i the spy with the note must pass the note to the spy with a lesser number, the i-th character should equal "L". If on step i the spy with the note must pass it to the spy with a larger number, the i-th character must equal "R". If the spy must keep the note at the i-th step, the i-th character must equal "X". As a result of applying the printed sequence of actions spy s must pass the note to spy f. The number of printed characters k must be as small as possible. Xenia must not catch the spies passing the note. If there are miltiple optimal solutions, you can print any of them. It is guaranteed that the answer exists.

n,m,s,f=gets.split.map(&:to_i)
q=''
p=1
c,d='R',1
c,d='L',-1 if s>f
m.times do
  t,l,r=gets.split.map(&:to_i)
  u=t-p
  if s < f
    u+=1 if !((l-1..r)===s+u)
    u=f-s if s+u>f
  else
    u+=1 if !((l..r+1)===s-u)
    u=s-f if s-u<f
  end
  q<<c*u
  s+=u*d
  break if s==f
  q<<'X'*(t+1-p-u)
  p=t+1
end
q<<c*(s-f).abs if f!=s
puts q

n,m,s,f = gets.split(" ").map(&:to_i)
steps = {}
m.times do
	t,l,r = gets.split(" ").map(&:to_i)
	steps[t] = [l,r]
end
if s < f
	direction = 1
	val = "R"
else
	direction = -1
	val = "L"
end
curr = s
ans = []
i = 1
while true
	can_reach = true
	next_spy = curr + direction
	ss = steps[i]
	if ss
		range = (ss[0]..ss[1])
		# puts "#{i} #{range.include?(curr) || range.include?(next_spy)}"
		can_reach = false if range.include?(curr) || range.include?(next_spy)
	end
	# puts "can_reach #{can_reach} curr #{curr} next_spy #{next_spy}"
	if can_reach
		ans << val
		curr = next_spy
	else
		ans << "X"
	end
	i += 1
	break if curr == f
end
puts ans.join("")

n,m,s,f=gets.split.map(&:to_i)
q=''
p=1
if s < f
  m.times do
    t,l,r=gets.split.map(&:to_i)
    u=t-p
    u+=1 if !((l-1..r)===s+u)
    u=f-s if s+u>f
    q<<'R'*u
    s+=u
    break if s==f
    q<<'X'*(t+1-p-u)
    p=t+1
  end
  q<<'R'*(f-s) if s<f
else
  m.times do
    t,l,r=gets.split.map(&:to_i)
    u=t-p
    u+=1 if !((l..r+1)===s-u)
    u=s-f if s-u<f
    q<<'L'*u
    s-=u
    break if s==f
    q<<'X'*(t+1-p-u)
    p=t+1
  end
  q<<'L'*(s-f) if f<s
end
puts q

n,m,s,f = gets.split(" ").map(&:to_i)
steps = {}
m.times do
	t,l,r = gets.split(" ").map(&:to_i)
	steps[l] = [l,r]
end
if s < f
	direction = 1
	val = "R"
else
	direction = -1
	val = "L"
end
curr = s
ans = []
(1..100000).each do |i|
	can_reach = true
	next_spy = curr + direction
	# puts curr
	ss = steps[i]
	if ss
		range = (ss[0]..ss[1])
		can_reach = false if range.include?(curr) || range.include?(next_spy)
	end
	if can_reach
		ans << val
		curr = next_spy
	else
		ans << "X"
	end
	break if curr == f
end
puts ans.join("")

n,m,s,f = gets.split(" ").map(&:to_i)
steps = {}
m.times do
	t,l,r = gets.split(" ").map(&:to_i)
	steps[t] = [l,r]
end
if s < f
	direction = 1
	val = "R"
else
	direction = -1
	val = "L"
end
curr = s
ans = []
(1..100000).each do |i|
	can_reach = true
	next_spy = curr + direction
	ss = steps[i]
	if ss
		range = (ss[0]..ss[1])
		# puts "#{i} #{range.include?(curr) || range.include?(next_spy)}"
		can_reach = false if range.include?(curr) || range.include?(next_spy)
	end
	# puts "can_reach #{can_reach} curr #{curr} next_spy #{next_spy}"
	if can_reach
		ans << val
		curr = next_spy
	else
		ans << "X"
	end
	break if curr == f
end
puts ans.join("")

n,m,s,f=gets.split.map(&:to_i)
q=''
p=1
m.times do
  t,l,r=gets.split.map(&:to_i)
  u=t-p
  u+=1 if !((l-1..r)===s+u)
  u=f-s if s+u>f
  u=0 if u < 0
  q<<'R'*u
  s+=u
  break if s==f
  q<<'X'*(t+1-p-u)
  p=t+1
end
q<<'R'*(f-s) if s<f
puts q

n,m,s,f=gets.split.map(&:to_i)
q=''
m.times do
  t,l,r=gets.split.map(&:to_i)
  if (l..r)===s || (l..r)===s+1
    q<<'X'
  else
    q<<'R'
    s+=1
    break if s==f
  end
end
puts q


Hongcow likes solving puzzles.One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.

The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece. The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space. It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.

Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.

NoteFor the first sample, one example of a rectangle we can form is as follows 111222111222For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle: .......XX................

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

piece = n.times.map{gets.chomp}
ym = piece.index{|x| x.include? 'X'}
yM = piece.rindex{|x| x.include? 'X'}
xm = piece.map{|x| x.index('X') || 1000}.min
xM = piece.map{|x| x.rindex('X') || -1000}.max

#p ym,yM,xm,xM
puts (ym..yM).all?{|y| (xm..xM).all? {|x| piece[y][x] == 'X'}} ? "YES" : "NO"

puts ($<.read.split.select{|e|e.include? ?X}.uniq.size==1 ? :YES : :NO)

class Region
  attr_reader(:n, :k, :queries)
  def initialize(n, k, queries)
    @n = n
    @k = k
    @queries = queries.map{|x| x.split("")}
    @locations = nil
    @xs = nil
    @ys = nil
    @minx = nil
    @miny = nil
    @maxy = nil
    @maxx = nil
  end

  def _locations
    (0..n - 1).map{|i| (0..k - 1).map{|j| [i, j]}}
      .flatten(1)
      .select{|i, j| queries[i][j] == 'X'}
  end

  def locations
    if(@locations.nil?)
      @locations = _locations
    else
      @locations
    end
  end

  def _xs
    locations.map{|y, x| x}
  end

  def xs
    if(@xs.nil?)
      @xs = _xs
    else
      @xs
    end
  end

  def _ys
    locations.map{|y, x| y}
  end

  def ys
    @ys ||= _ys
  end

  def minx
    @minx ||= xs.min
  end

  def maxx
    @maxx ||= xs.max
  end

  def miny
    @miny ||= ys.min
  end

  def maxy
    @maxy ||= ys.max
  end

  def bounds
    [
      minx,
      maxx,
      miny,
      maxy
    ]
  end

  def legitimations
    (miny..maxy).map do |y|
      (minx..maxx).map do |x|
        queries[y][x] == 'X'
      end
    end
  end

  def satisfied?
    legitimations.flatten.all?{|x| x}
  end

  def result
    return "YES" if satisfied?
    return "NO"
  end

end

def main
  n, k = gets.split(" ").map(&:to_i)
  xs = (0..n-1).map{ gets }
  r = Region.new(n, k, xs)
  puts r.result
end

main


Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.

The first line contains an integer n (3 ≤ n ≤ 10000), representing the number of hobbits.

In the first output line print a number k — the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.

hobbits_num = gets.to_i
num_of_days = ((-1 + Math.sqrt(1 + 8 * hobbits_num)) / 2).floor + 1
invited_hobbits = (num_of_days * (num_of_days - 1)) / 2
list_length = num_of_days - 1
array = Array.new(num_of_days) {Array.new(list_length, 0)}

array[0][0] = 1
num_of_days.times do |i|
  list_length.times do |j|
    if i == j
      array[i][j] = array[i - 1][list_length - 1] + 1 if i > 0
    elsif i < j
      array[i][j] = array[i][j - 1] + 1
    else
      array[i][j] = array[j][i - 1]
    end
  end
end

puts num_of_days
array.each do |e|
  e.each do |element|
    printf("%d ", element)
  end
  printf("\n");
end

n = gets.to_i

prev = [[1, 2], [1, 3], [2, 3]]
b = 3
while true
  cur = []
  tail = []
  prev.each do |a|
    b += 1
    tail << b
    cur << (a + [b])
  end
  cur << tail
  if b > n
    break
  end
  prev = cur
end

p prev.size
prev.each{|x| puts x*" "}

n = gets.to_i
a = []
i, j = 1, 1
while n >= i
 i.times{ |k|
  a[i] ||= []
  a[k] ||= []
  a[i] << j
  a[k] << j
  j += 1
 }
 n -= i
 i += 1
end
p a.length
a.each{ |x| puts x*" " }

n = gets.to_i
k = ((1 + Math.sqrt(1 + 8 * n)) / 2).to_i
n_ = k * (k - 1) / 2

d1 = 1
d2 = 2

a = Array.new(k + 1, "")

for i in 1 .. n_
	a[d1] += i.to_s + " "
	a[d2] += i.to_s + " "
	d2 += 1
	if d2 > k then
		d1 += 1
		d2 = d1 + 1
	end
end

puts k
for i in 1 .. k
	puts a[i]
end

hobbits_num = gets.to_i
num_of_days = ((-1 + Math.sqrt(1 + 8 * hobbits_num)) / 2).floor + 1
invited_hobbits = (num_of_days * (num_of_days - 1)) / 2
list_length = num_of_days - 1
array = Array.new(num_of_days) {Array.new(list_length, 0)}
visit = Array.new(invited_hobbits, 0)
def next_visit(start, last, visit)
  for i in start...last
    if visit[i] == 0
      visit[i] = 1
      return i
    end
  end
end

num_of_days.times do |n|
  for i in 0...n
    array[n][i] = array[i][n - 1]
  end
  for i in n...list_length
    array[n][i] = next_visit i, invited_hobbits, visit
  end
end
array.each do |e|
  e.each do |element|
    printf("%d ", element + 1)
  end
  printf("\n");
end

n = gets.to_i
k = ((1 + Math.sqrt(1 + 8 * n)) / 2).to_i
n_ = k * (k - 1) / 2

d1 = 1
d2 = 2

a = Array.new(k + 1, "")

for i in 1 .. n_
	a[d1] += i.to_s + " "
	a[d2] += i.to_s + " "
	d2 += 1
	if d2 > k then
		d1 += 1
		d2 = d1 + 1
	end
end

for i in 1 .. k
	puts a[i]
end


Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.

The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array.  The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.

Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).

h = Hash.new{[]}
n = gets.to_i
gets.split.map(&:to_i).each_with_index do |i, k|
    h[i] <<= k
end

a, b = 0, 0
gets
gets.split.map(&:to_i).each do |i|
    k = h[i]
    a += k[0] + 1
    b += n - k[-1]
end

puts "#{a} #{b}"

def compare_solutions(n,a,q,s)
  v_count = 0
  p_count = 0

  h_elements = Hash.new(0)
  # Creating a hash with element as symbol and value as index (as they can't be repeated cause
  # it could change the final couting for both team members)
  (1..n).each do |i|
    h_elements[a[i-1]] = i-1
  end

  queries = Hash.new(0)
  # Simplifying the amount of queries grouping them because the can be repeated
  s.each do |e|
    queries[e] +=1
  end

  queries.each do |k,v|
    e_index = h_elements[k]
    # vasya's count starting from the begining of the array and multiplied by v times the query is repeated
    v_count += (e_index + 1) * v
    # petya's count from the end of the array and multiplied by v times the query is repeated
    p_count += (n - e_index) * v
  end

  puts "#{v_count} #{p_count}"
end

n = gets.to_i
a_elements = gets.split(/\s/)
q_queries = gets.to_i
queries = gets.split(/\s/)
compare_solutions(n,a_elements,q_queries,queries)

h = Hash.new{[]}
n = gets.to_i
gets.split.map(&:to_i).each_with_index { |el, i| h[el] <<= i }
l,r = 0,0
gets
gets.split.map(&:to_i).each { |x|
  k = h[x]
  l += k[0]+1
  r += n-k[-1]
}
puts "#{l} #{r}"

n=gets.to_i
a=gets.split.map &:to_i
p=[0]*(n+1)
n.times{|i|p[a[i]]=i}
z=0
m=gets.to_i
gets.split.map(&:to_i).each{|i|z+=p[i]}
puts [z+m,m*n-z]*' '

n = gets.to_i
pos = Hash.new
tmp = 1
gets.split.each do |a|
    pos[a.to_i]=tmp
    tmp += 1
end
tmp = 0
m = gets.to_i
gets.split.each do |b|
    tmp+=pos[b.to_i]
end
print tmp, " ", (n+1)*m-tmp, "\n"

n = gets.to_i
i = -1
ar = Array.new(n){0}
gets.split.map(&:to_i).each_with_index do |el, index|
  ar[el] = index+1
end
m = gets.to_i
b = gets.split.map &:to_i

sum1,sum2 = 0, 0
b.each do |b|
  sum1 += ar[b]
  sum2 += n - ar[b] + 1
end

puts "#{sum1} #{sum2}"


John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$) — the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$.

Print the rank of Thomas Smith. Thomas's id is $$$1$$$.

NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$.

N = gets.to_i
arr = []
(1..N).each do |i|
    sum = gets.split.map(&:to_i).inject(:+)
    arr.push([-sum, i])
end

arr.sort!
N.times do |i|
    if arr[i][1] == 1
        puts i+1
        exit
    end
end

n = gets.to_i
tom = gets.split.map(&:to_i).inject(:+)
ans = 1
(n-1).times do
  sc = gets.split.map(&:to_i).inject(:+)
  ans += 1 if sc > tom
end
puts ans

n = gets.strip.to_i
ranks = {}
n.times do |i|
    scores = gets.strip.split.map(&:to_i).inject(:+)
    ranks[i + 1] = scores
end
ranks = ranks.sort_by { |k, v| [-v, k] }
ans = 0
ranks.each do |rank|
    ans += 1
    break if rank[0] == 1
end
puts ans

n=gets.to_i
puts (1..n).map{|i| [-gets.split.map(&:to_i).inject(:+), i]}.sort.index{|_,i|i==1}+1

n = gets.to_i
a = []
n.times{a << gets.split.map{|x| x.to_i}.inject(0){|s, x| s + x}}
s = a[0]
puts(a.sort.reverse.index(s) + 1)

n = gets.to_i
arr = []
n.times do |i|
  arr.push [i+1]+gets.chomp.split(" ").map(&:to_i)
end

arr.sort_by!{|x| [-x[1..-1].inject(:+),x[0]]}

arr.each_with_index do |x,i|
  if x[0]==1
    puts i+1
    exit
  end
end


You have decided to watch the best moments of some movie. There are two buttons on your player:   Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie.  Skip exactly x minutes of the movie (x is some fixed positive integer). If the player is now at the t-th minute of the movie, then as a result of pressing this button, it proceeds to the minute (t + x). Initially the movie is turned on in the player on the first minute, and you want to watch exactly n best moments of the movie, the i-th best moment starts at the li-th minute and ends at the ri-th minute (more formally, the i-th best moment consists of minutes: li, li + 1, ..., ri). Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?

The first line contains two space-separated integers n, x (1 ≤ n ≤ 50, 1 ≤ x ≤ 105) — the number of the best moments of the movie and the value of x for the second button. The following n lines contain the descriptions of the best moments of the movie, the i-th line of the description contains two integers separated by a space li, ri (1 ≤ li ≤ ri ≤ 105). It is guaranteed that for all integers i from 2 to n the following condition holds: ri - 1 < li.

Output a single number — the answer to the problem.

NoteIn the first sample, the player was initially standing on the first minute. As the minutes from the 1-st to the 4-th one don't contain interesting moments, we press the second button. Now we can not press the second button and skip 3 more minutes, because some of them contain interesting moments. Therefore, we watch the movie from the 4-th to the 6-th minute, after that the current time is 7. Similarly, we again skip 3 minutes and then watch from the 10-th to the 12-th minute of the movie. In total, we watch 6 minutes of the movie.In the second sample, the movie is very interesting, so you'll have to watch all 100000 minutes of the movie.

n, x = gets.split.map(&:to_i)
t = 1
q = 0
n.times do
  l, r = gets.split.map(&:to_i)
  t += x while t + x <= l
  q += r - t + 1
  t = r + 1
end
puts q

#!/usr/bin/env ruby
n,x=gets.split.map(&:to_i)
cur=1
ret=0
n.times{
	l,r=gets.split.map(&:to_i)
	ret+=r+1-l+(l-cur)%x
	cur=r+1
}
p ret

class A
  def initialize(n, x)
    @n = n
    @x = x
    @fields = Array.new(10**5) { 0 }
  end

  def setup(movements)
    movements.each do |l, r|
      (l..r).each { |idx| @fields[idx - 1] = 1 }
    end
  end

  def minimum_number_of_minutes
    idx = 0
    minutes = []

    while (idx <= @fields.length)
      @fields[idx..(idx + @x - 1)].tap do |arr|
        if arr.any? { |a| a == 1 }
          minutes << arr.rindex(1) + 1
          idx += minutes.last
        else
          minutes << 0
          idx += @x
        end
      end
    end

    minutes.inject(0, :+)
  end
end

n, x = gets.chomp.split().map(&:to_i)
movements = [].tap do |arr|
  n.times { arr << gets.chomp.split().map(&:to_i) }
end

a = A.new(n, x)
a.setup(movements)
puts a.minimum_number_of_minutes

n,x=gets.chomp.split.map(&:to_i)
lol,i=0,1
n.times do
	l,r=gets.chomp.split.map(&:to_i)
	lol+= r-l + (l-i)%x + 1
	i=r+1
end
puts lol

n, x = gets.chomp.split(/ /).map(&:to_i)
watch = 0
skip = 1
n.times do
    l, r = gets.chomp.split(/ /).map(&:to_i)
    skip += x while skip + x <= l
    if skip <= l
        while skip <= r
            watch += 1
            skip += 1
        end
    end
end
puts watch

n,x=gets.split.map{|e| e.to_i}
t=1
ans=0
n.times{
	l,r=gets.split.map{|e| e.to_i}
	while t+x<=l
		t+=x
	end
	ans+=r-t+1
	t=r+1
}
puts ans

#!/usr/bin/ruby
tokens = STDIN.gets.chomp.split(" ").map(&:to_i)
n = tokens[0]
x = tokens[1]
minute = 1
ans = 0
n.times do
    l, r = STDIN.gets.chomp.split(" ").map(&:to_i)
    while minute + x <= l do
        minute += x
    end
    ans += r - minute + 1
    minute = r + 1
end

puts ans

n,x = gets.split(" ").map(&:to_i)
minutes_watched = 0
current = 1
n.times do
	l,r = gets.split(" ").map(&:to_i)
	while current + x <= l
		current += x
	end
	minutes_watched += l - current
	current = r + 1
	minutes_watched += r + 1 - l
	# puts "current #{current} minutes_watched #{minutes_watched}"
end

puts minutes_watched

n, x = gets.chomp.split(' ').map(&:to_i)
c = 1
total = 0
n.times do |i|
  l, r = gets.chomp.split(' ').map(&:to_i)
  while c + x <= l do c += x end
  total += r-l + 1
  total += l - c
  c = r + 1
end
puts total

n,x = gets.split.map &:to_i
puts n.times.map{gets.split.map &:to_i}.unshift([0,0]).each_cons(2).map{|p,n| (n[0]-p[1]-1)%x+n[1]-n[0]+1}.inject(:+)

n, x = gets.split.map(&:to_i)
a = n.times.map{gets.split.map(&:to_i)}
ans = 0
a.each{|x, y| ans += y + 1 - x}
j = 1
n.times do |i|
  ans += (a[i][0] - j) % x
  j = a[i][1] + 1
end
puts ans

n, x = gets.split.map(&:to_i)
a = n.times.map{gets.split.map(&:to_i)}
ans = 0
j = 1
a.each do |s, e|
  ans += (s - j) % x
  ans += e - s + 1
  j = e + 1
end
puts ans

read=lambda{ gets.split(" ").map{|x| x.to_i} }
n,x=read.call
#puts "#{n} #{x}"
ans=0
now=1
for _ in 0...n
  l,r=read.call
  ans+=(l-now)%x+r-l+1
  now=r+1
end
puts ans

n, x = gets.split(' ').map(&:to_i)
pre = 0
ans = 0
n.times do
    l, r = gets.split(' ').map(&:to_i)
    ans += (l - pre - 1) % x + r - l + 1
    pre = r
end
print ans, "\n";

class Stu
	attr_accessor:a
	attr_accessor:b
end

#File.open("2.txt","r") do|file|
data=Array.new
h=Array.new
#str=file.gets.to_s
str=gets.to_s
h=str.split
n=h[0].to_i
x=h[1].to_i
i=0
while i<n
	data[i]=Stu.new
	#str=file.gets.to_s
	str=gets.to_s
	h=str.split
	data[i].a=h[0].to_i
	data[i].b=h[1].to_i
	i+=1
end

t=1
i=s=0
while i<n
	s+=(data[i].a-t)%x+data[i].b-data[i].a+1
	t=data[i].b+1
	i+=1
end
puts s
#end

# 499A

def read_next_line
  gets.chomp.split.map &:to_i
end

n, x = read_next_line
t, sum = 1, 0
n.times do
  l, r = read_next_line
  sum += (l - t) % x + r - l + 1
  t = r + 1
end
puts sum

# f = File.open('input.txt', 'r')
f = STDIN
n, x = f.gets.chomp.split.map &:to_i
res = 0
r0 = 0
n.times do
  l, r = f.gets.chomp.split.map &:to_i
  res += (l - r0 - 1) - ((l - r0 - 1) % x)
  r0 = r
end
puts r0 - res

n, x = gets.split.map(&:to_i)
cur = 1
tot = 0
n.times do
	l, r = gets.split.map(&:to_i)
	cur += x while cur + x <= l
	tot += r - cur + 1
	cur = r + 1
end
print tot

n, x = gets.split.map(&:to_i)
t = 1
q = 0
n.times do
  l, r = gets.split.map(&:to_i)
  t += x while t + x <= l
  while t <= r
    q += x
    t += x
  end
end
puts q

#!/usr/bin/env ruby
n,x=gets.split.map(&:to_i)
cur=0
ret=0
n.times{
	l,r=gets.split.map(&:to_i)
	ret+=r+1-l+(l-cur)%x
	cur=r+1
}
p ret

#!/usr/bin/env ruby
n,x=gets.split.map(&:to_i)
cur=0
ret=0
n.times{
	l,r=gets.split.map(&:to_i)
	ret+=r-l+(l-cur)%x
	cur=r
}
p ret

n, x = gets.chomp.split(/ /).map(&:to_i)
watch = 1
skip = 1
n.times do
    l, r = gets.chomp.split(/ /).map(&:to_i)
    skip += x while skip + x <= (l - watch)
    watch += r - l + (skip % x)
end
puts watch

n, x = gets.chomp.split(/ /).map(&:to_i)
watch = 1
n.times do
    l, r = gets.chomp.split(/ /).map(&:to_i)
    skip = 1
    skip += x while skip + x <= l
    watch += r - l + (skip % x)
end
puts watch

n, x = gets.chomp.split(/ /).map(&:to_i)
watch = 1
n.times do
    l, r = gets.chomp.split(/ /).map(&:to_i)
    skip = 1
    skip += x while skip + x <= l
    watch += r - l + (skip % x)
    puts "#{watch} #{skip}"
end
puts watch

#!/usr/bin/ruby
tokens = STDIN.gets.chomp.split(" ").map(&:to_i)
n = tokens[0]
x = tokens[1]
minute = 1
ans = 0
n.times do
    range = STDIN.gets.chomp.split(" ").map(&:to_i)
    while minute + x <= range[0] do
        minute += x
    end
    ans += range[1] - minute + 1
end

puts ans

n, x = gets.chomp.split(' ').map(&:to_i)
c = 1
total = 0
n.times do |i|
  l, r = gets.chomp.split(' ').map(&:to_i)
  while c + x <= l do c += x end
  total += r-l + 1
  total += l - c
end
puts total

n, x = gets.chomp.split(' ').map(&:to_i)
c = 1
total = 1
n.times do |i|
  l, r = gets.chomp.split(' ').map(&:to_i)
  while c + x <= l do c += x end
  total += r-l
  total += l - c
  c = r
end
puts total

read=lambda{ gets.split(" ").map{|x| x.to_i} }
n,x=read.call
#puts "#{n} #{x}"
ans=0
finish=0
for _ in 0...n
  l,r=read.call
  a=(l-1)/x
  b=r/x
  if b*x<r
    b+=1
  end
  if finish>a*x
    ans+=finish-a*x
  else
    ans+=(b-a)*x
  end
  finish=b*x
end
puts ans

read=lambda{ gets.split(" ").map{|x| x.to_i} }
n,x=read.call
#puts "#{n} #{x}"
ans=0
now=1
for _ in 0...n
  l,r=read.call
  ans+=(l-now)%x+(r-l)+1
end
puts ans

n, x = gets.split(' ').map(&:to_i)
pre = 1
ans = 0
n.times do
    l, r = gets.split(' ').map(&:to_i)
    ans += (l - pre) % x + r - l
    pre = r
end
print ans + 1, "\n";


Shubham has an array $$$a$$$ of size $$$n$$$, and wants to select exactly $$$x$$$ elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.Tell him whether he can do so.

The first line of the input contains a single integer $$$t$$$ $$$(1\le t \le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ $$$(1 \le x \le n \le 1000)$$$ — the length of the array and the number of elements you need to choose. The next line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 1000)$$$ — elements of the array.

For each test case, print "Yes" or "No" depending on whether it is possible to choose $$$x$$$ elements such that their sum is odd. You may print every letter in any case you want.

NoteFor $$$1$$$st case: We must select element $$$999$$$, and the sum is odd.For $$$2$$$nd case: We must select element $$$1000$$$, so overall sum is not odd.For $$$3$$$rd case: We can select element $$$51$$$.For $$$4$$$th case: We must select both elements $$$50$$$ and $$$51$$$  — so overall sum is odd.For $$$5$$$th case: We must select all elements  — but overall sum is not odd.

# cook your code here
t = gets.to_i
until t == 0
    x,y = gets.chomp.split().map { |e| e.to_i  }
    arr = gets.chomp.split().map { |e| e.to_i  }
    odd = 0;even = 0;
    for i in 0...arr.length()
        if(arr[i]%2 == 1)
            odd+=1;
        else
            even+=1;
        end
    end
    #print "%d %d" % [odd,even]
    #puts
    if(odd == 0)
        puts "No"
    else
        y-=1;
        odd-=1;
        if(y%2 == 0)
            if(odd%2 == 0)
                odd = odd
            else
                odd-=1
            end
            if(odd >= y or even >= (y-odd))
                puts "Yes"
            else
                puts "No"
            end
        else
            if(even == 0)
                puts "No"
            else
                y-=1
                even-=1
                if(odd%2 == 0)
                    odd = odd
                else
                    odd-=1
                end
                if(odd >= y or even >= (y-odd))
                    puts "Yes"
                else
                    puts "No"
                end
            end
        end
    end
    t-=1
end

num_tests = gets.chomp.to_i

def odd_selection(n,arr)
  odds = evens = 0
  arr.each { |el| el.odd? ? odds += 1 : evens += 1 }
  return "No" if evens == 0 && n.even?
  (n - max_odd_num(odds) <= evens && odds > 0) ? "Yes" : "No"
end

def max_odd_num(num)
  return num.odd? ? num : num - 1
end

i = 0
while i < num_tests
  a,b = gets.chomp.split(" ").map(&:to_i)
  arr = gets.chomp.split(" ").map(&:to_i)
  puts odd_selection(b,arr)
  i += 1
end

t = 0
t = gets.chomp.to_i
#puts "Value of t is ",t
while t > 0
    i = 0
    num = 0
    n = 0
    x = 0
    odd = 0
    n, x = gets.chomp.split(' ').map{|a| a.to_i}
    ar = gets.chomp.split(' ').map{|a| a.to_i}
    for i in 0..n-1
        #puts ar[i]
        if ar[i]%2 != 0
            odd = odd + 1
        end
    end
    #puts "The value of odd is", odd
    if odd >= 1 && !(x==n && odd%2 ==0) && !(n==odd && x%2==0 )
        puts "YES"
    else
        puts  "NO"
    end
t = t-1
end

gets.to_i.times{
  n,x=gets.split.map(&:to_i)
  a=b=0
  gets.split.map{|x|x.to_i%2==0 ? b+=1:a+=1}
  puts 1.step(a, 2).any?{|i| x-i>=0 and x-i<=b} ? "Yes" : "No"
}

def analyze(a, x)
  even_count = 0
  odd_count = 0
  a.each do |item|
    if item % 2 == 0
      even_count +=1
    else
      odd_count +=1
    end
  end

  return odd_count > 0 if x <= 1

  return false if odd_count < 1

  if x % 2 == 0
    return false if even_count < 1

    odd_count -= 1
    even_count -= 1

    odd_count / 2 + even_count / 2  >= (x -2) / 2
  else
    odd_count -= 1

    odd_count / 2 + even_count / 2  >= (x -1) / 2
  end
end

t = gets.chomp.to_i
res = []
(1..t).each do |_t|
  n, x = gets.chomp.split(' ').map{|a| a.to_i}
  ar = gets.chomp.split(' ').map{|a| a.to_i}
  res << analyze(ar, x)
end

res.each do |r|
  puts (r ? 'YES' : 'NO')
end

def solve
  _, k = gets.strip.split(' ').map(&:to_i)
  arr = gets.strip.split(' ').map(&:to_i)
  ev = arr.select { |e| e.even? }
  od = arr.select { |e| e.odd? }
  while !od.empty?
    if od.size.odd? && od.size <= k
      break
    end
    od.pop
  end
  if od.size + ev.size >= k && !od.size.zero?
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times { solve  }

# cook your code here
t = gets.to_i
until t == 0
    x,y = gets.chomp.split().map { |e| e.to_i  }
    arr = gets.chomp.split().map { |e| e.to_i  }
    odd = 0;even = 0;
    for i in 0...arr.length()
        if(arr[i]%2 == 1)
            odd+=1;
        else
            even+=1;
        end
    end
    #print "%d %d" % [odd,even]
    #puts
    if(odd == 0)
        puts "No"
    else
        y-=1;
        odd-=1;
        if(even >= y)
            puts "Yes"
        else
            if((y-even)%2)
                y = y - even + 1;
            else
                y = y - even;
            end
            if(odd >= y and y%2 == 0)
                puts "Yes"
            else
                puts "No"
            end
        end
    end
    t-=1
end

# cook your code here
t = gets.to_i
until t == 0
    x,y = gets.chomp.split().map { |e| e.to_i  }
    arr = gets.chomp.split().map { |e| e.to_i  }
    odd = 0;even = 0;
    for i in 0...arr.length()
        if(arr[i]%2 == 1)
            odd+=1;
        else
            even+=1;
        end
    end
    #print "%d %d" % [odd,even]
    #puts
    if(odd == 0)
        puts "No"
    else
        y-=1;
        odd-=1;
        if(even >= y)
            puts "Yes"
        else
            if((y-even)%2 == 0)
                y = y - even + 1;
            else
                y = y - even;
            end
            if(odd >= y and y%2 == 0)
                puts "Yes"
            else
                puts "No"
            end
        end
    end
    t-=1
end

# cook your code here
t = gets.to_i
until t == 0
    x,y = gets.chomp.split().map { |e| e.to_i  }
    arr = gets.chomp.split().map { |e| e.to_i  }
    odd = 0;even = 0;
    for i in 0...arr.length()
        if(arr[i]%2 == 1)
            odd+=1;
        else
            even+=1;
        end
    end
    #print "%d %d" % [odd,even]
    #puts
    if(odd == 0)
        puts "No"
    else
        y-=1;
        odd-=1;
        if(even >= y)
            puts "Yes"
        else
            if((y-even)%2 == 1)
                y = y - even + 1;
            else
                y = y - even;
            end
            # puts y
            if(odd >= y and y%2 == 0)
                puts "Yes"
            else
                puts "No"
            end
        end
    end
    t-=1
end

# cook your code here
t = gets.to_i
until t == 0
    x,y = gets.chomp.split().map { |e| e.to_i  }
    arr = gets.chomp.split().map { |e| e.to_i  }
    odd = 0;even = 0;
    for i in 0...arr.length()
        if(arr[i]%2 == 1)
            odd+=1;
        else
            even+=1;
        end
    end
    #print "%d %d" % [odd,even]
    #puts
    if(odd == 0)
        puts "No"
    else
        y-=1;
        odd-=1;
        if(even >= y)
            puts "Yes"
        else
            if((y-even)%2)
                y = y - even + 1;
            else
                y = y - even;
            end
            if(odd >= y)
                puts "Yes"
            else
                puts "No"
            end
        end
    end
    t-=1
end

num_tests = gets.chomp.to_i

def odd_selection(n,arr)
  odds = evens = 0
  arr.each { |el| el.odd? ? odds += 1 : evens += 1 }
  (n - max_odd_num(odds) <= evens && odds > 0) ? "Yes" : "No"
end

def max_odd_num(num)
  return num.odd? ? num : num - 1
end

i = 0
while i < num_tests
  a,b = gets.chomp.split(" ").map(&:to_i)
  arr = gets.chomp.split(" ").map(&:to_i)
  puts odd_selection(b,arr)
  i += 1
end

num_tests = gets.chomp.to_i

def odd_selection(n,arr)
  odds = evens = 0
  arr.each { |el| el.odd? ? odds += 1 : evens += 1 }
  (n - max_odd_num(odds) <= evens && odds > 0) ? "Yes" : "No"
end

def max_odd_num(num)
  return num.odd? ? num : num - 1
end

i = 0
while i < num_tests
  a,b = gets.chomp.split(" ").map(&:to_i)
  arr = gets.chomp.split(" ").map(&:to_i)
  p odd_selection(b,arr)
  i += 1
end

t = 0
t = gets.to_i

while t > 0
    odd = 0
    n = 0
    x = 0
    n = gets.to_i
    x = gets.to_i
    for i in 1..n
        a = gets.to_i
        if a%2 != 0
            odd = odd + 1
        end
    end
    if odd >= 1 && !(x==n && odd%2 ==0) && !(n==odd && x%2==0 )
        puts "YES"
    else
        puts  "NO"
    end
t = t-1
end

gets.to_i.times{
  n,x=gets.split.map(&:to_i)
  a=b=0
  gets.split.map{|x|x.to_i%2==0 ? b+=1:a+=1}
  puts 1.step(a, 2).any?{|i| x-i<=b} ? "Yes" : "No"
}

def analyze(a, x)
  even_count = 0
  odd_count = 0
  a.each do |item|
    if item % 2 == 0
      even_count +=1
    else
      odd_count +=1
    end
  end

  return odd_count > 0 if x <= 1

  if x % 2 == 1
    # x is odd
    even_count -= 1 if even_count % 2 == 1

    even_count + odd_count >= x
  else

    # x is even

    return false if odd_count < 1 || even_count < 1

    # one pair
    odd_count -= 1
    even_count -= 1

    # rest pairs

    even_count -= 1 if even_count % 2 == 1
    odd_count -= 1 if odd_count % 2 == 1

    even_count + odd_count >= x - 2
  end
end

t = gets.chomp.to_i
res = []
(1..t).each do |_t|
  n, x = gets.chomp.split(' ').map{|a| a.to_i}
  ar = gets.chomp.split(' ').map{|a| a.to_i}
  res << analyze(ar, x)
end

res.each do |r|
  puts (r ? 'YES' : 'NO')
end

def analyze(a, x)
  even_count = 0
  odd_count = 0
  a.each do |item|
    if item % 2 == 0
      even_count +=1
    else
      odd_count +=1
    end
  end

  return odd_count > 0 if x <= 1

  return false if odd_count < 1

  if x % 2 == 0
    odd_count -= 1
    even_count -= 1

    odd_count / 2 + even_count / 2  >= (x -2) / 2
  else
    odd_count -= 1

    odd_count / 2 + even_count / 2  >= (x -1) / 2
  end
end

t = gets.chomp.to_i
res = []
(1..t).each do |_t|
  n, x = gets.chomp.split(' ').map{|a| a.to_i}
  ar = gets.chomp.split(' ').map{|a| a.to_i}
  res << analyze(ar, x)
end

res.each do |r|
  puts (r ? 'YES' : 'NO')
end

def analyze(a, x)
  even_count = 0
  odd_count = 0
  a.each do |item|
    if item % 2 == 0
      even_count +=1
    else
      odd_count +=1
    end
  end

  return odd_count > 0 if x <= 1

  return false if odd_count < 1

  odd_count -= 1;

  odd_count / 2 + even_count / 2 + even_count % 2 >= x -1
end

t = gets.chomp.to_i
res = []
(1..t).each do |_t|
  n, x = gets.chomp.split(' ').map{|a| a.to_i}
  ar = gets.chomp.split(' ').map{|a| a.to_i}
  res << analyze(ar, x)
end

res.each do |r|
  puts (r ? 'YES' : 'NO')
end

def solve
  _, k = gets.strip.split(' ').map(&:to_i)
  arr = gets.strip.split(' ').map(&:to_i)
  ev = arr.select { |e| e.even? }
  od = arr.select { |e| e.odd? }
  od.pop if od.size.even? && !od.size.zero?
  if od.size + ev.size >= k && !od.size.zero?
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times { solve  }


You've got a string $$$a_1, a_2, \dots, a_n$$$, consisting of zeros and ones.Let's call a sequence of consecutive elements $$$a_i, a_{i + 1}, \ldots, a_j$$$ ($$$1\leq i\leq j\leq n$$$) a substring of string $$$a$$$. You can apply the following operations any number of times:  Choose some substring of string $$$a$$$ (for example, you can choose entire string) and reverse it, paying $$$x$$$ coins for it (for example, «0101101» $$$\to$$$ «0111001»);  Choose some substring of string $$$a$$$ (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying $$$y$$$ coins for it (for example, «0101101» $$$\to$$$ «0110001»). You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.What is the minimum number of coins you need to spend to get a string consisting only of ones?

The first line of input contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \leq n \leq 300\,000, 0 \leq x, y \leq 10^9$$$) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring). The second line contains the string $$$a$$$ of length $$$n$$$, consisting of zeros and ones.

Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print $$$0$$$, if you do not need to perform any operations.

NoteIn the first sample, at first you need to reverse substring $$$[1 \dots 2]$$$, and then you need to invert substring $$$[2 \dots 5]$$$. Then the string was changed as follows:«01000» $$$\to$$$ «10000» $$$\to$$$ «11111».The total cost of operations is $$$1 + 10 = 11$$$.In the second sample, at first you need to invert substring $$$[1 \dots 1]$$$, and then you need to invert substring $$$[3 \dots 5]$$$. Then the string was changed as follows:«01000» $$$\to$$$ «11000» $$$\to$$$ «11111».The overall cost is $$$1 + 1 = 2$$$.In the third example, string already consists only of ones, so the answer is $$$0$$$.

N, X, Y = gets.split.map(&:to_i)
num = gets.chomp.split('1').count{|s| s.length>0}
if num == 0
    puts 0
else
    puts Y + (num-1) * [X, Y].min
end

n, x, y = gets.strip.split.map(&:to_i)
str = gets.strip
cstr = str[0]
str.each_char do |c|
  cstr << c if c != cstr[-1]
end

zc = [y]
oc = [0]
n = cstr.size
1.upto(n).each do |i|
  oc << zc[i-1]
  if i%2==1
    zc << zc[i-1]
  else
    zc << [(y+zc[i-2]), (x+zc[i-2])].min
  end
end

puts (str[0]=='0' ? zc[n-1] : oc[n-1])

n, x, y = gets.strip.split.map(&:to_i)
str = gets.strip

nzb = 0
0.upto(n-2).each do |i|
  nzb += 1 if str[i] == '0' && str[i+1]=='1'
end
nzb += 1 if n>1 && str[-1] =='0'

ans = nzb * y
1.upto(nzb-1).each do |nx|
  ans = [ans, (x*nx) + ((nzb-nx)*y)].min
end
puts ans


You are given an integer array of length $$$n$$$.You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to $$$[x, x + 1, \dots, x + k - 1]$$$ for some value $$$x$$$ and length $$$k$$$.Subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. You can erase any elements, not necessarily going successively. The remaining elements preserve their order. For example, for the array $$$[5, 3, 1, 2, 4]$$$ the following arrays are subsequences: $$$[3]$$$, $$$[5, 3, 1, 2, 4]$$$, $$$[5, 1, 4]$$$, but the array $$$[1, 3]$$$ is not.

The first line of the input containing integer number $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array. The second line of the input containing $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array itself.

On the first line print $$$k$$$ — the maximum length of the subsequence of the given array that forms an increasing sequence of consecutive integers. On the second line print the sequence of the indices of the any maximum length subsequence of the given array that forms an increasing sequence of consecutive integers.

NoteAll valid answers for the first example (as sequences of indices):   $$$[1, 3, 5, 6]$$$  $$$[2, 3, 5, 6]$$$ All valid answers for the second example:   $$$[1, 4]$$$  $$$[2, 5]$$$  $$$[3, 6]$$$ All valid answers for the third example:   $$$[1]$$$  $$$[2]$$$  $$$[3]$$$  $$$[4]$$$ All valid answers for the fourth example:   $$$[1, 2, 3, 7, 8, 9]$$$

Node = Struct.new(:idx, :len, :next) do
  def append(idx)
    Node.new(idx, self.len + 1, self)
  end
end

EMPTY = Node.new(nil, 0, nil)

def find_max_streak(as)
  streaks = {}
  max_streak = EMPTY

  as.each.with_index do |a, q|
    i = q + 1

    streak = (streaks[a-1] || EMPTY).append(i)

    streaks[a] = streak

    if max_streak.len < streak.len
      max_streak = streak
    end

  end

  max_streak
end

def solution

  read_int

  as = read_ints

  ms = find_max_streak(as)

  rev = []
  crt = ms
  while crt.idx
    rev.unshift crt.idx
    crt = crt.next
  end

  puts rev.size
  puts rev.join(' ')

end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

def solution

  indices = {}
  streaks = {}

  max_streak = 0
  max_streak_tail = nil

  read_int

  as = read_ints

  as.each.with_index do |a, q|
    i = q + 1

    streak = (streaks[a-1] || 0) + 1

    streaks[a] = streak
    indices[a] = indices[a] || i

    next if (streak[a+1] || 0) > streak

    if max_streak < streak
      max_streak = streak
      max_streak_tail = a
    end

  end

  max_streak_head = max_streak_tail - max_streak + 1

  indices = (max_streak_head..max_streak_tail).map{ |a| indices[a] }

  puts max_streak
  puts indices.join(' ')

end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

def find_max_streak(as)
  indices = {}
  streaks = {}
  max_streak = 0
  max_streak_tail = nil

  as.each.with_index do |a, q|
    i = q + 1

    streak = (streaks[a-1] || 0) + 1

    if (streaks[a] || 0) < streak
      streaks[a] = streak
      indices[a] = i
    end

    if max_streak < streak
      max_streak = streak
      max_streak_tail = a
    end

  end

  max_streak_head = max_streak_tail - max_streak + 1

  indices = (max_streak_head..max_streak_tail).map{ |a| indices[a] }
end

def solution

  read_int

  as = read_ints

  ms = find_max_streak(as)

  puts ms.size
  puts ms.join(' ')

end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

def solution

  indices = {}
  streaks = {}

  max_streak = 0
  max_streak_tail = nil

  read_int

  as = read_ints

  as.each.with_index do |a, q|
    i = q + 1

    streak = (streaks[a-1] || 0) + 1

    streaks[a] = streak
    indices[a] = i

    if max_streak < streak
      max_streak = streak
      max_streak_tail = a
    end

  end

  max_streak_head = max_streak_tail - max_streak + 1

  indices = (max_streak_head..max_streak_tail).map{ |a| indices[a] }

  puts max_streak
  puts indices.join(' ')

end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

def solution

  indices = {}
  streaks = {}

  max_streak = 0
  max_streak_tail = nil

  read_int

  as = read_ints

  as.each.with_index do |a, q|
    i = q + 1

    streak = (streaks[a-1] || 0) + 1

    streaks[a] = streak
    indices[a] = i unless indices[a]

    if max_streak < streak
      max_streak = streak
      max_streak_tail = a
    end

  end

  max_streak_head = max_streak_tail - max_streak + 1

  indices = (max_streak_head..max_streak_tail).map{ |a| indices[a] }

  puts max_streak
  puts indices.join(' ')

end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']


Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types:   replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4);  swap any pair of digits in string a. Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task.

The first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 105.

Print on the single line the single number — the minimum number of operations needed to convert string a into string b.

NoteIn the first sample it is enough simply to swap the first and the second digit.In the second sample we should replace the second digit with its opposite.In the third number we should replace all three digits with their opposites.

$a = gets.chomp
$b = gets.chomp
plmi = 0
diffcnt = 0
for i in 0..$a.length
  ac = $a.slice(i,1)
  bc = $b.slice(i,1)
  next if ac == bc
  diffcnt += 1
  if ac == "4"
    plmi += 1
  else
    plmi -= 1
  end
end
puts (diffcnt-plmi.abs)/2+plmi.abs

a,b=2.times.map{gets.chomp.chars.to_a}
c4=c7=0
a.size.times{|i|
	unless a[i]==b[i]
		a[i]==?4 ? c4+=1 : c7+=1
	end
}
p [c4,c7].max

a = gets
b = gets
ea = a.each_char

h = {:aa => 0, :bb => 0}
b.each_char do |bb|
  aa = ea.next
  next if aa == bb
  aa == "4" ?  h[:aa] += 1 : h[:bb] += 1
end

puts [h[:aa], h[:bb]].max

a=gets.bytes.to_a
b=gets.bytes.to_a
cnt=[0,0]
a.length.times{|i| cnt[a[i]==52?1:0]+=1 if a[i]!=b[i]}
p cnt[0]+cnt[1]-cnt.min

a=gets.split[0].bytes.to_a
b=gets.split[0].bytes.to_a
n=a.length
input=Array.new
n.times{|i|
        input.push([a[i]==52?1:0,b[i]==52?1:0])
}
cnt1=0
cnt2=0
input.each{|t|
        cnt1+=1 if t[0]!=t[1] && t[0]==1
        cnt2+=1 if t[0]!=t[1] && t[0]==0
}
p [cnt1,cnt2].min+(cnt1+cnt2)-[cnt1,cnt2].min*2

a=gets
b=gets
x = a.split('').zip(b.split('')).inject([]) { |m, (x, y)| x != y ? m << x : m }
p x.length - %w[4 7].map { |d| x.count(d) }.min

a=gets.chomp.split("").map{|i|i.to_i}
b=gets.chomp.split("").map{|i|i.to_i}
c=(a.count(4)-b.count(4)).abs
i=0
l=0

if c>0
loop do
if a[i]!=b[i]
a[i]=b[i]
l+=1
end
i+=1
break if l>=c
end
end
length=a.length
swap=0
loop do
if a[i]!=b[i]
a[i]=b[i]
swap+=1
end
i+=1
break if i>=length
end

puts"#{c+swap/2}"

a, b = 2.times.map{gets.chars.to_a}
c = 0
a.zip(b){|i, j| c += 1 if i != j}
p c + (a.count('4') - b.count('4')).abs >> 1
__END__

a=gets.chomp
b=gets.chomp
counts=[0,0]
a.split("").each_index do |i|
 if a[i]=="4" && b[i]=="7"
   counts[0]=counts[0]+1
 elsif a[i]=="7" && b[i]=="4"
   counts[1]=counts[1]+1
 end
end
puts counts.max

a = gets.chomp
b = gets.chomp
x = 0
y = 0
(0...a.size).each do |i|
    if a[i] == '7' and b[i] == '4'
        x += 1
    elsif a[i] == '4' and b[i] == '7'
        y += 1
    end
end
puts [x,y].max

n = m = 0
a = gets.chomp.chars
b = gets.chomp.chars
(0...a.size).each { |i|
  if a[i] != b[i]
    if a[i] == '4'
      n += 1
    else
      m += 1
    end
  end
}
puts [n, m].max

a, b = gets.chomp.split("").map(&:to_i), gets.split("").map(&:to_i)
f, s = 0, 0
a.length.times{ |i|
 next if a[i] == b[i]
 if a[i]!=4
  f += 1
 else
  s += 1
 end
}
p [f, s].min + (f-s).abs

input = STDIN.read.split("\n")
str1, str2 = input[0].split(//).map(&:to_i), input[1].split(//).map(&:to_i)

str1.length.times {|x|
	if str1[x] == str2[x]
		str1[x] = nil
		str2[x] = nil
	end
}

n4 = str1.count(4)
n7 = str1.count(7)

moves = n4 <= n7 ? n4 : n7
STDOUT.puts moves += (n4 - n7).abs

$a = gets.chomp
$b = gets.chomp
plmi = 0
diffcnt = 0
for i in 0..$a.length
  ac = $a.slice(i,1)
  bc = $b.slice(i,1)
  next if ac == bc
  diffcnt += 1
  if ac == "4"
    plmi += 1
  else
    plmi -= 1
  end
end
puts diffcnt/2+plmi.abs

a = gets
b = gets
ea = a.each_char

ret = 0
b.each_char do |c|
  l = ea.next
  ret += 1 unless c == l
end

puts ret

a=gets.bytes.to_a
b=gets.bytes.to_a
cnt=[0,0]
a.length.times{|i| cnt[a[i]=="4"?1:0]+=1 if a[i]!=b[i]}
p cnt[0]+cnt[1]-cnt.min

input = STDIN.read.split("\n")
str1, str2 = input[0].split(//).map(&:to_i), input[1].split(//).map(&:to_i)

count = 0

str1.length.times {|x| str1.delete_at x if str1[x] == str2[x] }

n4 = str1.count(4)
n7 = str1.count(7)

moves = n4 <= n7 ? n4 : n7
STDOUT.puts moves += (n4 - n7).abs

input = STDIN.read.split("\n")
str1, str2 = input[0], input[1]

count = 0
skip = false

str1.length.times do |i|

	if str1[i] == str2[i] or skip
		skip = false
		next
	end

	if str1[i + 1].nil?
		count += 1
		break
	end

	if str1[i + 1] != str2[i + 1] and str1[i] != str1[i + 1]
		count += 1
		skip = true
	else
		count += 1
	end

end

STDOUT.puts count


Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of the region that will be cleared from snow. Help him.

The first line of the input contains three integers — the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integers — coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.

Print a single real value number — the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample snow will be removed from that area:

def sqr(x)
    return x*x
end

n,$ox,$oy = gets.split.map(&:to_i)
x = Array.new(n+1){|e|e=0}
y = Array.new(n+1){|e|e=0}

def calc(x1,y1,x2,y2)
    cross = (x2-x1)*($ox-x1) + (y2-y1)*($oy-y1)
    return sqr($ox-x1) + sqr($oy-y1) if cross <= 0
    d2 = (x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+0.0
    return sqr($ox-x2) + sqr($oy-y2) if cross >= d2
    r = cross/d2
    px = x1+(x2-x1)*r
    py = y1+(y2-y1)*r
    #p px,py
    return sqr($ox-px)+sqr($oy-py)
end

dismin=12100000000.0**2
dismax=-1.0

for i in 1..n
    x[i],y[i] = gets.split.map(&:to_i)
    dis = sqr(x[i]-$ox)+sqr(y[i]-$oy)
    dismin = dis if (dis<dismin)
    dismax = dis if (dis>dismax)
end
x[0],y[0]=x[n],y[n]
for i in 1..n
    dis = calc(x[i-1],y[i-1],x[i],y[i])
    dismin = dis if (dis<dismin)
end

p (dismax-dismin)*Math::PI

def sqr(x)
    return x*x
end

n,ox,oy = gets.split.map(&:to_i)
x = Array.new(n+1){|e|e=0}
y = Array.new(n+1){|e|e=0}

dismin=12100000000**2
dismax=-1

for i in 1..n
    x[i],y[i] = gets.split.map(&:to_i)
    dis = sqr(x[i]-ox)+sqr(y[i]-oy)
    dismin = dis if (dis<dismin)
    dismax = dis if (dis>dismax)
end
p (dismax-dismin)*Math::PI


Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day?

Output one integer  — the maximum number of breaks.

NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks.

n,l,a = gets.strip.split.map(&:to_i)
intervals = [0]

n.times do
  ti, li = gets.strip.split.map(&:to_i)
  intervals << ti
  intervals << ti + li
end
intervals << l

ans = 0
im = intervals.size / 2
i = 0
im.times do
  s = intervals[i]
  e = intervals[i+1]
  ans += (e-s)/a
  i+=2
end
puts ans

n,l,a = gets.split.map(&:to_i)
ans = 0
t = [[0,0]] + n.times.map{gets.split.map(&:to_i)} + [[l,0]]

for i in 0..n
  ans += (t[i+1][0]-t[i][0]-t[i][1])/a
end

puts ans

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

n = nla[0]
l = nla[1]
a = nla[2]

arr = []
n.times do
  arr.push gets.chomp.split(" ").map(&:to_i)
end

arr.sort_by{|x| x[0]}

if n==0
  puts l/a
  exit
end

first = arr[0][0]/a
last = (l-(arr[n-1][0]+arr[n-1][1]))/a

ans = 0

arr.each_with_index do |x,i|
  next if i==n-1
  ans += (arr[i+1][0]-(x[0]+x[1]))/a
end

ans += (first+last)
puts ans

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

n = nla[0]
l = nla[1]
a = nla[2]

arr = []
n.times do
  arr.push gets.chomp.split(" ").map(&:to_i)
end

arr.sort_by{|x| x[0]}

if n==0
  puts l/a
  exit
end

first = arr[0][0]/a
last = (l-arr[n-1][1])/a

ans = 0

arr.each_with_index do |x,i|
  next if i==n-1
  ans += (arr[i+1][0]-x[1])/a
end

ans += (first+last)
puts ans


Shohag has an integer sequence $$$a_1, a_2, \ldots, a_n$$$. He can perform the following operation any number of times (possibly, zero):  Select any positive integer $$$k$$$ (it can be different in different operations).  Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two elements) and insert $$$k$$$ into the sequence at this position.  This way, the sequence $$$a$$$ changes, and the next operation is performed on this changed sequence. For example, if $$$a=[3,3,4]$$$ and he selects $$$k = 2$$$, then after the operation he can obtain one of the sequences $$$[\underline{2},3,3,4]$$$, $$$[3,\underline{2},3,4]$$$, $$$[3,3,\underline{2},4]$$$, or $$$[3,3,4,\underline{2}]$$$.Shohag wants this sequence to satisfy the following condition: for each $$$1 \le i \le |a|$$$, $$$a_i \le i$$$. Here, $$$|a|$$$ denotes the size of $$$a$$$.Help him to find the minimum number of operations that he has to perform to achieve this goal. We can show that under the constraints of the problem it's always possible to achieve this goal in a finite number of operations.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$)  — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the initial length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the sequence.

For each test case, print a single integer  — the minimum number of operations needed to perform to achieve the goal mentioned in the statement.

NoteIn the first test case, we have to perform at least one operation, as $$$a_2=3>2$$$. We can perform the operation $$$[1, 3, 4] \rightarrow [1, \underline{2}, 3, 4]$$$ (the newly inserted element is underlined), now the condition is satisfied.In the second test case, Shohag can perform the following operations:$$$[1, 2, 5, 7, 4] \rightarrow [1, 2, \underline{3}, 5, 7, 4] \rightarrow [1, 2, 3, \underline{4}, 5, 7, 4] \rightarrow [1, 2, 3, 4, 5, \underline{3}, 7, 4]$$$.In the third test case, the sequence already satisfies the condition.

t = gets.to_i
t.times{
n = gets.to_i
z = gets.split.map &:to_i
x = []
z.size.times{|i|x<<z[i] - i}
puts x.max - 1
}


Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.

The first line of the input data contains an integer n (1 ≤ n ≤ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).

Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).

NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].

n = gets.chomp.to_i
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
ret = n
samecnt = 0
for i in 1..n-1
	if (ar[i] == ar[i-1])
		samecnt += 1
	else
		ret += ((samecnt+1)*samecnt)/2
		samecnt = 0
	end
end
ret += ((samecnt+1)*samecnt)/2
puts ret

gets
a=gets.split.map{|x| x.to_i}
last, cnt = -(10**10), 0
ans = 0

a.each do |x|
	if last != x then
		ans += cnt*(cnt+1)
		last = x
		cnt = 1
	else
		cnt += 1
	end
end

p (ans+cnt*(cnt+1))/2

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

def getis;gets.split.map(&:to_i);end
def log(m); warn(m); end

gets
nums = getis

i=0
pre=nil
c=1
log nums
nums.each do |n|
  log [pre, n]
  if pre == n
    c+=1
    i+=c
  else
    pre=n
    c=1
    i+=1
  end
end
puts i

n=gets.to_i
a=gets.split.map &:to_i;
z=i=j=0;
while i<n
	j+=1 while j<n&&a[i]==a[j]
	z+=(j-i)*(j-i+1)/2
	i=j
end
p z

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

count = arr.length

arr.chunk{|x| x}.each do |r|
	l = r[1].length
 	if l > 1
 		count += (l-1).downto(1).inject(0,:+)
 	end
end
puts count

n = gets.to_i
a = gets.split

prev = 2 * 1e9.to_i
sz = 0
ans = 0
a.each do |x|
  if x == prev
    sz += 1
  else
    ans += sz * (sz + 1) / 2
    sz = 1
    prev = x
  end
end
puts ans + sz * (sz + 1) / 2

n = gets.chomp.to_i
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
ar.sort!
ret = n
samecnt = 0
for i in 1..n-1
	if (ar[i] == ar[i-1])
		samecnt += 1
	else
		ret += ((samecnt+1)*samecnt)/2
		samecnt = 0
	end
end
ret += ((samecnt+1)*samecnt)/2
puts ret


Long time ago there was a symmetric array $$$a_1,a_2,\ldots,a_{2n}$$$ consisting of $$$2n$$$ distinct integers. Array $$$a_1,a_2,\ldots,a_{2n}$$$ is called symmetric if for each integer $$$1 \le i \le 2n$$$, there exists an integer $$$1 \le j \le 2n$$$ such that $$$a_i = -a_j$$$.For each integer $$$1 \le i \le 2n$$$, Nezzar wrote down an integer $$$d_i$$$ equal to the sum of absolute differences from $$$a_i$$$ to all integers in $$$a$$$, i. e. $$$d_i = \sum_{j = 1}^{2n} {|a_i - a_j|}$$$.Now a million years has passed and Nezzar can barely remember the array $$$d$$$ and totally forget $$$a$$$. Nezzar wonders if there exists any symmetric array $$$a$$$ consisting of $$$2n$$$ distinct integers that generates the array $$$d$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases.  The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$d_1, d_2, \ldots, d_{2n}$$$ ($$$0 \le d_i \le 10^{12}$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "YES" in a single line if there exists a possible array $$$a$$$. Otherwise, print "NO". You can print letters in any case (upper or lower).

NoteIn the first test case, $$$a=[1,-3,-1,3]$$$ is one possible symmetric array that generates the array $$$d=[8,12,8,12]$$$.In the second test case, it can be shown that there is no symmetric array consisting of distinct integers that can generate array $$$d$$$.

gets.to_i.times do
  n=gets.to_i
  d=gets.split.map(&:to_i).sort
  f=true
  n.times do |i|
    if d[2*i]!=d[2*i+1]
      f=false
      break
    end
  end
  if !f
    puts "NO"
    next
  end
  q=0
  qq=[]
  (n-1).downto(0) do |i|
    if (d[2*i]-q) % ((i+1)*2)!=0
      f=false
      break
    else
      qq << (d[2*i]-q) / (i+1)
      q+=(d[2*i]-q) / (i+1)
    end
  end
  if f&&qq.size==qq.uniq.size&&qq[-1]>0
    puts "YES"
  else
    puts "NO"
  end
end


Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?

The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day.  Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree.

Print a single integer — the maximum number of fruit that Valera can collect.

NoteIn the first sample, in order to obtain the optimal answer, you should act as follows.   On the first day collect 3 fruits from the 1-st tree.  On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree.  On the third day collect the remaining fruits from the 2-nd tree.  In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither.

#!/usr/bin/ruby
n,v=gets.split.map(&:to_i)
a=n.times.map{gets.split.map(&:to_i)}
ma=a.max[0]
m=[0]*(ma+2)
a.each{|x,y|m[x]+=y}
r=0
1.step(ma+1){|i|
	avail=m[i-1]+m[i]
	gather=[avail,v].min
	r+=gather
	x=[m[i-1],gather].min
	m[i-1]-=x
	gather-=x
	m[i]-=gather
}
p r

n,v=gets.split.map(&:to_i)
d=[0]*3001
n.times do
  a,b=gets.split.map(&:to_i)
  d[a-1]+=b
end
s=r=0
3001.times do |i|
  e=[r,v].min
  f=[v-e,d[i]].min
  s+=e+f
  r=d[i]-f
end
p s

n, v = gets.split.map(&:to_i)
x = [0] * 3001
n.times do
  pos, value = gets.split.map(&:to_i)
  x[pos - 1] += value
end

s = r = 0
3001.times do |i|
  e = [r, v].min
  f = [x[i], v - e].min
  s += e + f
  r = x[i] - f
end
p s

n,v = gets.split.map(&:to_i)
ripe_on_day = Array.new(3010, 0)
(0...n).each { |_|
  day,amount = gets.split.map(&:to_i)
  ripe_on_day[day] += amount
}
puts ripe_on_day.inject(0) { |memo, value|
  harvest = [memo[1] + value, v].min
  take_new_fruits = [0, v - memo[1]].max
  [memo[0] + harvest, [0, value - take_new_fruits].max]
}[0]

n, v = gets.split.collect{|i| i.to_i}
num = Hash.new(0)
(0...n).each do
    tmp = gets.split.collect{|i| i.to_i}
    num[tmp[0]] += tmp[1]
end
ans = 0
(1..3001).each do |i|
    tmp = [num[i-1], v].min
    ans += tmp
    tmp = v-tmp
    if tmp > 0
        if tmp >= num[i]
            ans += num[i]
            num[i] = 0
        else
            ans += tmp
            num[i] -= tmp
        end
    end
end
puts ans


Nikolay got a string $$$s$$$ of even length $$$n$$$, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from $$$1$$$ to $$$n$$$.He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arbitrary number of times (possibly, zero): choose some position in his string and replace the letter on this position with the other letter (i.e. replace 'a' with 'b' or replace 'b' with 'a'). Nikolay can use no letters except 'a' and 'b'.The prefix of string $$$s$$$ of length $$$l$$$ ($$$1 \le l \le n$$$) is a string $$$s[1..l]$$$.For example, for the string $$$s=$$$"abba" there are two prefixes of the even length. The first is $$$s[1\dots2]=$$$"ab" and the second $$$s[1\dots4]=$$$"abba". Both of them have the same number of 'a' and 'b'.Your task is to calculate the minimum number of operations Nikolay has to perform with the string $$$s$$$ to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.

The first line of the input contains one even integer $$$n$$$ $$$(2 \le n \le 2\cdot10^{5})$$$ — the length of string $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$, which consists only of lowercase Latin letters 'a' and 'b'.

In the first line print the minimum number of operations Nikolay has to perform with the string $$$s$$$ to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'. In the second line print the string Nikolay obtains after applying all the operations. If there are multiple answers, you can print any of them.

NoteIn the first example Nikolay has to perform two operations. For example, he can replace the first 'b' with 'a' and the last 'b' with 'a'. In the second example Nikolay doesn't need to do anything because each prefix of an even length of the initial string already contains an equal amount of letters 'a' and 'b'.

def anti(c)
  return 'b' if c == 'a'

  'a'
end
_ = gets.chomp
s = gets.chomp
n = 0
tmp = s.split('').each_slice(2).to_a
tmp.each_with_index do |el, ind|
  if el[0] == el[1]
    tmp[ind] = [el[0], anti(el[1])]
    n += 1
  end
end
puts(n)
puts(tmp.flatten.join(''))

n = gets.chomp.to_i
s = gets.chomp.split('')
ans = 0
n.times do |i|
    if i.odd?
        c = s[i - 1]
        if c == 'a'
            c = 'b'
        else
            c = 'a'
        end
        if s[i] != c
            ans += 1
        end
        s[i] = c
    end
end
puts ans
puts s.join('')

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

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

n = inp[0]
s = gets.chomp.split("")
f = false
ans = 0
s.each.with_index do |c, i|
  if(i.odd?)
    if(c == "a")
      if(f)
        s[i] = "b"
        ans += 1
      end
    else
      if(!f)
        s[i] = "a"
        ans += 1
      end
    end
    f = false
  else
    f = true if c == "a"
  end
end
p ans
puts s.join

MOD=10**9+7
cnt=0; sum=0; prev=nil; can=true; h=Hash.new(0)
def gs() gets.chomp end
def gi() gets.to_i end
def gsmi() gets.chomp.split.map(&:to_i) end

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end

#def bs(ar,eq,n) en=(eq==1 ? :>= : :>); ar.bsearch_index{|x|x.send(en,n)} end
def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n=gi
s=gs
ans=''
(n/2).times do |i|
  c1=s[2*i]
  c2=s[2*i+1]
  if c1==c2
    cnt+=1
    ans<<'ab'
  else
    ans<<(c1<<c2)
  end
end

puts "#{cnt}\n#{ans}"

n, s = gets.to_i, gets.chomp
i, nsubs, a = 0, 0, [nil]*s.size
while i < n
  if i%2 == 0 && s[i] == s[i + 1]
    nsubs += 1
    a[i] = s[i] == 'a' ? 'b' : 'a'
  else
    a[i] = s[i]
  end
  i += 1
end
p nsubs
puts a.join

def anti(c)
  return 'b' if c == 'a'

  'a'
end
_ = gets.chomp
s = 'b'
n = 0
prev = '_'
tmp = s.split('')
tmp.each_with_index do |el, ind|
  if el == prev
    s[ind] = anti(el)
    prev = anti(el)
    n += 1
  else
    s[ind] = el
    prev = el
  end
end
puts(n)
puts(s)

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

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

n = inp[0]
s = gets.chomp.split("")
f = false
ans = 0
s.each.with_index do |c, i|
  if(i.odd?)
    if(c == "a")
      if(f)
        s[i] = "b"
        ans += 1
      end
    else
      if(!f)
        s[i] = "a"
        ans += 1
      end
    end
  else
    f = true if c == "a"
  end
end
p ans
puts s.join