People worry that computers will get too smart and take over the world, but the real problem is that they're too stupid and they've already taken over the world.— Pedro DomingosYou work for a well-known department store that uses leading technologies and employs mechanistic work — that is, robots!The department you work in sells $$$n \cdot k$$$ items. The first item costs $$$1$$$ dollar, the second item costs $$$2$$$ dollars, and so on: $$$i$$$-th item costs $$$i$$$ dollars. The items are situated on shelves. The items form a rectangular grid: there are $$$n$$$ shelves in total, and each shelf contains exactly $$$k$$$ items. We will denote by $$$a_{i,j}$$$ the price of $$$j$$$-th item (counting from the left) on the $$$i$$$-th shelf, $$$1 \le i \le n, 1 \le j \le k$$$.Occasionally robots get curious and ponder on the following question: what is the mean price (arithmetic average) of items $$$a_{i,l}, a_{i,l+1}, \ldots, a_{i,r}$$$ for some shelf $$$i$$$ and indices $$$l \le r$$$? Unfortunately, the old robots can only work with whole numbers. If the mean price turns out not to be an integer, they break down.You care about robots' welfare. You want to arrange the items in such a way that the robots cannot theoretically break. Formally, you want to choose such a two-dimensional array $$$a$$$ that:  Every number from $$$1$$$ to $$$n \cdot k$$$ (inclusively) occurs exactly once.  For each $$$i, l, r$$$, the mean price of items from $$$l$$$ to $$$r$$$ on $$$i$$$-th shelf is an integer. Find out if such an arrangement is possible, and if it is, give any example of such arrangement.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 500$$$) — the number of shelves and length of each shelf, respectively. It is guaranteed that the sum $$$n$$$ over all test cases does not exceed $$$500$$$ and the sum $$$k$$$ over all test cases does not exceed $$$500$$$.

Print the answer for each test case. If such an arrangement exists, print "YES" on a single line. After that, print any example on $$$n$$$ lines of $$$k$$$ numbers each, one line per shelf. Each number from $$$1$$$ to $$$n \cdot k$$$ must occur exactly once in the output. If no good arrangement exists, print a single word "NO" on its own line.

case_count = gets.to_i

def put_table(n, k)
  (0...n).each do |i|
    row = []
    (0...k).each do |j|
      row << i / 2 * k * 2 + (i.odd? ? 2 : 1) + 2 * j
    end
    puts row.join " "
  end
end

case_count.times do
  n, k = gets.chomp.split(" ").map(&:to_i)

  if k == 1
    puts "YES"
    put_table n, k
  elsif n.even?
    puts "YES"
    put_table n, k
  else
    puts "NO"
  end
end

# puts "Table 1"
# put_table 10, 1
# puts "Table 2"
# put_table 2, 5


The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students.

Print one integer — the number of good pairs of topic.

def bsearch(l, h, a, v)
  m = l + (h - l)/2
  #print l, ' ', h, ' ', m
  #puts
  return l if h <= l
  if a[m] >= v
    bsearch(l, m, a, v)
  else
    bsearch(m+1, h, a, v)
  end
end

def lwr_bound(v, a)
  l = 0
  h = a.size-1
  bsearch(l, h, a, v)
end

#puts lwr_bound(5, [1,2,3,3,3,3,7,9])
n = gets.chomp.to_i
a = gets.chomp.split.map &:to_i
b = gets.chomp.split.map &:to_i
diff = a.each_with_index.map{|c, idx| c - b[idx]}.sort
ans = diff.each_with_index.map do |c, idx|
  next if c <= 0
  idx - lwr_bound(-c+1, diff)
end.compact.reduce(:+)
puts ans || 0


Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples:  for the array $$$[0, 0, 1, 0, 2]$$$ MEX equals to $$$3$$$ because numbers $$$0, 1$$$ and $$$2$$$ are presented in the array and $$$3$$$ is the minimum non-negative integer not presented in the array;  for the array $$$[1, 2, 3, 4]$$$ MEX equals to $$$0$$$ because $$$0$$$ is the minimum non-negative integer not presented in the array;  for the array $$$[0, 1, 4, 3]$$$ MEX equals to $$$2$$$ because $$$2$$$ is the minimum non-negative integer not presented in the array. You are given an empty array $$$a=[]$$$ (in other words, a zero-length array). You are also given a positive integer $$$x$$$.You are also given $$$q$$$ queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ and means that you have to append one element $$$y_j$$$ to the array. The array length increases by $$$1$$$ after a query.In one move, you can choose any index $$$i$$$ and set $$$a_i := a_i + x$$$ or $$$a_i := a_i - x$$$ (i.e. increase or decrease any element of the array by $$$x$$$). The only restriction is that $$$a_i$$$ cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of $$$q$$$ queries (i.e. the $$$j$$$-th answer corresponds to the array of length $$$j$$$).Operations are discarded before each query. I.e. the array $$$a$$$ after the $$$j$$$-th query equals to $$$[y_1, y_2, \dots, y_j]$$$.

The first line of the input contains two integers $$$q, x$$$ ($$$1 \le q, x \le 4 \cdot 10^5$$$) — the number of queries and the value of $$$x$$$. The next $$$q$$$ lines describe queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ ($$$0 \le y_j \le 10^9$$$) and means that you have to append one element $$$y_j$$$ to the array.

Print the answer to the initial problem after each query — for the query $$$j$$$ print the maximum value of MEX after first $$$j$$$ queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.

NoteIn the first example:  After the first query, the array is $$$a=[0]$$$: you don't need to perform any operations, maximum possible MEX is $$$1$$$.  After the second query, the array is $$$a=[0, 1]$$$: you don't need to perform any operations, maximum possible MEX is $$$2$$$.  After the third query, the array is $$$a=[0, 1, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$.  After the fourth query, the array is $$$a=[0, 1, 2, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$ (you can't make it greater with operations).  After the fifth query, the array is $$$a=[0, 1, 2, 2, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3]$$$. Now MEX is maximum possible and equals to $$$4$$$.  After the sixth query, the array is $$$a=[0, 1, 2, 2, 0, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3, 0]$$$. Now MEX is maximum possible and equals to $$$4$$$.  After the seventh query, the array is $$$a=[0, 1, 2, 2, 0, 0, 10]$$$. You can perform the following operations:   $$$a[3] := a[3] + 3 = 2 + 3 = 5$$$,  $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$,  $$$a[5] := a[5] + 3 = 0 + 3 = 3$$$,  $$$a[5] := a[5] + 3 = 3 + 3 = 6$$$,  $$$a[6] := a[6] - 3 = 10 - 3 = 7$$$,  $$$a[6] := a[6] - 3 = 7 - 3 = 4$$$.  The resulting array will be $$$a=[0, 1, 2, 5, 3, 6, 4]$$$. Now MEX is maximum possible and equals to $$$7$$$.

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

queries = Q.times.map { gets.to_i }
mex = 0
counter = Hash.new(0)

queries.each do |n|
  mod = n % X
  counter[mod] += 1

  while counter[mex % X] > 0
    counter[mex % X] -= 1
    mex += 1
  end

  puts mex
end


Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is different in evenness.

The first line contains integer n (3 ≤ n ≤ 100) — amount of numbers in the task. The second line contains n space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.

Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.

n = gets.to_i
hs = gets.split(' ').map(&:to_i).map.with_index{|x,id| [x,id]}.group_by{|x,id| x%2}
puts hs.min_by{|x,y| y.length}.last.last.last + 1

def func(n)
    if n % 2 == 0 then
        return true
    else
        return false
    end
end

n = gets.to_i
ch = []
nech = []

nums = gets.split.map{|i| i.to_i}

i = 0
while ch.size < 2 && nech.size < 2 do
    if func(nums[i]) then
        ch << nums[i]
    else
        nech << nums[i]
    end
    i += 1
end

if ch.size == 2 then
    i = 0
    while func(nums[i]) do
        i += 1
    end
else
    i = 0
    while !func(nums[i]) do
        i += 1
    end
end

puts i+1

n = gets.chomp.to_i
a = gets.chomp.split(/ /)
idx = 1
firste = 0
laste  = 0
firsto = 0
lasto  = 0
a.each {|aa|
	if aa.to_i % 2 == 0
		laste = idx
		firste = idx if firste == 0
	else
		lasto = idx
		firsto = idx if firsto == 0
	end
	idx += 1
}
if laste == firste
	puts laste
else
	puts lasto
end

n = gets.to_i
task = gets.strip.split.map &:to_i

odd_even_indexes = {odd: [], even:[]}

task.each_index do |i|
  if task[i].odd?
    odd_even_indexes[:odd] << (i + 1)
  else
    odd_even_indexes[:even] << (i + 1)
  end
end

if odd_even_indexes[:odd].length == 1
  puts odd_even_indexes[:odd].first
else
  puts odd_even_indexes[:even].first
end

gets
cnt = 0
a = gets().chomp.split(/[ \n]/)
a.map{|x| cnt += 1 if x.to_i.odd?}
puts a.index{|x| cnt == 1 ? x.to_i.odd? : x.to_i.even?} + 1

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

n = gets.chomp.to_i
test = string_to_int(gets.chomp)
if test.count(0) > test.count(1)
	puts test.index(1) + 1
else
	puts test.index(0) + 1
end

n = gets.to_i
a = gets.split.map(&:to_i)
c = [a[0], a[1], a[2]].map {|x| x%2}
c.count(0) > c.count(1) ? ch = 0 : ch = 1
puts a.index { |x| x%2 != ch } + 1

n = gets.to_i
arr = gets.split(" ").map{|i| i.to_i}
odd, even = [], []
n.times{|i| odd << i if arr[i].odd?; even << i if arr[i].even?}
puts (odd.count == 1 ? odd : even)[0]+1

n = gets.to_i
f = gets.split.map{|r| r.to_i}

counters = 0
for i in 0..n-1
 if f[i]%2 == 0
     par = i+1
     counters+=1
 else
     nep = i+1
 end
end

if counters > 1
    puts nep
else
    puts par
end

def find(n,even: false, odd: false )
  if even
    n.each_with_index do |val,ind|
      if val.even?
        puts ind +1
        break
      end
    end
  elsif odd
    n.each_with_index do |val,ind|
      if val.odd?
        puts ind+1
        break
      end
    end
  end
end

total = gets.chop!
n = gets.chop.split(" ").map(&:to_i)
count = 0
even=0
odd =0
n.each do |i|
  if count <3
    if i.even?
      even+=1
      count+=1
    else
      odd+=1
      count+=1
    end
  end
end
if even>odd
  find(n,odd: true)
else
  find(n,even: true)
end

n=gets.chomp.to_i
memo=gets.chomp.split.map{|i| i.to_i}
even=0
odd=0
evenIndex=-1
oddIndex=-1
n.times do |i|
  if memo[i]%2 == 0
    even=even+1
    evenIndex=i
  elsif
    odd=odd+1
    oddIndex=i
  end
end
if even > odd
  puts oddIndex+1
else
  puts evenIndex+1
end

gets
arr = gets.split.map &:to_i
puts arr.count { |x| x % 2 == 0 } > arr.count { |x| x % 2 != 0 } ?
  arr.index { |x| x % 2 != 0 } + 1 : arr.index { |x| x % 2 == 0 } + 1

n = gets.to_i
a = gets.split.map!{|t| t.to_i}
b = a.sort{|x,y| x%2 <=> y%2}
if b[0]%2 != b[1]%2
    puts a.index(b[0])+1
else
    puts a.index(b[-1])+1
end

gets.chomp
nums = gets.chomp.split(/ /).map(&:to_i)
odds = []
evens = []
(0...nums.length).each do |num|
    evens << num + 1 if nums[num].even?
    odds << num + 1 if nums[num].odd?
end
ans = 0
if odds.length == 1
    ans = odds[0]
else
    ans = evens[0]
end
puts ans

gets
a = gets.split.map(&:to_i)
b = { 0 => [], 1 => [] }
a.each_with_index do |x, i|
  b[x % 2] << i + 1
end
b.each_value do |ns|
  puts ns.first if ns.size == 1
end

n = gets.chomp.to_i
arr = gets.chomp.split.map(&:to_i)
co = 0
aco = {'odd'=>0,'even'=>0}
arr.each_with_index do |el,i|
  aco['even'] += 1 if el %2 == 0
  aco['odd'] += 1 if el %2 != 0
end

arr.each_with_index do |el,i|
  if aco['odd'] == 1
    if el % 2 != 0
      co = i
      break
    end
  else
    if el % 2 == 0
      co = i
      break
    end
  end
end

puts co+1

n = gets.to_i
arr = gets.split.map { |e| e.to_i  }
c = 0
3.times do |i|
	arr[i].even? ? c += 1 : c = c
	i += 1
end
x = 1
if c >= 2
	for i in arr
		if i.even?
			x += 1
		else
			p x
		end
	end
else
	for i in arr
		if i.even?
			p x
		else
			x += 1
		end
	end
end

gets
q = gets.split.map { |e| e.to_i }

s = q.find_all { |x| x.even? }
if s.size == 1
  puts q.index(s[0]) + 1
  exit
end

s = q.find_all { |x| x.odd? }
puts q.index(s[0]) + 1

def fn()
n=gets.to_i
arr=gets.split.collect{|a| a.to_i%2}
even=arr.count 0
odd= arr.count 1
wild=0
if odd == 1
  wild=1
end

return (arr.index wild)+1

end

p fn()

amount = gets.chomp
n = gets.chomp

numbers = n.split
even = 0
odd = 0

if amount.to_i == numbers.count
	for i in (1..amount.to_i)
		if numbers[i-1].to_i%2 != numbers[i].to_i%2
			a = numbers[i-1].to_i
			b = numbers[i].to_i
			pos_a = i
			pos_b = i+1
			break
		end
	end
end

numbers.each do |number|
	if number.to_i%2 == 0
		even += 1
	else
		odd += 1
	end
end

if even == 1 && a%2 == 0
	print pos_a
elsif even == 1 && b%2 == 0
	print pos_b
elsif odd == 1 && a%2 != 0
	print pos_a
else
	print pos_b
end

#!/bin/ruby

n = gets.chomp.to_i

a = gets.chomp.split(" ").map {|e| e.to_i}

j = 1
vitri = 0
odd = 0
even = 0
wE = 0
wO = 0
a.each do |i|
    if i % 2 == 0
        even += 1
        wE = j
    else
        odd += 1
        wO = j
    end
    j += 1
end

if even > odd
    puts wO.to_i
else
    puts wE.to_i
end

#puts "Enter total number of integers\n"
n = gets.to_i
#puts "Enter the numbers in a line\n"
s = gets.chomp.to_s.split(" ")
l = s.length
a = [l]
for i in 0...l do
    a[i] = s[i].to_i
end
e = []
o = []
j = 0
k = 0
for c in 0...l do
    if a[c] % 2 == 0
         e[j] = c
         j += 1
    else
        o[k] = c
        k += 1
    end
end
#puts o.length
#puts e.length
if o.length < e.length
    puts o[0] + 1
else
    puts e[0] + 1
end

gets.to_i
numbers = gets.split(" ").map(&:to_i)
odd_count = 0
even_count = 0
numbers[0..2].each do |n|
  if n % 2 == 0
    even_count += 1
  else
    odd_count += 1
  end
end

remainder = 1
remainder = 0 if even_count > odd_count
numbers.each_with_index do |n,i|
  puts i + 1 and break if n % 2 != remainder
end

gets
a = gets.split.map &:to_i
a.partition{|x| x.even? }[0].size == 1 ? a.map{|x| puts a.index(x) + 1 if x.even? } : a.map{|x| puts a.index(x) + 1 if x.odd? }

n = gets
l = gets.split
i = l.index{ |x| (l[0].to_i.even? and x.to_i.odd?) or (not l[0].to_i.even? and x.to_i.even?) } + 1
if l[i..-1].find{ |x| (l[0].to_i.even? and x.to_i.odd?) or (not l[0].to_i.even? and x.to_i.even?) }
	puts 1
else
	puts i
end

n, nums, odd, even, cur = gets, gets.chomp.split(' ').map { |item| item.to_i }, [], [], 1
nums.each{|i|
  even << cur if i.even?
  odd << cur if i.odd?
  cur=cur+1
}
puts even[0] if even.size==1
puts odd[0] if odd.size==1

n = gets.to_i
a = gets.split.map(&:to_i)
m = a.take(3).map{|x| x % 2}.sort[1]
puts a.find_index{|x| x % 2 != m} + 1

n = gets.to_i
a = [nil] + gets.split.map(&:to_i)
e = 0
o = 0
a[1..3].map{|x| x % 2 == 0 ? e += 1 : o += 1}
m = 1
m = 0 if e > o
for i in 1..a.size
  if a[i] % 2 != m
    puts i
    break
  end
end

gets
nums = gets.chomp.split.map(&:to_i)

res = nums.partition{ |e| e.even? }
elem = res.min_by{ |e| e.size }
puts nums.find_index(elem[0]) + 1

class Euler
  n=gets.to_i;
  a=gets;
  a=a.split(" ");
  a.each_index do |i|
    a[i]=(a[i].to_i)%2;
  end
  b=a.sort;
  if (b[0]==b[1])
    a.each_index do |i|
    if (a[i].to_i%2==1)
      puts (i+1);
      exit;
    end
    end
  else
     a.each_index do |i|
    if (a[i].to_i%2==0)
      puts (i+1);
      exit;
    end
  end
  end
end

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

puts (a.one?(&:odd?) ? a.index(&:odd?) : a.index(&:even?)) + 1

gets
nums = gets.split
even = 0
odd = 0
first_odd = nil
first_even = nil
nums.each_with_index do |num,index|
  num_even = num.to_i % 2 == 0
  if(!num_even)
    first_odd = index + 1 if odd == 0
    odd += 1
  else
    first_even = index + 1 if even == 0
    even +=1
  end
  if(odd >= 2 && even == 1)
    puts first_even
    break
  end
  if(even >= 2 && odd == 1)
    puts first_odd
    break
  end
end

gets
nums = gets.split(" ")

even = odd = even_pos = odd_pos = 0

nums.each_with_index do |num, i|
    buff = num.to_i
    if buff.even?
	even += 1
	even_pos = i + 1
    elsif buff.odd?
	odd += 1
	odd_pos = i + 1
    end

    if even >= 2 && odd == 1
	puts odd_pos
	exit
    elsif odd >= 2 && even == 1
	puts even_pos
	exit
    end
end

gets; input = gets.strip.split.map &:to_i
odd, even = [], []
input.each {|i| i % 2 == 0 ? even.push(i) : odd.push(i)  }
print even.length == 1 ? input.index(even.first) + 1 : input.index(odd.first) + 1

n = gets.chomp.to_i
a = gets.chomp.split.map(&:to_i)
e = a.select {|x| x % 2 == 0 }
puts a.each_with_index.select {|x| x[0] % 2 == (e.length == 1 ? 0 : 1)}.first.last + 1

gets
cnt = 0
a = gets().chomp.split(/[ \n]/)
a.map{|x| cnt += 1 if x.to_i.odd?}
puts a.select{|x| cnt == 1 ? x.to_i.odd? : x.to_i.even?}

n = gets.to_i
f = gets.split.map{|r| r.to_i}
a = Array.new(n)
b = Array.new(n)

for i in 0..n-1
 if f[i]%2 == 0
     a[i] = f[i]
 else
     b[i] = f[i]
 end
end

if a.compact.size < b.compact.size
   puts  a.compact
else
   puts b.compact
end

gets
p gets.split.collect{|i| i.to_i}.index{|x| x%2!=0}+1

gets
a = gets.split.map{|i| i.to_i%2}
p (a.count(0)>1?a.index{|x| x!=0}+1 : a.index{|x|x=0}+1)

gets
a = gets.split.map{|i| i.to_i%2}
p (a.count(0)>1?a.index{|x| x!=0} : a.index{|x|x=0})+1

gets
a = gets.split.map{|i| i.to_i%2}
p (a.count(?0)>1?a.index{|x| x!=0} : a.index{|x|x=0})+1

def find(n,even: false, odd: false )
  if even
    n.each_with_index do |val,ind|
      if val.even?
        return ind +1
      end
    end
  elsif odd
    n.each_with_index do |val,ind|
      if val.odd?
        return ind+1
      end
    end
  end
end

n = gets.chop.split(" ").map(&:to_i)
count = 0
even=0
odd =0
n.each do |i|
  if count <3
    if i.even?
      even+=1
      count+=1
    else
      odd+=1
      count+=1
    end
  else
    if even>odd
      puts find(n,odd: true).to_i
      break
    else
      puts find(n,even: true).to_i
      break
    end
  end
end

def find(n,even: false, odd: false )
  if even
    n.each_with_index do |val,ind|
      if val.even?
        puts ind +1
        break
      end
    end
  elsif odd
    n.each_with_index do |val,ind|
      if val.odd?
        puts ind+1
        break
      end
    end
  end
end

n = gets.chop.split(" ").map(&:to_i)
count = 0
even=0
odd =0
n.each do |i|
  if count <3
    if i.even?
      even+=1
      count+=1
    else
      odd+=1
      count+=1
    end
  else
    if even>odd
      find(n,odd: true)
      break
    else
      find(n,even: true)
      break
    end
  end
end

# cook your code here
def find(n,even: false, odd: false )
  if even
    n.each_with_index do |val,ind|
      if val.even?
        return ind +1
      end
    end
  elsif odd
    n.each_with_index do |val,ind|
      if val.odd?
        return ind+1
      end
    end
  end
end

n = gets.chop.split(" ").map(&:to_i)
count = 0
even=0
odd =0
n.each do |i|
  if count <3
    if i.even?
      even+=1
      count+=1
    else
      odd+=1
      count+=1
    end
  else
    if even>odd
      puts find(n,odd: true)
      break
    else
      puts find(n,even: true)
      break
    end
  end
end

def find(n,even: false, odd: false )
  if even
    n.each_with_index do |val,ind|
      if val.even?
        puts ind +1
        break
      end
    end
  elsif odd
    n.each_with_index do |val,ind|
      if val.odd?
        puts ind+1
        break
      end
    end
  end
end

total = gets.chop!
n = gets.chop.split(" ").map(&:to_i)
count = 0
even=0
odd =0
n.each do |i|
  if count <3
    if i.even?
      even+=1
      count+=1
    else
      odd+=1
      count+=1
    end
  else
    if even>odd
      find(n,odd: true)
      break
    else
      find(n,even: true)
      break
    end
  end
end

n=gets.chomp.to_i
number=gets.chomp.split.map{|i| i.to_i}
memo=Array.new(4)
if n==3
  puts 2
  exit(0)
end
mhash=Hash.new
num=0
(n-1).times do |i|
  memo[i]= number[i+1]-number[i]
  if mhash.include?(memo[i])==false
    mhash[memo[i]]=true
  elsif
    num=memo[i]
  end
end
(n-1).times do |i|
  if memo[i]!=num
    puts i+2
    break
  end
end

gets.chomp
nums = gets.chomp.split(/ /).map(&:to_i)
odds = []
evens = []
ans = 0
puts ans

n = gets.to_i
arr = gets.split.map { |e| e.to_i  }
c = 0
3.times do |i|
	arr[i].even? ? c += 1 : c = c
	i += 1
end
x = 1
if c == 2
	for i in arr
		if i.even?
			x += 1
		else
			p x
		end
	end
else
	for i in arr
		if i.even?
			p x
		else
			x += 1
		end
	end
end

def fn()
n=gets.to_i
arr=gets.split.collect{|a| a.to_i }
x=arr.pop
y=arr.pop
z=arr.pop
if x%2==y%2 && x%2!= z%2
 return z
elsif x%2==z%2  &&x%2 !=y%2
return y
elsif z%2==y%2 && z%2 !=x%2
return x
end

return arr.select{|a| a%3 != x%2}.first

end

p fn()

n = gets
l = gets.split
puts l.index{ |x| (l[0].to_i.even? and x.to_i.odd?) or (not l[0].to_i.even? and x.to_i.even?) } + 1

gets; input = gets.strip.split.map &:to_i
k = input[0] % 2

input.length.times {|i| print i + 1 if k != input[i] % 2 }


You came to a local shop and want to buy some chocolate bars. There are $$$n$$$ bars in the shop, $$$i$$$-th of them costs $$$a_i$$$ coins (and you want to buy all of them).You have $$$m$$$ different coupons that allow you to buy chocolate bars. $$$i$$$-th coupon allows you to buy $$$q_i$$$ chocolate bars while you have to pay only for the $$$q_i - 1$$$ most expensive ones (so, the cheapest bar of those $$$q_i$$$ bars is for free).You can use only one coupon; if you use coupon $$$i$$$, you have to choose $$$q_i$$$ bars and buy them using the coupon, and buy all the remaining $$$n - q_i$$$ bars without any discounts.To decide which coupon to choose, you want to know what will be the minimum total amount of money you have to pay if you use one of the coupons optimally.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of chocolate bars in the shop. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the cost of $$$i$$$-th chocolate bar. The third line contains one integer $$$m$$$ ($$$1 \le m \le n - 1$$$) — the number of coupons you have. The fourth line contains $$$m$$$ integers $$$q_1$$$, $$$q_2$$$, ..., $$$q_m$$$ ($$$2 \le q_i \le n$$$), where $$$q_i$$$ is the number of chocolate bars you have to buy using $$$i$$$-th coupon so that the least expensive of them will be for free. All values of $$$q_i$$$ are pairwise distinct.

Print $$$m$$$ integers, $$$i$$$-th of them should be the minimum amount of money you have to pay if you buy $$$q_i$$$ bars with $$$i$$$-th coupon, and all the remaining bars one by one for their full price.

NoteConsider the first example.If we use the first coupon, we may choose chocolate bars having indices $$$1$$$, $$$6$$$ and $$$7$$$, and we pay $$$18$$$ coins for them and $$$9$$$ coins for all other bars.If we use the second coupon, we may choose chocolate bars having indices $$$1$$$, $$$5$$$, $$$6$$$ and $$$7$$$, and we pay $$$25$$$ coins for them and $$$5$$$ coins for all other bars.

DBG = true
n = gets.to_i
a = gets.split.map{|z| z.to_i}
m = gets.to_i
q = gets.split.map{|z| z.to_i}
sum = a.inject(:+)
a.sort_by!{|z| -z}
for i in 0...m
  x = q[i]
  puts "#{sum - a[x-1]}"
end

if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

n = gets.to_i
arr = gets.chomp.split(" ").map(&:to_i).sort
sum = arr.inject(:+)
m = gets.to_i
qarr = gets.chomp.split(" ").map(&:to_i)

qarr.each do |q|
	puts sum-arr[-q]
end


In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with n - k + 1 strings s1, s2, ..., sn - k + 1, each either "YES" or "NO".   The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise).  The string s2 describes a group of soldiers 2 through k + 1.  And so on, till the string sn - k + 1 that describes a group of soldiers n - k + 1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing names — it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution.

The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 50) — the number of soldiers and the size of a group respectively. The second line contains n - k + 1 strings s1, s2, ..., sn - k + 1. The string si is "YES" if the group of soldiers i through i + k - 1 is effective, and "NO" otherwise.

Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them.

Adam Bob Bob Cpqepqwer Limak Adam Bob Adam

R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc

NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output:  First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO".  Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO".  Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES".  ...,  Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO".

names = ('A'..'Z').to_a + ('Aa'..'Az').to_a
n, k = gets.split.map(&:to_i)
bools = gets.split(' ').map{|x| x == 'YES'}
ans = Array.new(n)
ans[0, k - 1] = names[0, k - 1]
nn = k - 1
(n - k + 1).times do |i|
  if bools[i]
    ans[i + k - 1] = names[nn]
    nn += 1
  else
    ans[i + k - 1] = ans[i]
  end
end
puts ans.join(' ')

n, k=gets.split.map &:to_i
s=gets.split
c=?A
res=(1..n).map{c.next!.capitalize}
s.each_with_index{|e, i|
    res[i+k-1]=res[i] if e=="NO"
}
puts res*' '

while !STDIN.eof? && (string1 = STDIN.readline.strip) && (string2 = STDIN.readline.strip)
  n = string1.split(" ").first.to_i
  k = string1.split(" ").last.to_i
  successes = string2.split(" ").map { |s| s.strip == "YES" }
  name = "a"
  names = []
  successes.each_with_index do |success, index|
    if(index > 0)
      if(success)
        names.push(name.capitalize)
        name = name.next
      else
        names.push(names[index].capitalize)
      end
    else
      if(success)
        k.times do
          names.push(name.capitalize)
          name = name.next
        end
      else
        (k-1).times do
          names.push(name.capitalize)
          name = name.next
        end
        names.push(names[index].capitalize)
      end
    end
  end
  string = ""
  names.each { |name| string << name << " " }
  STDOUT << string.strip << "\n"
end

#1. Collect Input
n = gets(" ").to_i
k = gets.chomp.to_i

arr = gets.chomp.split(" ")
arr.map! { |s| s == "YES" ? true : false }

names = Array.new()
c_name = 0
stop_i = 0
out = Array.new(n, "")

names =
"Joyce
Abbey
Jenine
Arleen
Cammie
Lizbeth
Mario
Cortney
Shauna
Jenae
Erich
Faviola
Lexie
Erlinda
Alethia
Jacklyn
Yvone
Judy
Cassy
Hilda
Nettie
Florencia
Pattie
Zula
Debrah
Celeste
Leia
Lisette
Margarito
Josephina
Lanie
Justin
Kacie
Delores
Sherita
Carolynn
Edra
Hiedi
Neville
Rhona
Zane
Devona
Sigrid
Phillis
Delana
Nathanial
Roni
Melvina
Terri
Kandra".split("\n").each{ |s| s.strip! }

#2. First Advance
(0...arr.length).each do |i|
  if arr[i]
    (i...i+k).each do |j|
      out[j] = names[c_name]
      c_name += 1
    end
    stop_i = i
    break
  else
    out[i] = names[0]
  end
end

#3. Rest
if c_name == 0
  (arr.length...n).each { |i| out[i] = names[0] }
else
  (stop_i+1...arr.length).each do |i|
    if arr[i]
      out[i+k-1] = names[c_name]
      c_name += 1
    else
      out[i+k-1] = out[i]
    end
  end
end

out.each do |e|
  print e
  print " "
end

names = ('A'..'Z').to_a + ('AA'..'AZ').to_a
nn = 0
n, k = gets.split.map(&:to_i)
bools = gets.split(' ').map{|x| x == 'YES'}
ans = Array.new(n)
if bools[0]
  ans[0, k] = names[nn, k]
  nn += k
else
  ans[0, k - 1] = names[nn, k - 1]
  ans[0 + k - 1] = ans[0]
  nn += k - 1
end
(n - k).times do |i|
  if bools[i + 1]
    ans[i + k] = names[nn]
    nn += 1
  else
    ans[i + k] = ans[i + 1]
  end
end
puts ans.join(' ')

n, k=gets.split.map &:to_i
s=gets.split
if !s.include?("YES")
    puts "A "*n
else
    c=?A
    res=(1..n).map{c.next!.capitalize}
    s.reverse.each_with_index{|e, i|
        res[i]=res[i+k-1] if e=="NO"
    }
    puts res.reverse*' '
end

while !STDIN.eof? && (string1 = STDIN.readline.strip) && (string2 = STDIN.readline.strip)
  n = string1.split(" ").first.to_i
  k = string1.split(" ").last.to_i
  successes = string2.split(" ").map { |s| s.strip == "YES" }
  name = "a"
  names = []
  successes.each_with_index do |success, index|
    if(index > 0)
      if(success)
        names.push(name)
        name = name.next
      else
        names.push(names[index])
      end
    else
      if(success)
        k.times do
          names.push(name)
          name = name.next
        end
      else
        (k-1).times do
          names.push(name)
          name = name.next
        end
        names.push(names[index])
      end
    end
  end

  p names
end

while !STDIN.eof? && (string1 = STDIN.readline.strip) && (string2 = STDIN.readline.strip)
  n = string1.split(" ").first.to_i
  k = string1.split(" ").last.to_i
  successes = string2.split(" ").map { |s| s.strip == "YES" }
  name = "a"
  names = []
  successes.each_with_index do |success, index|
    if(index > 0)
      if(success)
        names.push(name)
        name = name.next
      else
        names.push(names[index])
      end
    else
      if(success)
        k.times do
          names.push(name)
          name = name.next
        end
      else
        (k-1).times do
          names.push(name)
          name = name.next
        end
        names.push(names[index])
      end
    end
  end
  string = ""
  names.each { |name| string << name << " " }
  STDOUT << string.strip << "\n"
end


A sequence of $$$n$$$ numbers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once. For example, the sequences [$$$3, 1, 4, 2$$$], [$$$1$$$] and [$$$2,1$$$] are permutations, but [$$$1,2,1$$$], [$$$0,1$$$] and [$$$1,3,4$$$] — are not.Polycarp lost his favorite permutation and found only some of its elements — the numbers $$$b_1, b_2, \dots b_m$$$. He is sure that the sum of the lost elements equals $$$s$$$.Determine whether one or more numbers can be appended to the given sequence $$$b_1, b_2, \dots b_m$$$ such that the sum of the added numbers equals $$$s$$$, and the resulting new array is a permutation?

The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) —the number of test cases.  Then the descriptions of the test cases follow. The first line of each test set contains two integers $$$m$$$ and $$$s$$$ ($$$1 \le m \le 50$$$, $$$1 \le s \le 1000$$$)—-the number of found elements and the sum of forgotten numbers. The second line of each test set contains $$$m$$$ different integers $$$b_1, b_2 \dots b_m$$$ ($$$1 \le b_i \le 50$$$) — the elements Polycarp managed to find.

Print $$$t$$$ lines, each of which is the answer to the corresponding test set. Print as the answer YES if you can append several elements to the array $$$b$$$, that their sum equals $$$s$$$ and the result will be a permutation. Output NO otherwise. You can output the answer in any case (for example, yEs, yes, Yes and YES will be recognized as positive answer).

NoteIn the test case of the example, $$$m=3, s=13, b=[3,1,4]$$$. You can append to $$$b$$$ the numbers $$$6,2,5$$$, the sum of which is $$$6+2+5=13$$$. Note that the final array will become $$$[3,1,4,6,2,5]$$$, which is a permutation.In the second test case of the example, $$$m=1, s=1, b=[1]$$$. You cannot append one or more numbers to $$$[1]$$$ such that their sum equals $$$1$$$ and the result is a permutation.In the third test case of the example, $$$m=3, s=3, b=[1,4,2]$$$. You can append the number $$$3$$$ to $$$b$$$. Note that the resulting array will be $$$[1,4,2,3]$$$, which is a permutation.

gets.to_i.times do
    m, s=gets.chomp.split(' ').map(&:to_i)
    arr=gets.chomp.split(' ').map(&:to_i)
    n= Math.sqrt((arr.sum+s)*2).floor
    mx=arr.max
    if arr.uniq.length==m && n*(n+1)==(arr.sum+s)*2 && n>=mx
        puts "YES"
    else
        puts "NO"
    end
end

main = -> {
  m, s = ints
  b = ints

  return "NO" if b.uniq.size != m

  b_max = b.max

  exist = [false] * (b_max + 1)
  b.each do |bi|
    exist[bi] = true
  end

  acc = 0
  (1..b_max).each do |i|
    acc += i unless exist[i]
  end

  (b_max+1..30000).each do |i|
    return "YES" if acc + (b_max + 1...i).sum == s
  end

  return "NO"
}

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

t = gets.to_i
puts t.times.map{ main.call }.join("\n")

gets.to_i.times do
    m, s=gets.chomp.split(' ').map(&:to_i)
    arr=gets.chomp.split(' ').map(&:to_i)
    n= Math.sqrt((arr.sum+s)*2).floor
    if arr.uniq.length==m and n*(n+1)==(arr.sum+s)*2
        puts "YES"
    else
        puts "NO"
    end
end


As a human, she can erase history of its entirety. As a Bai Ze (Hakutaku), she can create history out of nothingness.—Perfect Memento in Strict SenseKeine has the ability to manipulate history. The history of Gensokyo is a string $$$s$$$ of length $$$1$$$ initially. To fix the chaos caused by Yukari, she needs to do the following operations $$$n$$$ times, for the $$$i$$$-th time:  She chooses a non-empty substring $$$t_{2i-1}$$$ of $$$s$$$. She replaces $$$t_{2i-1}$$$ with a non-empty string, $$$t_{2i}$$$. Note that the lengths of strings $$$t_{2i-1}$$$ and $$$t_{2i}$$$ can be different.Note that if $$$t_{2i-1}$$$ occurs more than once in $$$s$$$, exactly one of them will be replaced.For example, let $$$s=$$$"marisa", $$$t_{2i-1}=$$$"a", and $$$t_{2i}=$$$"z". After the operation, $$$s$$$ becomes "mzrisa" or "marisz".After $$$n$$$ operations, Keine got the final string and an operation sequence $$$t$$$ of length $$$2n$$$. Just as Keine thinks she has finished, Yukari appears again and shuffles the order of $$$t$$$. Worse still, Keine forgets the initial history. Help Keine find the initial history of Gensokyo!Recall that a substring is a sequence of consecutive characters of the string. For example, for string "abc" its substrings are: "ab", "c", "bc" and some others. But the following strings are not its substring: "ac", "cba", "acb".HacksYou cannot make hacks in this problem.

Each test contains multiple test cases. The first line contains a single integer $$$T$$$ ($$$1 \leq T \leq 10^3$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n < 10 ^ 5$$$) — the number of operations. The next $$$2n$$$ lines contains one non-empty string $$$t_{i}$$$ — the $$$i$$$-th string of the shuffled sequence $$$t$$$. The next line contains one non-empty string $$$s$$$ — the final string. It is guaranteed that the total length of given strings (including $$$t_i$$$ and $$$s$$$) over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$. All given strings consist of lowercase English letters only. It is guaranteed that the initial string exists. It can be shown that the initial string is unique.

For each test case, print the initial string in one line.

2

2

a

ab

b

cd

acd

3

z

a

a

aa

yakumo

ran

yakumoran

NoteTest case 1:Initially $$$s$$$ is "a". In the first operation, Keine chooses "a", and replaces it with "ab". $$$s$$$ becomes "ab". In the second operation, Keine chooses "b", and replaces it with "cd". $$$s$$$ becomes "acd".So the final string is "acd", and $$$t=[$$$"a", "ab", "b", "cd"$$$]$$$ before being shuffled.Test case 2:Initially $$$s$$$ is "z". In the first operation, Keine chooses "z", and replaces it with "aa". $$$s$$$ becomes "aa". In the second operation, Keine chooses "a", and replaces it with "ran". $$$s$$$ becomes "aran". In the third operation, Keine chooses "a", and replaces it with "yakumo". $$$s$$$ becomes "yakumoran".So the final string is "yakumoran", and $$$t=[$$$"z", "aa", "a", "ran", "a", "yakumo"$$$]$$$ before being shuffled.

gets.to_i.times do
  n = gets.to_i
  freq = [0] * 26
  (2 * n + 1).times do |i|
    gets.chomp.bytes.each do |c|
      freq[c - 97] += 1
    end
  end
  freq.each.with_index do |f, i|
    puts (97 + i).chr if f % 2 == 1
  end
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    list = {}
    ('a'..'z').each do |i|
        list.store(i, 0)
    end
    possible_answers = []

    ((2*n)+1).times do
        x = gets.chomp
        x.each_char do |i|
            list[i] += 1;
        end
    end

    list.keys.each do |key|
        if list[key]%2 == 1
            puts key
            break
        end
    end
end

gets.to_i.times do
    n=gets.to_i
    h=Hash.new (0)
    (n*2+1).times do
        gets.each_char do |c|
            h[c]=h[c]+1
        end
    end
    h.each do |x,y|
        if y%2!=0 && x>='a' and x<='z'
            puts x
        end
    end
end

gets.to_i.times do
  n = gets.to_i
  freq = Array.new(26) { [0] * (2 * n + 1) }
  (2 * n + 1).times do |i|
    gets.chomp.bytes.each do |c|
      freq[c - 97][i] += 1
    end
  end
  freq.each.with_index do |f, i|
    left, right = 0, 0
    f.sort.reverse.each do |x|
      if left < right
        left += x
      else
        right += x
      end
    end
    if left != right
      puts (97 + i).chr
      break
    end
  end
end

gets.to_i.times do
  n = gets.to_i
  freq = Array.new(26) { [0] * (2 * n + 1) }
  (2 * n + 1).times do |i|
    gets.chomp.bytes.each do |c|
      freq[c - 97][i] += 1
    end
  end
  freq.each.with_index do |f, i|
    left, right = 0, 0
    f.sort.each do |x|
      if left < right
        left += x
      else
        right += x
      end
    end
    if left != right
      puts (97 + i).chr
      break
    end
  end
end

gets.to_i.times do
  n = gets.to_i
  freq = Array.new(26) { [0] * (2 * n + 1) }
  (2 * n + 1).times do |i|
    gets.chomp.bytes.each do |c|
      freq[c - 97][i] += 1
    end
  end
  freq.each.with_index do |f, i|
    sum = 0
    f.sort.each do |x|
      if (sum + x).abs < (sum - x).abs
        sum += x
      else
        sum -= x
      end
    end
    if sum != 0
      puts (97 + i).chr
      break
    end
  end
end

gets.to_i.times do
  n = gets.to_i
  freq = Array.new(26) { [0] * (2 * n + 1) }
  (2 * n + 1).times do |i|
    gets.chomp.bytes.each do |c|
      freq[c - 97][i] += 1
    end
  end
  freq.each.with_index do |f, i|
    sum = 0
    f.sort.reverse.each do |x|
      if (sum + x).abs < (sum - x).abs
        sum += x
      else
        sum -= x
      end
    end
    if sum != 0
      puts (97 + i).chr
      break
    end
  end
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    list = {}
    ('a'..'z').each do |i|
        list.store(i, 0)
    end
    possible_answers = []
    cnt = 0
    ((2*n)+1).times do
        x = gets.chomp
        cnt+=1
        if cnt != 2*n+1
            if x.length == 1
                possible_answers << x
            end
        end
        temp_list = {}
        x.each_char do |i|
            temp_list[i] = 1;
        end
        temp_list.keys.each do |key|
            list[key]+=1
        end

    end

    possible_answers.each do |x|
        if list[x]%2 == 1
            puts x
            break
        end
    end
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    list = {}
    ('a'..'z').each do |i|
        list.store(i, 0)
    end
    possible_answers = []
    ((2*n)+1).times do
        x = gets.chomp
        if x.length == 1
            possible_answers << x
        end
        temp_list = {}
        x.each_char do |i|
            temp_list[i] = 1;
        end
        temp_list.keys.each do |key|
            list[key]+=1
        end

    end

    possible_answers.each do |x|
        if list[x]%2 == 1
            puts x
            break
        end
    end
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    list = {}
    ('a'..'z').each do |i|
        list.store(i, 0)
    end
    possible_answers = []
    ((2*n)+1).times do
        x = gets.chomp
        if x.length == 1
            possible_answers << x
        end
        temp_list = {}
        x.each_char do |i|
            temp_list[i] = 1;
        end
        temp_list.keys.each do |key|
            list[key]+=1
        end

    end

    possible_answers.each do |x|
        if list[x]%2 == 1
            p x
            break
        end
    end
end

gets.to_i.times do
    n=gets.to_i
    h=Hash.new (0)
    (n*2+1).times do
        gets.each_char do |c|
            h[c]=h[c]+1
        end
    end
    h.each do |x,y|
        if y%2!=0
            print x
        end
    end
end

gets.to_i.times do
    n=gets.to_i
    h=Hash.new (0)
    (n*2+1).times do
        gets.each_char do |c|
            h[c]=h[c]+1
        end
    end
    h.each do |x,y|
        if y%2!=0
            puts x
        end
    end
end


This is an interactive problem.In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI.The subway of the Metropolis is one line (regular straight line with no self-intersections) with $$$n$$$ stations, indexed consecutively from $$$1$$$ to $$$n$$$. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured.To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers $$$l$$$ and $$$r$$$ ($$$l \le r$$$), and then check, whether the train is located on a station with index between $$$l$$$ and $$$r$$$, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most $$$k$$$ stations away. Formally, if the train was at the station $$$x$$$ when the gadget was applied, then at the next application of the gadget the train can appear at any station $$$y$$$ such that $$$\max(1, x - k) \leq y \leq \min(n, x + k)$$$.Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan.After an examination of the gadget you found that it is very old and can hold no more than $$$4500$$$ applications, after which it will break and your mission will be considered a failure.Can you find the station with the train using no more than $$$4500$$$ applications of the gadgets?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^{18}$$$, $$$0 \leq k \leq 10$$$) — the number of stations and the maximum number of stations the train can move between two applications of the gadget.

NoteIn the first sample, the train was initially at the station $$$5$$$, after the first application of the gadget it did not move, after the second application it moved to the station $$$3$$$, and after the third application moved again to the station $$$5$$$.

def min(a,b)
  a<b ? a : b
end

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

@c = 0
def query(i,j)
  @c += 1
  if @c > 4500
    raise "GG"
  end
  puts "#{i} #{j}"
  STDOUT.flush
  inp = gets.strip
  if inp[0]=='B'
    raise 'GG'
    exit -1
  end
  if i==j && inp[0]=='Y'
    exit 0
  elsif inp[0]=='Y'
    true
  else
    false
  end
end

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

l = 1
r = n

while l <= r do
  if r-l <= (40)
    p = l + rand(r-l+1)
    query(p,p)
  else
    m = ((l+r)/2)
    if query(l,m)
      r=m
    else
      l=m+1
    end
  end
  l -= k
  r += k
  l = max(1,l)
  r = min(n,r)
end

def min(a,b)
  a<b ? a : b
end

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

@c = 0
def query(i,j)
  @c += 1
  if @c > 4500
    raise "GG"
  end
  puts "#{i} #{j}"
  STDOUT.flush
  inp = gets.strip
  if inp[0]=='B'
    raise 'GG'
    exit -1
  end
  if i==j && inp[0]=='Y'
    exit 0
  elsif inp[0]=='Y'
    true
  else
    false
  end
end

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

l = 1
r = n

while l <= r do
  if r-l <= (2*k + 1)
    p = l + rand(r-l+1)
    query(p,p)
  else
    m = ((l+r)/2)
    if query(l,m)
      r=m
    else
      l=m+1
    end
  end
  l -= k
  r += k
  l = max(1,l)
  r = min(n,r)
end

def min(a,b)
  a<b ? a : b
end

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

@c = 0
def query(i,j)
  puts "#{i} #{j}"
  STDOUT.flush
  inp = gets.strip
  if inp[0]=='B'
    raise 'GG'
    exit -1
  end
  if i==j && inp[0]=='Y'
    exit 0
  elsif inp[0]=='Y'
    true
  else
    false
  end
end

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

l = 1
r = n

while l <= r do
  if r-l <= (2*k + 0)
    p = l + rand(r-l+1)
    query(p,p)
  else
    m = ((l+r)/2)
    if query(l,m)
      r=m
    else
      l=m+1
    end
  end
  l -= k
  r += k
  l = max(1,l)
  r = min(n,r)
end

def min(a,b)
  a<b ? a : b
end

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

@c = 0
def query(i,j)
  puts "#{i} #{j}"
  STDOUT.flush
  inp = gets.strip
  if inp[0]=='B'
    raise 'GG'
    exit -1
  end
  if i==j && inp[0]=='Y'
    exit 0
  elsif inp[0]=='Y'
    true
  else
    false
  end
end

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

l = 1
r = n

while l <= r do
  if r-l <= (3*k + 7)
    p = l + rand(r-l+1)
    query(p,p)
  else
    m = ((l+r)/2)
    if query(l,m)
      r=m
    else
      l=m+1
    end
  end
  l -= k
  r += k
  l = max(1,l)
  r = min(n,r)
end

def min(a,b)
  a<b ? a : b
end

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

@c = 0
def query(i,j)
  @c += 1
  if @c > 4500
    raise "GG"
  end
  puts "#{i} #{j}"
  STDOUT.flush
  inp = gets.strip
  if inp[0]=='B'
    raise 'GG'
    exit -1
  end
  if i==j && inp[0]=='Y'
    exit 0
  elsif inp[0]=='Y'
    true
  else
    false
  end
end

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

l = 1
r = n

while l <= r do
  if r-l <= (35)
    p = l + rand(r-l+1)
    query(p,p)
  else
    m = ((l+r)/2)
    if query(l,m)
      r=m
    else
      l=m+1
    end
  end
  l -= k
  r += k
  l = max(1,l)
  r = min(n,r)
end

def min(a,b)
  a<b ? a : b
end

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

@c = 0
def query(i,j)
  puts "#{i} #{j}"
  STDOUT.flush
  inp = gets.strip
  if inp[0]=='B'
    raise 'GG'
    exit -1
  end
  if i==j && inp[0]=='Y'
    exit 0
  elsif inp[0]=='Y'
    true
  else
    false
  end
end

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

l = 1
r = n

while l < r do
  l -= k
  r += k
  l = max(1,l)
  r = min(n,r)
  if r-l <= (4*k)
    p = l + rand(r-l+1)
    query(p,p)
  else
    m = ((l+r)/2)
    if query(l,m)
      r=m
    else
      l=m+1
    end
  end
end

def min(a,b)
  a<b ? a : b
end

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

@c = 0
def query(i,j)
  puts "#{i} #{j}"
  STDOUT.flush
  inp = gets.strip
  if inp[0]=='B'
    raise 'GG'
    exit -1
  end
  if i==j && inp[0]=='Y'
    exit 0
  elsif inp[0]=='Y'
    true
  else
    false
  end
end

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

l = 1
r = n

while l <= r do
  if r-l <= (2*k)
    p = l + rand(r-l+1)
    query(p,p)
  else
    m = ((l+r)/2)
    if query(l,m)
      r=m
    else
      l=m+1
    end
  end
  l -= k
  r += k
  l = max(1,l)
  r = min(n,r)
end

def min(a,b)
  a<b ? a : b
end

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

@c = 0
def query(i,j)
  puts "#{i} #{j}"
  STDOUT.flush
  inp = gets.strip
  if inp[0]=='B'
    exit -1
  end
  if i==j && inp[0]=='Y'
    exit 0
  elsif inp[0]=='Y'
    true
  else
    false
  end
end

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

l = 1
r = n

while l < r do
  l -= k
  r += k
  l = max(1,l)
  r = min(n,r)
  if r-l <= (3*k + 5)
    p = l + rand(r-l+1)
    query(p,p)
  else
    m = ((l+r)/2)
    if query(l,m)
      r=m
    else
      l=m+1
    end
  end
end


Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.

Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.

4
hello
hello
hello
helloo
hello
hlllloo
hello
helo

5
aa
bb
codeforces
codeforce
polycarp
poolycarpp
aaaa
aaaab
abcdefghijklmnopqrstuvwxyz
zabcdefghijklmnopqrstuvwxyz

n = gets.to_i
n.times do
  s = gets.chomp
  t = gets.chomp
  flg = true
  i,j=0,0
  sl,tl = s.length,t.length
  while i < sl && j < tl
    ci,cj = 0,0
    #p [i,j]
    while i < sl-1 && s[i] == s[i+1]
      i += 1
      ci += 1
    end
    while j < tl-1 && t[j] == t[j+1]
      j += 1
      cj += 1
    end
    if s[i] != t[j] || ci > cj
      flg = false
      break
    end
    i+=1
    j+=1
  end
  flg = false if i != sl || j != tl
  puts flg ? "YES" : "NO"
end

def compress(s)
  a = []
  last = nil
  cnt = 0
  s.split('').each do |c|
    if c == last
      cnt += 1
    else
      a.push [last, cnt] if last
      last = c
      cnt = 1
    end
  end
  a.push [last, cnt]
end

def good(a, b)
  if a.size != b.size
    false
  else
    !(a.map.with_index do |e, i|
      e[0] == b[i][0] && e[1] <= b[i][1]
    end.include? false)
  end
end

n = gets.strip.to_i
n.times do
  a = gets.strip
  b = gets.strip
  puts good(compress(a), compress(b)) ? 'YES' : 'NO'
end

def compress(s)
  a = []
  last = nil
  cnt = 0
  s.split('').each do |c|
    if c == last
      cnt += 1
    else
      a << [last, cnt] if last
      last = c
      cnt = 1
    end
  end
  a << [last, cnt]
end

def good(a, b)
  if a.size != b.size
    false
  else
    !(a.map.with_index do |e, i|
      e[0] == b[i][0] && e[1] <= b[i][1]
    end.include? false)
  end
end

n = gets.strip.to_i
n.times do
  a = gets.strip
  b = gets.strip
  puts good(compress(a), compress(b)) ? 'YES' : 'NO'
end

def compress(s)
  a = []
  last = nil
  cnt = 0
  index = 0
  s.split('').each do |c|
    if c == last
      cnt += 1
    else
      a << [last, cnt] if last
      last = c
      cnt = 1
    end
  end
  a << [last, cnt]
  a.compact
end

def good(a, b)
  if a.size != b.size
    false
  else
    !(a.map.with_index do |e, i|
      e[0] == b[i][0] && e[1] <= b[i][1]
    end.include? false)
  end
end

n = gets.strip.to_i
n.times do
  a = gets.strip
  b = gets.strip
  puts good(compress(a), compress(b)) ? 'YES' : 'NO'
end

def compress(s)
  a = []
  last = nil
  cnt = 0
  index = 0
  s.split('').each do |c|
    if c == last
      cnt += 1
    else
      a << [last, cnt] if last
      last = c
      cnt = 1
    end
  end
  a << [last, cnt]
  a.compact
end

def good(a, b)
  if a.size != b.size
    false
  else
    (0...(a.size)).each do |i|
      if !(a[i][0] == b[i][0] && a[i][1] <= b[i][1])
        return false
      end
    end
    true
  end
end

n = gets.chomp.to_i
n.times do
  a = gets.chomp
  b = gets.chomp
  puts good(compress(a), compress(b)) ? 'YES' : 'NO'
end

def compress(s)
  a = []
  last = nil
  cnt = 0
  index = 0
  s.split('').each do |c|
    if c == last
      cnt += 1
    else
      a << [last, cnt] if last
      last = c
      cnt = 1
    end
  end
  a << [last, cnt]
  a.compact
end

def good(a, b)
  if a.size != b.size
    false
  else
    (0...(a.size)).each do |i|
      if !(a[i][0] == b[i][0] && a[i][1] <= b[i][1])
        return false
      end
    end
    true
  end
end

n = gets.strip.to_i
n.times do
  a = gets.strip
  b = gets.strip
  puts good(compress(a), compress(b)) ? 'YES' : 'NO'
end

def compress(s)
  a = []
  last = nil
  cnt = 0
  index = 0
  s.split('').each do |c|
    if c == last
      cnt += 1
    else
      a << [last, cnt] if last
      last = c
      cnt = 1
    end
  end
  a << [last, cnt]
  a.compact
end

def good(a, b)
  if a.size != b.size
    false
  else
    a.each.with_index do |e, i|
      if !(e[0] == b[i][0] && e[1] <= b[i][1])
        return false
      end
    end
    true
  end
end

n = gets.strip.to_i
n.times do
  a = gets.strip
  b = gets.strip
  puts good(compress(a), compress(b)) ? 'YES' : 'NO'
end

def compress(s)
  a = Array.new(s.size)
  last = nil
  cnt = 0
  s.split('').each do |c|
    if c == last
      cnt += 1
    else
      a.push [last, cnt] if last
      last = c
      cnt = 1
    end
  end
  a.push([last, cnt]).compact
end

def good(a, b)
  if a.size != b.size
    false
  else
    !(a.map.with_index do |e, i|
      e[0] == b[i][0] && e[1] <= b[i][1]
    end.include? false)
  end
end

n = gets.strip.to_i
n.times do
  a = gets.strip
  b = gets.strip
  puts good(compress(a), compress(b)) ? 'YES' : 'NO'
end

def compress s
  a = []
  last = nil
  cnt = 0
  s.split('').each do |c|
    if c == last
      cnt += 1
    else
      if last
        a << [c, cnt]
      end
      last = c
      cnt = 1
    end
  end
  a << [last, cnt]
end

def good a, b
  if a.size != b.size
    false
  else
    !(a.map.with_index do |e, i|
      e[0] == b[i][0] && e[1] <= b[i][1]
    end.include? false)
  end
end

n = gets.strip.to_i
n.times do
  a, b = gets.strip, gets.strip
  puts good(compress(a), compress(b)) ? "YES" : "NO"
end

def compress(s)
  a = []
  last = nil
  cnt = 0
  s.split('').each do |c|
    if c == last
      cnt += 1
    else
      a << [c, cnt] if last
      last = c
      cnt = 1
    end
  end
  a << [last, cnt]
end

def good(a, b)
  if a.size != b.size
    false
  else
    (0...(a.size)).each do |i|
      if !((a[i][0] == b[i][0]) && (a[i][1] <= b[i][1]))
        return false
      end
    end
    true
  end
end

n = gets.strip.to_i
n.times do
  a = gets.strip
  b = gets.strip
  puts good(compress(a), compress(b)) ? 'YES' : 'NO'
end

def compress(s)
  a = []
  last = nil
  cnt = 0
  s.split('').each do |c|
    if c == last
      cnt += 1
    else
      a << [c, cnt] if last
      last = c
      cnt = 1
    end
  end
  a << [last, cnt]
end

def good(a, b)
  if a.size != b.size
    false
  else
    a.each.with_index do |e, i|
      if !((e[0] == b[i][0]) && (e[1] <= b[i][1]))
        return false
      end
    end
    true
  end
end

n = gets.strip.to_i
n.times do
  a = gets.strip
  b = gets.strip
  puts good(compress(a), compress(b)) ? 'YES' : 'NO'
end


Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.

The first line contains a single number n (2 ≤ n ≤ 1000) — the number of the tram's stops.  Then n lines follow, each contains two integers ai and bi (0 ≤ ai, bi ≤ 1000) — the number of passengers that exits the tram at the i-th stop, and the number of passengers that enter the tram at the i-th stop. The stops are given from the first to the last stop in the order of tram's movement.   The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, . This particularly means that a1 = 0.  At the last stop, all the passengers exit the tram and it becomes empty. More formally, .  No passenger will enter the train at the last stop. That is, bn = 0.

Print a single integer denoting the minimum possible capacity of the tram (0 is allowed).

NoteFor the first example, a capacity of 6 is sufficient:   At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3.  At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now.  At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now.  Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints. Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer.

a=[0]
gets.to_i.times{
  i,j=gets.split.map &:to_i
  a<<a[-1]-i+j
}
p a.sort![-1]

s = t = 0
gets.to_i.times do
  x, y = gets.split.map &:to_i
  s += y - x
  t = s if s > t
end
puts t

n = gets.to_i

s = max = 0
(0..n-1).each{|i|
    a,b=gets.split.map(&:to_i)
    s = s - a + b
    max < s ? max = s : max = max
}
p max

n = gets.chomp.to_i

res = 0
act = 0

for i in 1..n
	input = gets.chomp.split(" ")
	a = input[0].to_i
	b = input[1].to_i

	act -= a
	act += b

	if act>res
		res = act
	end
end

puts res

max, passengers = 0, 0
gets.to_i.times do
  tramio = gets.split.map(&:to_i)
  passengers += tramio[1] - tramio[0]
  max = passengers > max ? passengers : max
end
puts max

n = gets.to_i
c = 0
max = 0
for i in 1..n do
	a,b = gets.split.map(&:to_i)
	c = c - a + b
	if c > max
		max = c
	end
end

puts max

n = gets.to_i

inn = []
outt = []
counter,xounter = 0,0
for i in 0..n-1
  inn[i], outt[i] = gets.split.map(&:to_i)
  counter+=(outt[i]-inn[i])
  xounter = counter if counter > xounter
end

puts xounter

n=gets.to_i
a=[0]
n.times do
  i,j=gets.split.map &:to_i
  a<<a[-1]-i+j
end
puts a.sort![-1]

n=gets.to_i

ans=bus=0
n.times{
	a,b=gets.split.map(&:to_i)

	bus=bus-a+b
	ans=[bus, ans].max
}

p ans

res=0; puts gets.to_i.times.map{res+=-gets(' ').to_i+gets.to_i}.max

n = gets.to_i
ans = 0
p = 0
n.times do
  a, b = gets.split.map(&:to_i)
  p += - a + b
  ans = [ans, p].max
end
puts ans

n, k, s = gets.to_i, 0, 0
n.times do
  a, b = gets.split.map(&:to_i)
  s += -a + b
  k = [s, k].max
end
puts k

stop_count = gets.chomp.to_i
accum = 0
max = 0
for i in 1..stop_count
  stop = gets.chomp.split ' '

  accum += stop[1].to_i - stop[0].to_i

  if accum > max
    max = accum
  end
end

puts max

capacity, max = 0, 0
gets.to_i.times do
  inp = gets.split.map &:to_i
  capacity += inp[1] - inp[0]
  max = capacity if capacity > max
end
puts max

def get_min_capacity(passangers)
  temp_p = passangers.shift.sum
  # removing the last stop which is not important because all passangers exit the tram
  passangers.pop
  min = temp_p
  passangers.each do |a,b|
    temp_p = (temp_p-a) + b
    min = temp_p if temp_p > min
  end
  min
end

s = gets.to_i
a_p = []
(1..s).each do
  a = gets.split(/\s/).map(&:to_i)
  a_p << a
end
puts get_min_capacity(a_p)

n = gets.to_i
m, sv = 0, 0
n.times do
  a, b = gets.split(' ').map{|_|_.to_i}
  sv += b-a
  m = sv if sv>m
end
puts m

n = gets.chomp.to_i
array = []
passenger = 0
ans = 0
n.times do
	input = gets.chomp.split.map{|x| array.push x.to_i}
end
i = 0
while i < array.length
	passenger = passenger - array[i] + array[i+1]
	if passenger >= ans
		ans = passenger
	end
	i += 2
end
puts ans

num = gets.chomp.to_i
entra  = []
sale = []
a1 = 0
a2 = 0
i = 0
while (i < num)
	line = gets.chomp.split
	sale.push line[0].to_i
	entra.push line[1].to_i
	i = i + 1
end
j = 0
while (j < num)
	a1 = a1 + (entra[j] - sale[j])
	if (a1 > a2)
		a2 = a1
	end
	j = j + 1
end
puts a2.to_s

def tram ()
  n = gets.chomp
  capacity = 0
  count = 0
  for i in 0...n.to_i
    stops = gets.chomp
    stop = stops.split(" ")
    count = count + stop[1].to_i - (stop[0].to_i)
    if count > capacity
      capacity = count
    end
  end
  puts capacity
end

tram

n = gets.chomp.to_i
maxCap = 0
currentCap = 0

for i in 0...n
	input = gets.chomp.split(' ').map {|item| item.to_i}

	currentCap = currentCap - input[0] + input[1]
	maxCap = currentCap if maxCap < currentCap
end

puts maxCap

def max(a, b)
    return a>b ? a : b
end
n = gets.to_i
ans = 0
tk = 0
while (n > 0)
    a,b = gets.split(' ').map{|s| s.to_i}
    tk = tk - a + b
    ans = max(ans, tk)
    n -= 1
end
puts ans

def func()
 a=STDIN.readchar;
  b=0;
  while (a!=" "&& a!="\n")
  b=b*10+a.to_i;
  a=STDIN.readchar;
end
return b;
end
class Euler
  n=func;
  kol=0;
  max=0;
  (1..n).each do |i|
    a=func;
    b=func;
    kol-=a;
    kol+=b;
    if (kol>max)
      max=kol;
      end;
  end
  puts max;
 end

stops = gets.chomp.to_i
passengers = []
i = 0
while i < stops
	n = gets.chomp
	passengers << n.split(" ")
	i += 1
end

arr = []
count = 0
passengers.each do |pair|
	if passengers[0] == pair
		count += pair[1].to_i
		arr << count
	else
		count -= pair[0].to_i
		count += pair[1].to_i
		arr << count
	end
end

print arr.max

n=gets.to_i
ans = 0
t = 0
n.times do
    a,b = gets.split.map(&:to_i)
    t += b - a
    ans = t if t > ans
end

puts ans

@stopCount = STDIN.gets.to_i
@minSlot = 0;
@currentSlot = 0;
while (@stopCount > 0)
    stopInfo = STDIN.gets
    passengers_info = stopInfo.split(" ")
    @currentSlot = @currentSlot - passengers_info[0].to_i + passengers_info[1].to_i
    if(@minSlot < @currentSlot)
        @minSlot = @currentSlot
    end
    @stopCount -= 1
end
puts @minSlot

a=[0]
gets.to_i.times{
  i,j=gets.split.map &:to_i
  a<<a[-1]-i+j
}
p a.sort![-1]

n=gets.to_i

ans=bus=0
n.times{
	a,b=gets.split.map(&:to_i)

	bus=bus-a+b
	ans=[bus, ans].max
}

p ans

n = gets.to_i
rmax = 0
tmax = 0
for i in 0..n-1 do
    a = gets.split(" ").map(&:to_i)
    tmax = tmax - a[0]
    tmax = tmax + a[1]
    if tmax > rmax then
        rmax = tmax
    end
end

puts rmax

def main
  number_of_stops = gets.to_i

  max_people_on_tram = 0
  current_people_on_tram = 0

  until number_of_stops.zero?
    leaving, entering = gets.split.map(&:to_i)

    current_people_on_tram = current_people_on_tram - leaving + entering

    if current_people_on_tram > max_people_on_tram
      max_people_on_tram = current_people_on_tram
    end

    number_of_stops -= 1
  end

  puts max_people_on_tram

end

main if __FILE__ == $PROGRAM_NAME

s = gets.split(" ")
n = s[0].to_i
rez = 0
cur = 0
for i in 1..n
  s = gets.split(" ").to_a
  a = s[0].to_i
  b = s[1].to_i
  cur -= a;
  cur += b;
  rez = [rez, cur].max
end
puts(rez)

n = gets.to_i
answer = 0
max = 0

while(n>0)
    a, b = gets.split.map(&:to_i)
    answer -= a
    answer += b
    if answer > max
        max = answer
    end

    n-=1
end
puts max

s=0
res=[]
gets.to_i.times{
  a,b=gets.split.map(&:to_i)
  res<<s=s+(-a+b)
}
puts res.max

ret = 0
cur = 0
for i in 1..gets.to_i do
    a,b = gets.split.map(&:to_i)
    cur += b-a
    if (cur > ret) then ret = cur end
end
puts ret

ret = 0
running = 0
gets.to_i.times do
    chu, jin = gets.split.map &:to_i
    running += jin - chu;
    ret = [ret, running].max
end
puts ret

stations = Array.new
tram = 0
gets.to_i.times do
  station = gets.split.map(&:to_i)
  tram += station[1] - station[0]
  stations.push(tram)
end
puts stations.max

#!/usr/bin/ruby

stops = gets.to_i
capacity = 0
passengers = 0
stops.times do
    a, b = gets.split.map(&:to_i)
    passengers = [passengers - a , 0].max
    passengers += b
    capacity = [capacity, passengers].max
end

p capacity

n = gets.to_i

passengers_count = 0
max_passengers_count = 0

n.times do
  outcoming, incoming = gets.split.map(&:to_i)
  passengers_count += incoming - outcoming
  max_passengers_count = max_passengers_count > passengers_count ? max_passengers_count : passengers_count
end

puts max_passengers_count

n = max_n = 0
gets.to_i.times do
  x,y = gets.split.map &:to_i
  n = n-x+y
  max_n = n if n > max_n
end
p max_n

n = gets.strip.to_i
capacity = 0
current_passenger = 0
n.times do
  a, b = gets.strip.split(" ").map(&:to_i)
  current_passenger = current_passenger - a + b
  capacity = [capacity, current_passenger].max
end
puts capacity

n = gets.to_i

max = 0
col = 0
while n > 0 do
  a, b = gets.split.map &:to_i
  col += b - a
  max = col if col > max
  n -= 1
end

puts max

gets; input = STDIN.read.split("\n").map {|i| i.split.map! &:to_i }

max, up = 0, 0

input.each do |i|
  up -= i[0]
  up += i[1]
  max = up if max < up
end

print max

n = gets.to_i

max = 0
tram = 0
n.times do |i|
    s = gets.split.map{|i| i.to_i}
    tram -= s[0]
    tram += s[1]
    if tram > max then
        max = tram
    end
end

puts max

total=0
max=0
k=gets.to_i
k.times{|x|a,b=gets.split.map(&:to_i)
total=total+b-a
max=total if total>max}
print max

n = gets.strip.to_i
in_count = max_capacity = 0
n.times do
    a, b = gets.strip.split.map(&:to_i)
    in_count += (b - a)
    max_capacity = [max_capacity, in_count].max
end
puts max_capacity

n=0
ans=0
gets.to_i.times{
	a,b=gets.split.map{|e| e.to_i}
	n=n-a+b
	ans=[ans,n].max
}
puts ans

caps = 0
pass = 0
gets.to_i.times {
  a, b = gets.split.map(&:to_i)
  pass = pass - a + b
  caps = [caps, pass].max
}
puts caps

n = gets.to_i

max_cnt = 0
cur_cnt = 0
n.times {
  a, b = gets.split(" ").map(&:to_i)
  cur_cnt = cur_cnt - a + b
  max_cnt = cur_cnt if cur_cnt > max_cnt
}

puts max_cnt

max = 0
count = 0
n = gets.chomp.to_i
a = []
b = []
n.times.each do |_|
  a_n, b_n = gets.chomp.split(/ /).map(&:to_i)
  a << a_n
  b << b_n
  count += b_n - a_n
  max = count if count > max
end
puts max

t = $stdin.readline.split
n = t[0].to_i

m = 0
s = 0
n.times do
    t = $stdin.readline.split
    a, b = t.map(&:to_i)
    s += (b-a)
    m = s if s>m
end

puts m

class C116A
  q = 0
  m = 0
  gets.to_i.times{
    a, b = gets.split.map &:to_i
    q -= a
    q += b
    q > m && m = q
  }
  puts m
end

n = gets.chomp.to_i
ans = 0
people = 0

n.times do |i|
    a, b = gets.chomp.split(" ").map(&:to_i)
    people = people + b - a
    ans = [ans,people].max
end

puts ans

a=gets.chomp.to_i
ans=0
temp=0
a.times do
k=gets.chomp.split(" ")
temp=temp+k[1].to_i-k[0].to_i
if temp> ans
ans = temp
end
end

puts "#{ans}"

n = gets.to_i
a = []
b = []
for i in 1..n do
	b = gets.split.map(&:to_i)
	a.push(b)
end

j = 1
c = a[0][1]
max = 0
while j < (n-1) do
	c = c - a[j][0] + a[j][1]
	j = j+1
	if c > max
		max = c
	end
end

puts max

stops = gets.to_i
max = 0
passengers = 0
0.upto(stops - 1) do
  stop = gets.split
  passengers = passengers - stop[0].to_i
  passengers = passengers + stop[1].to_i
  max = passengers if passengers > max
end

puts passengers

def get_min_capacity(passangers)
  temp_p = passangers.shift.sum
  # removing the last stop which is not important because all passangers exit the tram
  passangers.pop
  min = 0
  passangers.each do |a,b|
    temp_p = (temp_p-a) + b
    min = temp_p if temp_p > min
  end
  min
end

s = gets.to_i
a_p = []
(1..s).each do
  a = gets.split(/\s/).map(&:to_i)
  a_p << a
end
puts get_min_capacity(a_p)

def get_min_capacity(passangers)
  min = passangers.shift.sum
  # removing the last stop which is not important because all passangers exit the tram
  passangers.pop

  passangers.each do |a,b|
    temp_p = (min-a) + b
    min = temp_p if temp_p > min
  end
  min
end

s = gets.to_i
a_p = []
(1..s).each do
  a = gets.split(/\s/).map(&:to_i)
  a_p << a
end
puts get_min_capacity(a_p)

def get_min_capacity(passangers)
  temp_p = passangers.shift.sum
  # removing the last stop which is not important because all passangers exit the tram
  passangers.pop
  min = 1
  passangers.each do |a,b|
    temp_p = (temp_p-a) + b
    min = temp_p if temp_p > min
  end
  min
end

s = gets.to_i
a_p = []
(1..s).each do
  a = gets.split(/\s/).map(&:to_i)
  a_p << a
end
puts get_min_capacity(a_p)

def tram ()
  n = gets.chomp
  capacity = 0
  count = 0
  for i in 0...n.to_i
    stops = gets.chomp
    count = count + stops[2].to_i - stops[0].to_i
    if count > capacity
      capacity = count
    end
  end
  puts capacity
end

tram

ret = 0
for i in 1..gets.to_i do
    a,b = gets.split.map(&:to_i)
    if (b-a>0) then ret += b-a end
end
puts ret

a=gets.chomp
res=0
if a.length==1
if a==a.upcase
puts "#{a.downcase}"
else
puts "#{a.upcase}"
end
else
1.upto(a.length-1) do|i|
if a[i]!=a[i].upcase
res=1
end
break if res==1
end
if res==1
puts "#{a}"
elsif (a[0]==a[0].upcase)
puts "#{a.downcase}"
else
a=a.downcase
b=a[0].upcase+a[1..a.length-1]
puts "#{b}"
end
end

n=gets.to_i

ans=bus=0
n.times{
	a,b=gets.split.map(&:to_i)

	bus-=(-a+b)
	ans=[bus, ans].max
}

p ans

n = gets.to_i
 a,b=gets.split.map(&:to_i)
s = max = 0
(0..n-1).each{|i|
    s = s - a[i] + b[i]
    max < s ? max = s : max = max
}
p max

stops = gets.chomp.to_i
passengers = []
i = 0
while i < stops
	n = gets.chomp
	passengers << n.split(" ")
	i += 1
end

arr = []
count = 0
passengers.each do |pair|
	if passengers[0] == pair
		count += pair[1].to_i
	else
		count -= pair[0].to_i
		count += pair[1].to_i
		arr << count
	end
end

print arr.max

caps = 0
gets.to_i.times {
  a, b = gets.split.map(&:to_i)
  caps = [caps, caps - a + b].max
}
puts caps

tramio, results = [], []
gets.to_i.times { tramio << gets.split.map(&:to_i) }
(tramio.size-1).times {|index| results << (tramio[index][1] - tramio[index+1][0] + tramio[index+1][1]) }
puts results.max

n = gets.to_i
a = []
b = []
for i in 1..n do
	b = gets.split.map(&:to_i)
	a.push(b)
end
print a
j = 1
c = a[0][1]
max = 0
while j < (n-1) do
	c = c - a[j][0] + a[j][1]
	j = j+1
	if c > max
		max = c
	end
end

puts max


Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.

The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements.

Print the only integer — the maximum value of f.

NoteIn the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].In the second case maximal value of f is reachable only on the whole array.

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

s = (0...n-1).map { |i| (a[i] - a[i+1]).abs }

s1 = s.map.with_index { |v, i| i % 2 == 0 ? v : -v }
s2 = s.drop(1).map.with_index { |v, i| i % 2 == 0 ? v : -v }

def solve(arr)
    arr.push(0)
    mn = 0
    (1...arr.length).each { |i| arr[i] += arr[i-1] }
    (0...arr.length).map { |i|
        mn = [mn, arr[i]].min if i % 2 == 1
        arr[i] - mn
    }.max
end

puts [solve(s1), solve(s2)].max

n = gets.chomp.to_i
a = gets.split(" ").map{|e| e.to_i}
b = a.each_cons(2).map.with_index{|e, i| (e[0] - e[1]).abs * (i & 1 == 0 ? 1 : -1)}
c = b.map{|e| -e}
def get_max_sum(a)
    l = 0
    r = 0
    sum = a[0]
    max = sum
    while r < a.length - 1
        while r < a.length - 1 && sum >= 0
            r += 1
            sum += a[r]
            max = [max, sum].max
        end
        while sum < 0
            sum -= a[l]
            l += 1
            max = [max, sum].max
        end
    end
    while l < a.length
        sum -= a[l]
        l += 1
        max = [max, sum].max
    end
    return max
end
puts [get_max_sum(b), get_max_sum(c)].max

n = gets.to_i
a = gets.split.map(&:to_i)
b = (n - 1).times.map{|i| (a[i + 1] - a[i]).abs * (-1) ** i}
bs = [0]
(n - 1).times{|i| bs[i + 1] = bs[i] + b[i]}
cmi = bs[0]
cmx = bs.max
mx = 0
mi = 0
n.times do |i|
  t = bs[i] - cmi
  mx = [t, mx].max
  cmi = [bs[i], cmi].min

  t = bs[i] - cmx
  mi = [t, mi].min
  cmx = [bs[i], cmx].max
end
p [mx, mi.abs].max

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

s = (0...n-1).map { |i| (a[i] - a[i+1]).abs }

s1 = s.map.with_index { |v, i| i % 2 == 0 ? v : -v }
s2 = s.drop(1).map.with_index { |v, i| i % 2 == 0 ? v : -v }

def solve(arr)
    arr.push(0)
    (1...arr.length).each { |i| arr[i] += arr[i-1] }
    mn = 0
    (0...arr.length).step(2).map { |i|
        mn = [mn, arr[i]] if i % 2 == 1
        arr[i] - mn
    }.max
end

puts [solve(s1), solve(s2)].max


One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.

Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.

NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".

# Utility
class BracketsSequence
  attr_reader :str, :correct, :clear_open, :clear_close

  def initialize(str)
    @str = str.strip

    @clear_open = 0
    @clear_close = 0

    @str.each_char do |c|
      if c == "("
        @clear_open += 1
      else
        @clear_open == 0 ? (@clear_close += 1) : (@clear_open -= 1)
      end
    end

    @correct = (@clear_open == 0) && (@clear_close == 0)
  end

  def to_s
    @str
  end
end

# Input and processing
n = gets.to_i
seq = Array.new

correct_count = 0
n.times do |i|
  s = BracketsSequence.new(gets)
  if s.correct
    correct_count += 1
  else
    seq << s
  end
end

count = 0
left  = Hash.new(0) # Amount of sequences with only N of opening brackets
right = Hash.new(0) # Amount of sequences with only N of closing brackets
seq.each do |s|
  if s.clear_close == 0
    left[s.clear_open] += 1
  elsif s.clear_open == 0
    right[s.clear_close] += 1
  end
end

left.each { |key, value| count += [value, right[key]].min }

# Output
puts correct_count / 2 + count

st0 = Time.now
n = gets().to_i
arr = [0] * n
n.times do |i|
  arr[i] = gets().chomp
end
# puts "0- #{Time.now - st0}"
st1 = Time.now
b = Array.new(arr.size) {[0, '']}
# b = Hash.new([0, ''])
# puts "1- #{Time.now - st1}"
t = 0

st2 = Time.now
arr.each_with_index do |e, ind|
  l = true
  r = e[-1] == ')'
  min_i = 0
  min = 1e9
  lst = 0
  # b[ind] = [0, '']
  e.each_char.with_index do |s, indd|
    lst = indd
    b[ind][0] += (s == '(') ? 1 : -1
    l = l && (b[ind][0] >= 0)
    if (b[ind][0] <= min)
      min = b[ind][0]
      min_i = indd
    end
  end
  r = r && min_i == lst && b[ind][0] <= 0
  b[ind][1] += 'l' if l
  b[ind][1] += 'r' if r
  if l && r
    t += 1
  end
end
# puts "2- #{Time.now - st2}"
# puts arr.to_s
# puts b.to_s
p = Hash.new(0)
m = Hash.new(0)
st3 = Time.now
b.each do |e|
  if e[0] < 0 && e[1] != ''
    m[-e[0]] += 1
  end
  if e[0] > 0 && e[1] != ''
    p[e[0]] += 1
  end
end
# puts "3- #{Time.now - st3}"
# puts p
# puts m
res = 0
st4 = Time.now
(p.keys & m.keys).each do |e|
  lp = p[e]
  rm = m[e]
  res += [lp, rm].min
end

# puts "4- #{Time.now - st4}"
# puts "sum- #{Time.now - st0}"
# puts t
puts res + t/2

N = gets.to_i
es = {}

def judge(s)
  t = []
  s.each{ |c|
    if t.size > 0 && t[-1] == "(" && c == ")"
      t.pop
    else
      t << c
    end
  }
  t.size == 0 ? 0 : (t[0] == t[-1] ? (t[0] == "(" ? t.size : -t.size) : nil)
end

N.times {
  s = gets.chomp.split("")
  x = judge(s)
  #p [s.join(""),x]
  next if !x
  es[x] = (es[x] || 0) + 1
}
#p es
p es.keys.select{ |x| x > 0 }.reduce(0){ |a,x| a + [es[x] || 0, es[-x] || 0].min } + (es[0] || 0)/2

def stack_output(s)
    stack = Array.new
    opening_count = 0
    closing_count = 0
    s.split('').each do |char|
        if char == '('
            stack.push(char)
            opening_count += 1
        elsif char == ')'
            unless stack.empty?
                stack.pop
                opening_count -= 1
            else
                closing_count += 1
            end
        end
    end
    if opening_count != 0 && closing_count != 0
        return ['unbalanced', -1]
    elsif opening_count != 0
        return ['open', opening_count]
    elsif closing_count != 0
        return ['close', closing_count]
    else
        return ['balanced', -1]
    end
end

s_arr = []
n = gets.chomp.to_i

0.upto(n-1) do |i|
    s_arr << gets.chomp
end

open_bracket = {}
closing_bracket = {}
balanced_bracket = 0

s_arr.each do |s|
    type, count = stack_output(s)
    case type
    when 'open'
        open_bracket[count] ||= 0
        open_bracket[count] += 1
    when 'close'
        closing_bracket[count] ||= 0
        closing_bracket[count] += 1
    when 'balanced'
        balanced_bracket += 1
    end
end

ac = 0
open_bracket.each do |k, v|
    ac += [v, closing_bracket[k]].min unless closing_bracket[k].nil?
end

ac += balanced_bracket/2
print ac

st0 = Time.now
n = gets().to_i
arr = []
n.times do
  arr += [gets().chomp]
end
st1 = Time.now
b = Hash.new([0, ''])
# arr.size.times do
#   b += [[0, '']]
# end
# puts "1- #{Time.now - st1}"
t = 0

st2 = Time.now
arr.each_with_index do |e, ind|
  l = true
  r = e[-1] == ')'
  min_i = 0
  min = 1e9
  lst = 0
  b[ind] = [0, '']
  e.each_char.with_index do |s, indd|
    lst = indd
    b[ind][0] += (s == '(') ? 1 : -1
    l = l && (b[ind][0] >= 0)
    if (b[ind][0] <= min)
      min = b[ind][0]
      min_i = indd
    end
  end
  r = r && min_i == lst && b[ind][0] <= 0
  b[ind][1] += 'l' if l
  b[ind][1] += 'r' if r
  if l && r
    t += 1
  end
end
# puts "2- #{Time.now - st2}"
# puts arr.to_s
# puts b.to_s
p = Hash.new(0)
m = Hash.new(0)
st3 = Time.now
b.values.each do |e|
  if e[0] < 0
    m[-e[0]] += 1
  end
  if e[0] > 0
    p[e[0]] += 1
  end
end
# puts "3- #{Time.now - st3}"
# puts p
# puts m
res = 0
st4 = Time.now
(p.keys & m.keys).each do |e|
  lp = p[e]
  rm = m[e]
  res += [lp, rm].min
end

# puts "4- #{Time.now - st4}"
# puts "sum- #{Time.now - st0}"
# puts t
puts res + t/2

n = gets().to_i
arr = []
n.times do
  arr += [gets().chomp]
end
b = []
arr.size.times do
  b += [[0, '']]
end
t = 0
arr.each_with_index do |e, ind|
  l = true
  r = e[-1] == ')'
  min_i = 0
  min = 1e9
  lst = 0
  e.each_char.with_index do |s, indd|
    lst = indd
    b[ind][0] += (s == '(') ? 1 : -1
    l = l && (b[ind][0] >= 0)
    if (b[ind][0] <= min)
      min = b[ind][0]
      min_i = indd
    end
  end
  r = r && min_i == lst
  b[ind][1] += 'l' if l
  b[ind][1] += 'r' if r
  if l && r
    t += 1
  end
end
# puts arr.to_s
# puts b.to_s
p = Hash.new('')
m = Hash.new('')
b.each do |e| #TODO: e[0] == 0
  if e[0] < 0
    m[-e[0]] += e[1]
  end
  if e[0] > 0
    p[e[0]] += e[1]
  end
end
res = 0
(p.keys & m.keys).each do |e|
  lp = p[e].count('l')
  rp = p[e].count('r')
  lm = m[e].count('l')
  rm = m[e].count('r')
  res += [lp, rm].min + [rp, lm].min
end
puts res + t/2

st0 = Time.now
n = gets().to_i
arr = []
n.times do
  arr += [gets().chomp]
end
st1 = Time.now
b = Array.new(arr.size) {[0, '']}
# b = Hash.new([0, ''])
# puts "1- #{Time.now - st1}"
t = 0

st2 = Time.now
arr.each_with_index do |e, ind|
  l = true
  r = e[-1] == ')'
  min_i = 0
  min = 1e9
  lst = 0
  # b[ind] = [0, '']
  e.each_char.with_index do |s, indd|
    lst = indd
    b[ind][0] += (s == '(') ? 1 : -1
    l = l && (b[ind][0] >= 0)
    if (b[ind][0] <= min)
      min = b[ind][0]
      min_i = indd
    end
  end
  r = r && min_i == lst && b[ind][0] <= 0
  b[ind][1] += 'l' if l
  b[ind][1] += 'r' if r
  if l && r
    t += 1
  end
end
# puts "2- #{Time.now - st2}"
# puts arr.to_s
# puts b.to_s
p = Hash.new(0)
m = Hash.new(0)
st3 = Time.now
b.each do |e|
  if e[0] < 0
    m[-e[0]] += 1
  end
  if e[0] > 0
    p[e[0]] += 1
  end
end
# puts "3- #{Time.now - st3}"
# puts p
# puts m
res = 0
st4 = Time.now
(p.keys & m.keys).each do |e|
  lp = p[e]
  rm = m[e]
  res += [lp, rm].min
end

# puts "4- #{Time.now - st4}"
# puts "sum- #{Time.now - st0}"
# puts t
puts res + t/2


This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?

NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:

N = gets.to_i
E = Hash.new { |h, k| h[k] = Hash.new(false) }

(N - 1).times do
  u, v = gets.split.map(&:to_i)

  E[u][v] = E[v][u] = true
end

leaf = []

E.each do |u, list|
  leaf << u if list.size == 1
end

ans = -1

(N / 2).times do |i|
  break if leaf.size < 2

  u, v = leaf.pop(2)

  STDOUT.puts("? #{u} #{v}")
  STDOUT.flush

  r = gets.to_i

  if r == u || r == v
    ans = r
    break
  end

  E[u].each_key do |k|
    E[k].delete(u)
  end

  E[v].each_key do |k|
    E[k].delete(v)
  end

  E.delete(u)
  E.delete(v)

  E.each do |u, list|
    leaf << u if list.size == 1
  end
end

if ans == -1
  ans = E.keys.first
end

puts "! #{ans}"

N = gets.to_i
E = Hash.new { |h, k| h[k] = Hash.new(false) }

(N - 1).times do
  u, v = gets.split.map(&:to_i)

  E[u][v] = E[v][u] = true
end

leaf = []

E.each do |u, list|
  leaf << u if list.size == 1
end

u = -1
v = -1
r = 1

cand = (1..N)
(N / 2).times do |i|
  if i == 0
    u, v = leaf.pop(2)
  else
    u = r
    v = E[u].keys.first
  end

  STDOUT.puts("? #{u} #{v}")
  STDOUT.flush

  r = gets.to_i
  E[u][r] = E[r][u] = true
  E[v][r] = E[r][v] = true
end

puts "! #{r}"


Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and b are different. Then your task will be to find any string s3 of length n, such that f(s1, s3) = f(s2, s3) = t. If there is no such string, print  - 1.

The first line contains two integers n and t (1 ≤ n ≤ 105, 0 ≤ t ≤ n). The second line contains string s1 of length n, consisting of lowercase English letters. The third line contain string s2 of length n, consisting of lowercase English letters.

Print a string of length n, differing from string s1 and from s2 in exactly t characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.

def camb(x, y)
    ('a'..'z').each do |v|
        if(v!=x && v!=y)
            return v
        end
    end
    return '0'
end

n= Array.new
c= Array.new

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

s=0
d=0
p=0
h=1

a = gets.chomp
b = gets.chomp

(0..(n[0]-1)).each do |i|
    if(a[i]==b[i])
        s+=1
    else
        d+=1
    end
end

if(d<=n[1])
    n[1]-=d
    (0..(n[0]-1)).each do |i|
        if(a[i]!=b[i])
            c << camb(a[i],b[i])
        elsif(n[1]>0 && a[i]==b[i])
            c << camb(a[i],b[i])
            n[1]-=1
        elsif(a[i]==b[i])
            c << a[i]
        end
    end
elsif(n[1]!=0 && ((d+1)/2)<=n[1])
    p=d/2
    (0..(n[0]-1)).each do |i|
        if(d!=n[1] && a[i]!=b[i])
            if(h==1)
                c<<a[i]
                h=0
            else
                c<<b[i]
                h=1
                n[1]-=1
                d-=2
            end
        elsif(d==n[1] && a[i]!=b[i])
            c<<camb(a[i],b[i])
            d-=1
            n[1]-=1
        elsif(a[i]==b[i])
            c<<a[i]
        end
    end
else
    c="-1"
end
if(c!="-1")
    print(c.join.to_s)
else
    print(c)
end

def camb(x, y)
    ('a'..'z').each do |v|
        if(v!=x && v!=y)
            return v
        end
    end
    return '0'
end

n= Array.new
c= Array.new

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

s=0
d=0
p=0
h=1

a = gets.chomp
b = gets.chomp

(0..(n[0]-1)).each do |i|
    if(a[i]==b[i])
        s+=1
    else
        d+=1
    end
end

if(d<=n[1])
    n[1]-=d
    (0..(n[0]-1)).each do |i|
        if(a[i]!=b[i])
            c << camb(a[i],b[i])
        elsif(n[1]>0 && a[i]==b[i])
            c << camb(a[i],b[i])
        elsif(a[i]==b[i])
            c << a[i]
        end
    end
elsif(n[1]!=0 && ((d+1)/2)<=n[1])
    p=d/2
    (0..(n[0]-1)).each do |i|
        if(d!=n[1] && a[i]!=b[i])
            if(h==1)
                c<<a[i]
                h=0
            else
                c<<b[i]
                h=1
                n[1]-=1
                d-=2
            end
        elsif(d==n[1] && a[i]!=b[i])
            c<<camb(a[i],b[i])
            d-=1
            n[1]-=1
        elsif(a[i]==b[i])
            c<<a[i]
        end
    end
else
    c="-1"
end
if(c!="-1")
    print(c.join.to_s)
else
    print(c)
end


It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.

The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.

Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.

NoteFor the sample input:  The worms with labels from [1, 2] are in the first pile.  The worms with labels from [3, 9] are in the second pile.  The worms with labels from [10, 12] are in the third pile.  The worms with labels from [13, 16] are in the fourth pile.  The worms with labels from [17, 25] are in the fifth pile.

n = gets.to_i
a = gets.split.map &:to_i
m = gets.to_i
q = gets.split.map &:to_i
(1...n).each do |i|
    a[i] += a[i - 1]
end
a = [0] + a
n.downto(1).each do |i|
    a[i] = a[i - 1] + 1
end
q.each do |x|
    ans = 1
    l, r = 1, n
    while l <= r do
        mid = (l + r) / 2
        if x >= a[mid] then
            l = mid + 1
            ans = [ans, mid].max
        else
            r = mid - 1
        end
    end
    puts ans
end

n = gets.chomp.to_i
a = gets.chomp.split(" ").map { |e| e.to_i }
m = gets.chomp.to_i
q = gets.chomp.split(" ").map { |e| e.to_i }

hash = {}
c = 1
a.each_with_index { |val, idx|
  val.times {
    hash[c] = idx + 1
    c += 1
  }
}

q.each { |val|
  puts hash[val]
}

n = STDIN.readline.to_i
piles = STDIN.readline.split.map {|s| s.to_i }
total = piles.inject(:+)
index = Array.new(total+1)
pos = 0
piles.each_with_index do |pile, i|
	pile.times do
		pos += 1
		index[pos] = i+1
	end
end
m = STDIN.readline.to_i
results = []
xs = STDIN.readline.split.map {|s| s.to_i }
xs.each {|x| results.push(index[x]) }
puts results.join("\n")

#!/usr/bin/ruby
t = 0
p = []
gets
gets.split(' ').each{|x|
  t += 1
  p << [t] * x.to_i
}
p.flatten!
gets
gets.split(' ').each{|x|
  puts p[x.to_i - 1]
}

gets
arr = gets.split.map &:to_i
gets
best = gets.split.map &:to_i
key = 1
hash = {}
arr.each_with_index do |item, index|
  item.times do |x|
    hash[key] = index + 1
    key += 1
  end
end
best.each { |x| puts hash[x] }

$a = [0]
def bs(w,x,y)
		pi = (x+y)/2
		if w <= $a[pi] and w > $a[pi-1]
			return pi
		elsif w > $a[pi]
			return bs(w,pi+1,y)
		else
			return bs(w,x,pi-1)
		end

end
n = gets.to_i
c = 1
gets.split.map(&:to_i).each do |i|
	$a[c] = $a[c-1] + i
	c += 1
end
m = gets.to_i
gets.split.map(&:to_i).each do |i|
	puts bs(i,0,n)
end

gets
a = gets.split.map(&:to_i)
s = []
temp = 0
a.each.with_index do |i, id|
  s << [temp + 1, temp + i, id + 1]
  temp += i
end
gets
qs = gets.split.map(&:to_i)
qs.each do |q|
  ans = s.bsearch do |x|
    if x[0] <= q && q <= x[1]
      0
    elsif q < x[0]
      -1
    else
      1
    end
  end
  puts ans[2]
end

n = Integer(gets.chomp)
numbers = gets
numbers_split = numbers.split
a = Array.new
for i in 0...n
    a[i] = Integer(numbers_split[i])
end
m = Integer(gets.chomp)
numbers2 = gets
numbers2_split = numbers2.split
q = Array.new
for i in 0...m
    q[i] = Integer(numbers2_split[i])
end

def binary_search(object,a)
    lo = 0
    hi = a.length - 1
    while lo != hi - 1
        mid = lo + (hi - lo) / 2
        if object <= a[mid]
            hi = mid
        elsif object > a[mid]
            lo = mid
        end
    end
    return lo + 1
end

a2 = Array.new
a2[0] = 0
my = 0
for i in 0...n
    my += a[i]
    a2.push(my)
end

for i in 0...m
    puts binary_search(q[i],a2)
end

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

arr = []
for i in (0..n-1)
	if i != 0
		sum = arr[i-1] + a[i]
		arr << sum
	else
		arr << a[i]
	end
end

for i in (0..m-1)
	first = 0
	last = n-1
	mid = (first + last)/2
	while first < last
		if arr[mid] < q[i]
			first = mid+1
		else
			last = mid
		end
		mid = (first + last)/2
	end
	puts first+1
end

=begin
5
2 7 3 4 9
3
1 25 11
=end
n = gets.to_i
ns = gets.split.map(&:to_i)
m = gets.to_i
ms = gets.split.map(&:to_i)
s = []
stack = 1
n.times do |i|
  ns[i].times do
    s.push stack
  end
  stack += 1
end
m.times do |i|
  puts s[ms[i] - 1]
end

n = gets.chomp
m = Array.new
k = 0

gets.split.map do |e|

  k += 1

  for i in 1..e.to_i
    m << k
  end

end

gets.chomp

gets.split.map do |e|

  puts m[e.to_i-1]

end

def read_int_array
    $stdin.readline.split(' ').map(&:to_i)
end

unless Array.method_defined? :bsearch_index
    class Array
        def bsearch_index
            ibegin, iend = 0, length
            found = false
            while ibegin < iend
                imid = ibegin + (iend - ibegin) / 2
                val = at(imid)
                if yield val
                    found = true
                    iend = imid
                else
                    ibegin = imid + 1
                end
            end
            found ? ibegin : nil
        end
    end
end

PILES_AMOUNT = $stdin.readline.to_i

PILES = read_int_array.reduce([]) { |array, pile| array.push (array[-1] or 0) + pile }

WORMS_AMOUNT = $stdin.readline.to_i

result = read_int_array.map { |worm| PILES.bsearch_index { |pile| pile >= worm } + 1 }
puts result

gets
a = gets.split(' ').each_with_index.map { |n, i| [i+1]*n.to_i }.flatten.unshift(0)

gets
gets.split(' ').each do |x|
  puts a[x.to_i]
end

i=0;
j=[];

gets
gets.split(' ').each{|x| i+=1; j << [i] * x.to_i}
j.flatten!
gets
gets.split(' ').each{|x| puts j[x.to_i-1]}

n = gets.to_i
a = gets.split(' ').map(&:to_i)
m = gets.to_i
q = gets.split(' ').map(&:to_i)
(1).upto(n-1) do |i|
  a[i]+=a[i-1]
end
b=[1]
a.each {|ai| b.push(ai+1)}
q.each do |i|
  s,e,mid,best=0,n,0,0
  while s<=e
    mid=s+e>>1
    if(b[mid]<=i)
      best=mid
      s=mid+1
    else
      e=mid-1
    end
  end
  puts best+1
end

n = Integer(gets.chomp)
numbers = gets
numbers_split = numbers.split
a = Array.new
for i in 0...n
    a[i] = Integer(numbers_split[i])
end
m = Integer(gets.chomp)
numbers2 = gets
numbers2_split = numbers2.split
q = Array.new
for i in 0...m
    q[i] = Integer(numbers2_split[i])
end

def binary_search(object,a)
    lo = 0
    hi = a.length - 1
    while lo != hi - 1
        mid = lo + (hi - lo) / 2
        if object <= a[mid]
            hi = mid
        elsif object > a[mid]
            lo = mid
        end
    end
    return mid + 1
end

a2 = Array.new
a2[0] = 0
my = 0
for i in 0...n
    my += a[i]
    a2.push(my)
end

for i in 0...m
    puts binary_search(q[i],a2)
end

n = Integer(gets.chomp)
numbers = gets
numbers_split = numbers.split
a = Array.new
for i in 0...n
    a[i] = Integer(numbers_split[i])
end
m = Integer(gets.chomp)
numbers2 = gets
numbers2_split = numbers2.split
q = Array.new
for i in 0...m
    q[i] = Integer(numbers2_split[i])
end

def binary_search(object,a)
    lo = 0
    hi = a.length - 1
    while lo <= hi
        mid = lo + (hi - lo) / 2
        if object < a[mid]
            hi = mid - 1
        elsif object > a[mid]
            lo = mid + 1
        else object = a[mid]
            return mid
        end
    end
    return mid
end

a2 = Array.new
a2[0] = 0
my = 0
for i in 0...n
    my += a[i]
    a2.push(my)
end

for i in 0...m
    puts binary_search(q[i],a2)
end