For the given integer $$$n$$$ ($$$n > 2$$$) let's write down all the strings of length $$$n$$$ which contain $$$n-2$$$ letters 'a' and two letters 'b' in lexicographical (alphabetical) order.Recall that the string $$$s$$$ of length $$$n$$$ is lexicographically less than string $$$t$$$ of length $$$n$$$, if there exists such $$$i$$$ ($$$1 \le i \le n$$$), that $$$s_i < t_i$$$, and for any $$$j$$$ ($$$1 \le j < i$$$) $$$s_j = t_j$$$. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.For example, if $$$n=5$$$ the strings are (the order does matter):  aaabb  aabab  aabba  abaab  ababa  abbaa  baaab  baaba  babaa  bbaaa It is easy to show that such a list of strings will contain exactly $$$\frac{n \cdot (n-1)}{2}$$$ strings.You are given $$$n$$$ ($$$n > 2$$$) and $$$k$$$ ($$$1 \le k \le \frac{n \cdot (n-1)}{2}$$$). Print the $$$k$$$-th string from the list.

The input contains one or more test cases. The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case is written on the the separate line containing two integers $$$n$$$ and $$$k$$$ ($$$3 \le n \le 10^5, 1 \le k \le \min(2\cdot10^9, \frac{n \cdot (n-1)}{2})$$$. The sum of values $$$n$$$ over all test cases in the test doesn't exceed $$$10^5$$$.

For each test case print the $$$k$$$-th string from the list of all described above strings of length $$$n$$$. Strings in the list are sorted lexicographically (alphabetically).

aaabb
aabab
baaba
bbaaa
abb
bab
aaaaabaaaaabaaaaaaaa

def tri(n)
	n * (n + 1) / 2
end

gets.to_i.times do
	n, k = gets.split.map &:to_i
	x = (1..10**9).bsearch{|i| tri(i) >= k}
	y = tri(x) - k
	ans = 'a' * n
	ans[n - x - 1] = 'b'
	ans[n - x + y] = 'b'
	puts ans
end

t = gets.to_i
t.times do
  n, k = gets.split.map(&:to_i)
  kk = 0
  for i in 1..(n-1) do
    if (kk + i) >= k
      j = k - kk - 1
      break
    end
    kk += i
  end
  s = "a" * n
  s[-1 - i] = "b"
  s[-1 - j] = "b"
  puts s
end

for run in 0...gets.to_i
	nums = gets.split(" ").map { |i| i.to_i }
	len = nums[0]
	loc = nums[1]
	t = 1
	i = 2
	until t >= loc
		t += i
		i += 1
	end
	rem = t - loc
	str = "a" * (len - i) + "b" + "a" * rem + "b" + "a" * (len - (len - i) - 1 - rem - 1)
	puts str
end

t = gets.to_i

1.upto(t) do
  n, k = gets.split(' ').map(&:to_i)

  sum = 0
  pos = 1
  i = 1
  while sum < k do
    sum += i
    pos += 1
    i   += 1
  end

  result = 'a'*n
  result[-pos] = 'b'
  result[-(k - sum + i - 1)] = 'b'

  puts result
end

# frozen_string_literal: true

def total(n, a)
  b = n - a
  tmp = (a + 1).upto(n).inject(:*) || 1
  2.upto(n - a) { |i| tmp /= i }
  tmp
end

test = gets.to_i
test.times do
  n, k = gets.chomp.split.map(&:to_i)
  a = n - 2
  n.downto(1) do |current|
    if current == 1
      if a > 0
        print 'a'
      else
        print 'b'
      end
    elsif a.zero?
      print 'b'
    elsif total(current - 1, a - 1) >= k
      print 'a'
      a -= 1
    else
      k -= total(current - 1, a - 1)
      print 'b'
    end
  end
  puts
end

t = gets.to_i
(1..t).each do
  arr = gets.split(' ')
  n = arr[0].to_i
  k = arr[1].to_i
  x = 1
  v = 0
  loop do
    if v+x < k
      v+=x
      x+=1
    else
      v+=x
      break
    end
  end
  ans = []
  (1..n-x-1).each do
    print "a"
  end
  rem = x-1
  print "b"
  (1..v-k).each do
    print "a"
    rem-=1
  end
  print "b"
  (1..rem).each do
    print "a"
  end
  puts("")

end


There are $$$n$$$ products in the shop. The price of the $$$i$$$-th product is $$$a_i$$$. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.In fact, the owner of the shop can change the price of some product $$$i$$$ in such a way that the difference between the old price of this product $$$a_i$$$ and the new price $$$b_i$$$ is at most $$$k$$$. In other words, the condition $$$|a_i - b_i| \le k$$$ should be satisfied ($$$|x|$$$ is the absolute value of $$$x$$$).He can change the price for each product not more than once. Note that he can leave the old prices for some products. The new price $$$b_i$$$ of each product $$$i$$$ should be positive (i.e. $$$b_i > 0$$$ should be satisfied for all $$$i$$$ from $$$1$$$ to $$$n$$$).Your task is to find out the maximum possible equal price $$$B$$$ of all productts with the restriction that for all products the condiion $$$|a_i - B| \le k$$$ should be satisfied (where $$$a_i$$$ is the old price of the product and $$$B$$$ is the same new price of all products) or report that it is impossible to find such price $$$B$$$.Note that the chosen price $$$B$$$ should be integer.You should answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Each query is presented by two lines. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100, 1 \le k \le 10^8$$$) — the number of products and the value $$$k$$$. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^8$$$), where $$$a_i$$$ is the price of the $$$i$$$-th product.

Print $$$q$$$ integers, where the $$$i$$$-th integer is the answer $$$B$$$ on the $$$i$$$-th query. If it is impossible to equalize prices of all given products with restriction that for all products the condition $$$|a_i - B| \le k$$$ should be satisfied (where $$$a_i$$$ is the old price of the product and $$$B$$$ is the new equal price of all products), print -1. Otherwise print the maximum possible equal price of all products.

NoteIn the first example query you can choose the price $$$B=2$$$. It is easy to see that the difference between each old price and each new price $$$B=2$$$ is no more than $$$1$$$.In the second example query you can choose the price $$$B=6$$$ and then all the differences between old and new price $$$B=6$$$ will be no more than $$$2$$$.In the third example query you cannot choose any suitable price $$$B$$$. For any value $$$B$$$ at least one condition out of two will be violated: $$$|1-B| \le 2$$$, $$$|6-B| \le 2$$$.In the fourth example query all values $$$B$$$ between $$$1$$$ and $$$7$$$ are valid. But the maximum is $$$7$$$, so it's the answer.

q = gets.chomp.to_i

for ii in 1..q
  _min = 100000000
  _max = 0

  (n,k) = gets.chomp.split(" ")
  k = k.to_i
  gets.chomp.split(" ").each do |num|
    num = num.to_i
    _min = _min > num ? num : _min
    _max = _max > num ? _max : num
  end

  if _max - _min > k*2
    puts -1
  else
    puts _min + k
  end
end

t = gets.to_i
(1..t).each do
  res = 0
  read = gets.split(" ").map{|c| c.to_i}
  n = read[0]
  k = read[1]
  prices = gets.split(" ").map{|c| c.to_i}
  mini = 1000000000
  maxi = 0
  prices.each do |price|
    mini = price if price < mini
    maxi = price if price > maxi
  end
  if (mini-maxi).abs > k * 2
    res = -1
  else
    res = mini + k
  end
  puts res
end

q = gets.to_i
q.times do
  n,k = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)
  if a.min + k < a.max - k
    p -1
  else
    p a.min + k
  end
end

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

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

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

def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
 q=gi
 q.times do
  n,k=gsmi
  a=gsmi.sort

  min=a[0]
  max=a[-1]

  if (max-min)>2*k
    puts -1
    next
  end

  puts min+k
 end

def test_cases(testCase)
    for interator in (0...testCase)
        (no_of_products, differ) = gets.chomp.split(' ').collect{|var| var.to_i}
        products = gets.chomp.split(' ').collect{|var| var.to_i}
        greatest_number = products.max
        smallest_number = products.min
        if(greatest_number - differ <= smallest_number + differ)
            puts smallest_number + differ
        else
            puts -1
        end
    end
end
testCase = gets.chomp.to_i
test_cases(testCase)


There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?Formally, we assume that two words denote the same name, if using the replacements "u"  "oo" and "h"  "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.For example, the following pairs of words denote the same name:  "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper"  "kuuper" and "kuooper"  "kuuper".  "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun"  "khoon" and "kkkhoon"  "kkhoon"  "khoon". For a given list of words, find the minimal number of groups where the words in each group denote the same name.

The first line contains integer number n (2 ≤ n ≤ 400) — number of the words in the list. The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.

Print the minimal number of groups where the words in each group denote the same name.

10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon

9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi

NoteThere are four groups of words in the first example. Words in each group denote same name:  "mihail", "mikhail"  "oolyana", "ulyana"  "kooooper", "koouper"  "hoon", "khun", "kkkhoon" There are five groups of words in the second example. Words in each group denote same name:  "hariton", "kkkhariton", "khariton"  "hkariton"  "buoi", "boooi", "boui"  "bui"  "boi" In the third example the words are equal, so they denote the same name.

def norm(s)
  s.gsub('u', 'oo').gsub('oo', 'u').gsub(/k+h/, 'h')
end

n = gets.to_i
ws = n.times.map{gets.strip}
puts ws.map{|w| norm(w)}.uniq.size

#! /usr/bin/env ruby

n = gets.to_i
a = (1..n).map { gets.gsub(/k+h/, 'h').gsub('u', 'oo') }.sort.uniq
puts a.size

number = ''
number = gets.chomp
n = number.to_i
res = {}
n.times do
   str = gets.chomp
   str.gsub!(/u/, 'oo')
   str.gsub!(/k+h/, 'h')
   res[str] = 1
end
puts res.size


A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative — it means that there was a loss in the correspondent year). King wants to show financial stability. To do this, he needs to find common coefficient X — the coefficient of income growth during one year. This coefficient should satisfy the equation:A·Xn = B.Surely, the king is not going to do this job by himself, and demands you to find such number X.It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient X must be integers. The number X may be zero or negative.

The input contains three integers A, B, n (|A|, |B| ≤ 1000, 1 ≤ n ≤ 10).

Output the required integer coefficient X, or «No solution», if such a coefficient does not exist or it is fractional. If there are several possible solutions, output any of them.

s = gets
n1,n2,n3 = s.split(/ /)
A=n1.to_i
B=n2.to_i
n=n3.to_i
ret = "No solution"

for x in -1000..1000
	if A*(x**n) == B then
		ret = x
		break
	end
end
puts ret

#!/usr/bin/ruby
a,b,n=gets.split.map(&:to_i)
if a==0
	puts b==0 ? 1 : 'No solution'
	exit
end
if a<0 then a=-a;b=-b end
sign=1
if b<0
	sign=-1 if n.odd?
	b=-b
end
r=(b.to_f/a)**(1.0/n)+1e-9
if (r-r.to_i).abs>1e-8 then puts 'No solution';exit end
p r.to_i*sign

input=gets.split.map(&:to_i)
a=input[0]
b=input[1]
n=input[2]
-1000.upto(1000){|ans|
    if a*(ans**n)==b then
        puts ans
        exit
    end
}
puts "No solution"

a,b,n=gets.split.map &:to_i
-1000.upto(1000){|_|
	if a*_**n==b then
		p _
		exit
	end
}
print 'No solution'

#!/usr/bin/ruby

(a,b,n) =  gets.split(" ")
a = a.to_i()
b = b.to_i()
n = n.to_i()

for x in -1000..1000
  if a * (x**n) == b
    puts x
    exit()
  end
end

puts "No solution"
exit()

def pow(x,p)
  res = 1
  1.upto(p){
    res = res*x
  }
  return res
end

def bsearch(l, r, n, a, b)
  if (b%a != 0)
    return 0, true
  end

  c = b/a

  l.upto(r) { |i|
    return i, false if pow(i,n)==c
  }
  return 0, true
end

v = gets.split(' ')
A,B,n = v[0].to_i, v[1].to_i, v[2].to_i
no_solution = false
x=0
if n==0
    no_solution = true
  else
    x=0
  end if ((A==0) && (B==0))

no_solution = true if ((A==0) && (B!=0))

if n==0
    no_solution = true
  else
    x=0
  end if ((A>0) && (B==0))

if n.even?
    no_solution = true
  else
    x, no_solution = bsearch(-1001, 1001, n, A, B)
  end if ((A>0) && (B<0))

x, no_solution = bsearch(-1001, 1001, n, A, B) if ((A>0) && (B>0))

x, no_solution = bsearch(-1001, 1001, n, A, B) if ((A<0)&&(B<0))

if n==0
    no_solution = true
  else
    x=0
  end if ((A<0)&&(B==0))

if ((A<0)&&(B>0))
  if n.even?
    no_solution = true
  else
    x, no_solution = bsearch(-1001, 1001, n, A, B)
  end
end

if no_solution
  puts "No solution"
else
  puts x
end

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if (result - result.round).abs < 0.000000001
  if (b/a < 0)
    print "-"
  end
  print result.round.to_s.split(".")[0]
else
  puts "No solution"
end

s = gets
n1,n2,n3 = s.split(/ /)
A=n1.to_i
B=n2.to_i
n=n3.to_i

if(A==0)
	if(B==0)
		puts "1"
	else
		puts "No solution"
	end
else
	c = (Float(B)/A).abs**(1.0/n)
	 c = -c if (n%2>0  && (B/A)<0)
	wk = c.floor
	if (Float(wk) < c)
		puts "No solution"
	else
		puts wk
	end
end

s = gets
n1,n2,n3 = s.split(/ /)
A=n1.to_i
B=n2.to_i
n=n3.to_i

if(A==0)
	if(B==0)
		puts "5"
	else
		puts "No solution"
	end
else
	c = (Float(B)/A).abs**(1.0/n)
	 c = -c if (n%2>0  && (B/A)<0)
	wk = c.floor
	if (Float(wk) < c)
		puts "No solution"
	else
		puts wk
	end
end

#!/usr/bin/ruby
a,b,n=gets.split.map(&:to_i)
if a==0 then p 1;exit end
if a<0 then a=-a;b=-b end
sign=1
if b<0
	sign=-1 if n.odd?
	b=-b
end
r=(b.to_f/a)**(1.0/n)
if r!=r.to_i then puts 'No solution';exit end
p r.to_i*sign

#!/usr/bin/ruby
a,b,n=gets.split.map(&:to_i)
if a==0
	puts b==0 ? 1 : 'No solution'
	exit
end
if a<0 then a=-a;b=-b end
sign=1
if b<0
	sign=-1 if n.odd?
	b=-b
end
r=(b.to_f/a)**(1.0/n)
if r!=r.to_i then puts 'No solution';exit end
p r.to_i*sign

#!/usr/bin/ruby
a,b,n=gets.split.map(&:to_i)
if a==0
	puts b==0 ? 1 : 'No solution'
	exit
end
if a<0 then a=-a;b=-b end
sign=1
if b<0
	sign=-1 if n.odd?
	b=-b
end
r=(b.to_f/a)**(1.0/n)+1e-7
if (r-r.to_i).abs>1e-7 then puts 'No solution';exit end
p r.to_i*sign

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if result.to_s.split(".")[1].to_f == 0
  if (b/a < 0)
    print "-"
  end
  print result.to_s.split(".")[0]
else
  puts "No solution"
end

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if (result.to_s.split(".")[1].to_f).abs < 0.000000001
  if (b/a < 0)
    print "-"
  end
  print result.to_s.split(".")[0]
else
  if (a == 1 && b == 1000 && n == 3)
    puts result.to_s.split(".")[1].to_f
  end
  puts "No solution"

end

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if (result.to_s.split(".")[1].to_f).abs < 0.000000001
  if (b/a < 0)
    print "-"
  end
  print result.to_s.split(".")[0]
else
  puts "No solution"
end

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if (result - result.round).abs < 0.000000001
  if (b/a < 0)
    print "-"
  end
  print result.to_s.split(".")[0]
else
  if (a == 1 && b == 1000 && n == 3)
    result - result.round
  end
  puts "No solution"

end

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if (result.to_s.split(".")[1].to_f).abs < 0.000000001
  if (b/a < 0)
    print "-"
  end
  print result.to_s.split(".")[0]
else
  if (a == 1 && b == 1000 && n == 3)
    result.to_s.split(".")[1].to_f
  end
  puts "No solution"

end


You are given a permutation $$$p_1, p_2, \dots, p_n$$$. A permutation of length $$$n$$$ is a sequence such that each integer between $$$1$$$ and $$$n$$$ occurs exactly once in the sequence.Find the number of pairs of indices $$$(l, r)$$$ ($$$1 \le l \le r \le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \dots, p_r$$$ is exactly the given number $$$m$$$.The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.For example, if $$$a=[4, 2, 7, 5]$$$ then its median is $$$4$$$ since after sorting the sequence, it will look like $$$[2, 4, 5, 7]$$$ and the left of two middle elements is equal to $$$4$$$. The median of $$$[7, 1, 2, 9, 6]$$$ equals $$$6$$$ since after sorting, the value $$$6$$$ will be in the middle of the sequence.Write a program to find the number of pairs of indices $$$(l, r)$$$ ($$$1 \le l \le r \le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \dots, p_r$$$ is exactly the given number $$$m$$$.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le m \le n$$$) — the length of the given sequence and the required value of the median. The second line contains a permutation $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). Each integer between $$$1$$$ and $$$n$$$ occurs in $$$p$$$ exactly once.

NoteIn the first example, the suitable pairs of indices are: $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$ and $$$(2, 4)$$$.

N, M = gets.split.map(&:to_i)
ps = gets.split.map(&:to_i)
index = ps.index(M)
lhash = Hash.new(0)
rhash = Hash.new(0)
lhash[0] = 1
rhash[0] = 1
sum = 0
(index-1).downto(0) do |i|
    sum += (ps[i] > M) ? 1 : -1
    lhash[sum] += 1
end
sum = 0
(index+1).upto(N-1) do |i|
    sum += (ps[i] > M) ? 1 : -1
    rhash[sum] += 1
end

ans = 0
lhash.keys.each do |i|
    ans += lhash[i] * (rhash[-i] + rhash[-i+1])
end
puts ans


Little X and Little Z are good friends. They always chat online. But both of them have schedules.Little Z has fixed schedule. He always online at any moment of time between a1 and b1, between a2 and b2, ..., between ap and bp (all borders inclusive). But the schedule of Little X is quite strange, it depends on the time when he gets up. If he gets up at time 0, he will be online at any moment of time between c1 and d1, between c2 and d2, ..., between cq and dq (all borders inclusive). But if he gets up at time t, these segments will be shifted by t. They become [ci + t, di + t] (for all i).If at a moment of time, both Little X and Little Z are online simultaneosly, they can chat online happily. You know that Little X can get up at an integer moment of time between l and r (both borders inclusive). Also you know that Little X wants to get up at the moment of time, that is suitable for chatting with Little Z (they must have at least one common moment of time in schedules). How many integer moments of time from the segment [l, r] suit for that?

The first line contains four space-separated integers p, q, l, r (1 ≤  p, q ≤ 50; 0 ≤ l ≤ r ≤ 1000). Each of the next p lines contains two space-separated integers ai, bi (0 ≤ ai < bi ≤ 1000). Each of the next q lines contains two space-separated integers cj, dj (0 ≤ cj < dj ≤ 1000). It's guaranteed that bi < ai + 1 and dj < cj + 1 for all valid i and j.

Output a single integer — the number of moments of time from the segment [l, r] which suit for online conversation.

p, q, l, r = STDIN.readline.split.map {|s| s.to_i }
x_pairs, z_pairs = [], []
p.times { x_pairs.push(STDIN.readline.split.map {|s| s.to_i }) }
x_bits = Array.new(1001, false)
x_pairs.each do |a, b|
	(a..b).each {|i| x_bits[i] = true }
end
q.times { z_pairs.push(STDIN.readline.split.map {|s| s.to_i }) }
count = 0
(l..r).each do |t|
	found = false
	z_pairs.each do |c, d|
		(c..d).each do |i|
			if x_bits[i+t]
				found = true
				break
			end
		end
		break if found
	end
	count += 1 if found
end
puts count

p, q, l, r = STDIN.readline.split.map {|s| s.to_i }
x_pairs, z_pairs = [], []
p.times { x_pairs.push(STDIN.readline.split.map {|s| s.to_i }) }
x = 0
x_pairs.each do |a, b|
	(a..b).each {|i| x |= (1 << i) }
end
q.times { z_pairs.push(STDIN.readline.split.map {|s| s.to_i }) }
z = 0
z_pairs.each do |c, d|
	(c..d).each {|i| z |= (1 << i) }
end
count = 0
(l..r).each {|t| count += 1 if (x & (z << t)) != 0 }
puts count

def check(ztime, xtime, t)
  ztime.each do |a, b|
    xtime.each do |c, d|
      break if c + t > b
      next if b < c + t
      return true if (c + t).between?(a, b) || (d + t).between?(a, b)
      return true if a.between?(c + t, d + t) || b.between?(c + t, d + t)
    end
  end

  false
end

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

ztime = []
p.times { ztime << gets.split.map(&:to_i) }

xtime = []
q.times { xtime << gets.split.map(&:to_i) }

puts l.upto(r).select { |t| check(ztime, xtime, t) }.size

p,q,l,r=gets.chomp.split.map(&:to_i)
a,b,c,ans=[],[],Array.new(1005,0),0
p.times do
	x,y=gets.chomp.split.map(&:to_i)
	a<<x;b<<y
end
q.times do
	x,y=gets.chomp.split.map(&:to_i)
	p.times do |i|
		j=a[i]-y
		while j<=b[i]-x
			if j>=l && j<=r && c[j]==0
				ans+=1
				c[j]=1
			end
			j+=1
		end
	end
end
puts ans

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

x = []
p.times do
  a, b = gets.chomp.split(' ').map(&:to_i)
  #puts ">> #{a} #{b} #{a..b}"
  x.concat (a..b).to_a
end

y = []
q.times do
  c, d = gets.chomp.split(' ').map(&:to_i)
  y.concat (c..d).to_a
end
hy = {}
y.each { |e| hy[e] = true }

res = 0
(l..r).each do |i|
  found = false
  x.each do |xi|
    if hy[xi-i]
      found = true
      break
    end
  end

  res += 1 if found
end

puts res

p,q,l,r = gets.split(" ").map(&:to_i)
first = []
second = []
p.times do
	x,y = gets.split(" ").map(&:to_i)
	first << (x..y).to_a
end
first.flatten!

q.times do
	x,y = gets.split(" ").map(&:to_i)
	second << (x..y).to_a
end
second.flatten!
# puts "first #{first}"
# puts "sec #{second}"
count = 0
(l..r).each do |i|
	count += 1 unless (first & second.map{|a| a + i}).empty?
end
puts count

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

p, q, l, r = read_next_line
a = (p + q).times.map { read_next_line }
x, y = a[0...p], a[p..-1]
puts (l..r).to_a.select { |m|
  s = t = 0
  res = false
  while s < p
    t += 1 while t < q && x[s][0] > y[t][1] + m
    if t == q
      break
    elsif x[s][1] >= y[t][0] + m
      res = true
      break
    end
    s += 1
  end
  res
}.count

p, q, l, r = gets.split.map(&:to_i)
ps, qs = [], []
p.times {ps << gets.split.map(&:to_i)}
q.times {qs << gets.split.map(&:to_i)}
count = 0
can = false
l.upto(r).each do |t|
  can = false
    ps.each do |pp|
  qs.each do |qq|
      next if pp[0] > qq[1] + t
      break if pp[1] < qq[0] + t
      if pp[0].between?((qq[0]+t), (qq[1]+t)) || pp[1].between?((qq[0]+t), (qq[1]+t)) || (qq[0]+t).between?(pp[0], pp[1]) || (qq[1]+t).between?(pp[0], pp[1])##(pp[0] <= (qq[0]+t) && pp[1] >= (qq[0]+t)) || (pp[0] <= (qq[1]+t) && pp[1] >= (qq[1]+t)) #((pp[0]..pp[1]).to_a & ((qq[0]+t)..(qq[1]+t)).to_a).any?
        can = true
        break
      end
  end
    break if can
    end
  count += 1 if can
end
# qs.each do |qq|
#   ps.each do |pp|
#     if pp[1] >= qq[0] && qq[0].between?(pp[0], pp[1])
#       count += 1
#     elsif pp[1] >= qq[0]
#       c = pp[0] - qq[1]
#       if c.between?(l, r)
#         count += 1
#       end
#     end
#   end
# end

puts count

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

str1 = '0' * 1001
str2 = '0' * 1001

p.times do
	a, b = gets.chomp.split(' ').map(&:to_i)
	str1[a..b]='1' * (b-a+1)
end

q.times do
	a, b = gets.chomp.split(' ').map(&:to_i)
	str2[a..b]='1' * (b-a+1)
end

str2.prepend('0' * l)

ans = 0
(r-l+1).times do

	for i in 0..(-1+str1.length)
		if (str1[i]=='1' and str2[i]=='1')
			ans=ans+1
			break
		end
	end

	str2.prepend('0')

end
puts ans

#! /usr/bin/env ruby
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2014 Szymon Sliwa <knight.erraunt@gmail.com>
#
# Distributed under terms of the MIT license.

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

tab_p, tab_q = [], []
p.times do
    tab_p << gets.split.map(&:to_i)
end
q.times do
    tab_q << gets.split.map(&:to_i)
end

p_present = {}
tab_p.each do |x|
    (x[0]..x[1]).each do |y|
        p_present[y] = true
    end
end

possible_diffs = {}
tab_q.each do |x|
    (x[0]..x[1]).each do |y|
        p_present.to_a.map do |a|
            possible_diffs[a[0]-y] = true
        end
    end
end

puts possible_diffs.to_a.select{|a| a[0] >= l && a[0] <= r}.size

def check(xtime, ztime, getup)
  xtime.each do |a, b|
    ztime.each do |c, d|
      return true if (c + getup).between?(a, b) || (d + getup).between?(a, b)
    end
  end

  false
end

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

xtime = []
p.times { xtime << gets.split.map(&:to_i) }

ztime = []
q.times { ztime << gets.split.map(&:to_i) }

puts l.upto(r).select { |getup| check(xtime, ztime, getup) }.size

p, q, l, r = gets.split.map(&:to_i)
ps, qs = [], []
p.times {ps << gets.split.map(&:to_i)}
q.times {qs << gets.split.map(&:to_i)}
count = 0
(l..r).each do |t|
  can= false
  qs.each do |qq|
    ps.each do |pp|
      if (pp[0] <= (qq[0]+t) && pp[1] >= (qq[0]+t)) #((pp[0]..pp[1]).to_a & ((qq[0]+t)..(qq[1]+t)).to_a).any?
        can = true
        break
      end
    end
    break if can
  end
  count += 1 if can
end

puts count

p, q, l, r = gets.split.map(&:to_i)
ps, qs = [], []
p.times {ps << gets.split.map(&:to_i)}
q.times {qs << gets.split.map(&:to_i)}
count = 0
(l..r).each do |t|
  can= false
  qs.each do |qq|
    ps.each do |pp|
      if (pp[0] <= (qq[0]+t) && pp[1] >= (qq[0]+t)) || (pp[0] <= (qq[1]+t) && pp[1] >= (qq[1]+t)) #((pp[0]..pp[1]).to_a & ((qq[0]+t)..(qq[1]+t)).to_a).any?
        can = true
        break
      end
    end
    break if can
  end
  count += 1 if can
end

puts count

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

str1 = '0' * 40
str2 = '0' * 40

p.times do
	a, b = gets.chomp.split(' ').map(&:to_i)
	str1[(a-1)..(b-1)]='1' * (b-a+1)
end

q.times do
	a, b = gets.chomp.split(' ').map(&:to_i)
	str2[(a-1)..(b-1)]='1' * (b-a+1)
end

str2.prepend('0' * l)

ans = 0
(r-l+1).times do

	for i in 0..(-1+str1.length)
		if (str1[i]=='1' and str2[i]=='1')
			ans=ans+1
			break
		end
	end

	str2.prepend('0')

end
puts ans


Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.There are $$$n$$$ banknote denominations on Mars: the value of $$$i$$$-th banknote is $$$a_i$$$. Natasha has an infinite number of banknotes of each denomination.Martians have $$$k$$$ fingers on their hands, so they use a number system with base $$$k$$$. In addition, the Martians consider the digit $$$d$$$ (in the number system with base $$$k$$$) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base $$$k$$$ is $$$d$$$, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet.Determine for which values $$$d$$$ Natasha can make the Martians happy.Natasha can use only her banknotes. Martians don't give her change.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100\,000$$$, $$$2 \le k \le 100\,000$$$) — the number of denominations of banknotes and the base of the number system on Mars. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — denominations of banknotes on Mars. All numbers are given in decimal notation.

On the first line output the number of values $$$d$$$ for which Natasha can make the Martians happy. In the second line, output all these values in increasing order. Print all numbers in decimal notation.

NoteConsider the first test case. It uses the octal number system.If you take one banknote with the value of $$$12$$$, you will get $$$14_8$$$ in octal system. The last digit is $$$4_8$$$.If you take one banknote with the value of $$$12$$$ and one banknote with the value of $$$20$$$, the total value will be $$$32$$$. In the octal system, it is $$$40_8$$$. The last digit is $$$0_8$$$.If you take two banknotes with the value of $$$20$$$, the total value will be $$$40$$$, this is $$$50_8$$$ in the octal system. The last digit is $$$0_8$$$.No other digits other than $$$0_8$$$ and $$$4_8$$$ can be obtained. Digits $$$0_8$$$ and $$$4_8$$$ could also be obtained in other ways.The second test case uses the decimal number system. The nominals of all banknotes end with zero, so Natasha can give the Martians only the amount whose decimal notation also ends with zero.

N, K = gets.split.map(&:to_i)
as = gets.split.map(&:to_i)
num = K
as.each do |a|
    num = num.gcd(a)
end
puts K/num
puts (0...(K/num)).map{|i| i*num}.join(' ')


The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order:  She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$).  She collects all mushrooms on point $$$y$$$.  A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.

For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.

NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.

gets.to_i.times do
    n,k=gets.split.map(&:to_i)
    arr=gets.split.map(&:to_i)
    if k<n
        sum=0
        max=0
        for i in (0...n) do
            if i<k
                sum+=arr[i]
            else
                max=[max,sum].max
                sum+=arr[i]-arr[i-k]
            end
        end
        max=[max,sum].max
        puts max + k*(k-1)/2
    else
        puts k*(k-1)/2-(k-n)*(k-n-1)/2+arr.sum
    end
end


You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$ and an integer $$$k$$$, such that $$$1 \leq k \leq n$$$. A permutation means that every number from $$$1$$$ to $$$n$$$ is contained in $$$p$$$ exactly once.Let's consider all partitions of this permutation into $$$k$$$ disjoint segments. Formally, a partition is a set of segments $$$\{[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]\}$$$, such that:  $$$1 \leq l_i \leq r_i \leq n$$$ for all $$$1 \leq i \leq k$$$;  For all $$$1 \leq j \leq n$$$ there exists exactly one segment $$$[l_i, r_i]$$$, such that $$$l_i \leq j \leq r_i$$$. Two partitions are different if there exists a segment that lies in one partition but not the other.Let's calculate the partition value, defined as $$$\sum\limits_{i=1}^{k} {\max\limits_{l_i \leq j \leq r_i} {p_j}}$$$, for all possible partitions of the permutation into $$$k$$$ disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by $$$998\,244\,353$$$.

The first line contains two integers, $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 200\,000$$$) — the size of the given permutation and the number of segments in a partition. The second line contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the given permutation.

Print two integers — the maximum possible partition value over all partitions of the permutation into $$$k$$$ disjoint segments and the number of such partitions for which the partition value is equal to the maximum possible value, modulo $$$998\,244\,353$$$. Please note that you should only find the second value modulo $$$998\,244\,353$$$.

NoteIn the first test, for $$$k = 2$$$, there exists only two valid partitions: $$$\{[1, 1], [2, 3]\}$$$ and $$$\{[1, 2], [3, 3]\}$$$. For each partition, the partition value is equal to $$$2 + 3 = 5$$$. So, the maximum possible value is $$$5$$$ and the number of partitions is $$$2$$$.In the third test, for $$$k = 3$$$, the partitions with the maximum possible partition value are $$$\{[1, 2], [3, 5], [6, 7]\}$$$, $$$\{[1, 3], [4, 5], [6, 7]\}$$$, $$$\{[1, 4], [5, 5], [6, 7]\}$$$, $$$\{[1, 2], [3, 6], [7, 7]\}$$$, $$$\{[1, 3], [4, 6], [7, 7]\}$$$, $$$\{[1, 4], [5, 6], [7, 7]\}$$$. For all of them, the partition value is equal to $$$7 + 5 + 6 = 18$$$. The partition $$$\{[1, 2], [3, 4], [5, 7]\}$$$, however, has the partition value $$$7 + 3 + 6 = 16$$$. This is not the maximum possible value, so we don't count it.

MOD = 998244353
N, K = gets.split.map(&:to_i)
P = gets.split.map(&:to_i)

order = Hash.new

P.each_with_index do |v, idx|
  order[v] = idx
end

v1 = (N - K + 1..N).inject(:+)

points = (N - K + 1..N).map { |n| order[n] }.sort
dp = Array.new(N + 10, 0)
v2 = 1

(K - 1).times do |i|
  po = points[i]
  np = points[i + 1]

  v2 *= np - po
  v2 %= MOD
end

puts [v1, v2].join(' ')

MOD = 998244353
N, K = gets.split.map(&:to_i)
P = gets.split.map(&:to_i)

order = Hash.new

P.each_with_index do |v, idx|
  order[v] = idx
end

v1 = (N - K + 1..N).inject(:+)

points = (N - K + 1..N).map { |n| order[n] }.sort
dp = Array.new(N + 10, 0)
v2 = 1

K.times do |i|
  po = points[i]
  np = points[i + 1] || N

  if i == 0
    v2 *= np - po
  else
    v2 *= np - po
  end

  v2 %= MOD
end

puts [v1, v2].join(' ')


Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.

The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.

Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.

TEST_MODE = ARGV[0] == 't'

def evaluate(actual, expected); actual == expected ? "OK" : "**NG**"; end
def tests(); yield if TEST_MODE; end
def to_array(val); val.kind_of?(Array) ? val : [val]; end
def parse_int_array(str); str.split(" ").collect{|s| s.to_i}; end

def t(input, expected_output)
  input = to_array(input)
  expected_output = to_array(expected_output)
  output = []
  solve(input, output)
  puts "#{evaluate(output, expected_output)} : input=#{input.to_s}, expected=#{expected_output.to_s}, actual=#{output.to_s}"
end

def gen_tree(input, n)
  tree = {}
  (1..n-1).each {|i|
    a, b = parse_int_array(input[i])
    if tree.include?(a) then tree[a].push(b) else tree[a] = [b] end
    if tree.include?(b) then tree[b].push(a) else tree[b] = [a] end
  }
  return tree
end

def find_edge(tree)
  tree.find{|k, v|
    v.size == 1
  }[0]
end

def find_roots(tree, edge, colors)
  c = colors[edge]
  done = {}
  queue = [edge]
  while queue.size > 0
    node = queue.pop
    done[node] = true
    for n in tree[node]
      return [node, n] if colors[n] != c
      queue.push(n) unless done[n]
    end
  end
  return [edge]
end

def eval_branch(tree, parent, root, colors)
  c = colors[root]
  done = {parent => true}
  queue = [root]
#  puts "root:#{root}, parent: #{parent}"
  while queue.size > 0
    node = queue.pop
    done[node] = true
    for n in tree[node]
      next if done[n]
#      puts "node:#{n}, color: #{colors[n]}"
      return false if colors[n] != c
      queue.push(n)
    end
  end
  return true
end

def solve(input, output)
  n = input[0].to_i
  tree = gen_tree(input, n)
  colors = parse_int_array("0 " + input[n])
  edge = find_edge(tree)
#  puts edge
  roots = find_roots(tree, edge, colors)
#  puts root
  if tree[roots[0]].all? {|e| eval_branch(tree, roots[0], e, colors) }
    output << "YES"
    output << roots[0].to_s
  elsif tree[roots[1]].all? {|e| eval_branch(tree, roots[1], e, colors) }
    output << "YES"
    output << roots[1].to_s
  else
    output << "NO"
  end
end

tests do
  # test cases
  t(["4",
    "1 2",
    "2 3",
    "3 4",
    "1 2 1 1"],
    ["YES", "2"])
  t(["3",
      "1 2",
      "2 3",
      "1 2 3"],
      ["YES", "2"])
  t(["4",
    "1 2",
    "2 3",
    "3 4",
    "1 2 1 2"],
    ["NO"])
  t(["2",
      "1 2",
      "1 1"],
      ["YES", "1"])
  t(["4",
    "1 4",
    "2 4",
    "3 4",
    "1 2 3 1"],
    ["YES", "4"])
end

puts solve(STDIN.read.split("\n"), []) unless TEST_MODE

TEST_MODE = ARGV[0] == 't'

def evaluate(actual, expected); actual == expected ? "OK" : "**NG**"; end
def tests(); yield if TEST_MODE; end
def to_array(val); val.kind_of?(Array) ? val : [val]; end
def parse_int_array(str); str.split(" ").collect{|s| s.to_i}; end

def t(input, expected_output)
  input = to_array(input)
  expected_output = to_array(expected_output)
  output = []
  solve(input, output)
  puts "#{evaluate(output, expected_output)} : input=#{input.to_s}, expected=#{expected_output.to_s}, actual=#{output.to_s}"
end

def gen_tree(input, n)
  tree = {}
  (1..n-1).each {|i|
    a, b = parse_int_array(input[i])
    if tree.include?(a) then tree[a].push(b) else tree[a] = [b] end
    if tree.include?(b) then tree[b].push(a) else tree[b] = [a] end
  }
  return tree
end

def find_edge(tree)
  tree.find{|k, v|
    v.size == 1
  }[0]
end

def find_root(tree, edge, colors)
  c = colors[edge]
  done = {}
  queue = [edge]
  while queue.size > 0
    node = queue.pop
    done[node] = true
    for n in tree[node]
      return n if colors[n] != c
      queue.push(n) unless done[n]
    end
  end
  return edge
end

def eval_branch(tree, parent, root, colors)
  c = colors[root]
  done = {parent => true}
  queue = [root]
#  puts "root:#{root}, parent: #{parent}"
  while queue.size > 0
    node = queue.pop
    done[node] = true
    for n in tree[node]
      next if done[n]
#      puts "node:#{n}, color: #{colors[n]}"
      return false if colors[n] != c
      queue.push(n)
    end
  end
  return true
end

def solve(input, output)
  n = input[0].to_i
  tree = gen_tree(input, n)
  colors = parse_int_array("0 " + input[n])
  edge = find_edge(tree)
#  puts edge
  root = find_root(tree, edge, colors)
#  puts root
  if tree[root].all? {|e| eval_branch(tree, root, e, colors) }
    output << "YES"
    output << root.to_s
  else
    output << "NO"
  end
end

tests do
  # test cases
  t(["4",
    "1 2",
    "2 3",
    "3 4",
    "1 2 1 1"],
    ["YES", "2"])
  t(["3",
      "1 2",
      "2 3",
      "1 2 3"],
      ["YES", "2"])
  t(["4",
    "1 2",
    "2 3",
    "3 4",
    "1 2 1 2"],
    ["NO"])
  t(["2",
      "1 2",
      "1 1"],
      ["YES", "1"])
end

puts solve(STDIN.read.split("\n"), []) unless TEST_MODE


Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li.You are given lengths of the claws. You need to find the total number of alive people after the bell rings.

The first line contains one integer n (1 ≤ n ≤ 106) — the number of guilty people. Second line contains n space-separated integers L1, L2, ..., Ln (0 ≤ Li ≤ 109), where Li is the length of the i-th person's claw.

Print one integer — the total number of alive people after the bell rings.

NoteIn first sample the last person kills everyone in front of him.

n = gets.chomp.to_i
l = gets.chomp.split.map(&:to_i)
ans, cmp = 0, n
(n - 1).downto(0) do |i|
  ans += (i < cmp) ? 1 : 0
  cmp = [cmp, i - l[i]].min
end
print ans

gets
ar = gets.split.map(&:to_i)

ptr = ar.length
ans = 0

(ar.length-1).downto(0).each do |i|
  ans += 1  if ptr > i
  ptr = [ptr, i-ar[i]].min
end

puts ans

gets
ar = gets.split.map(&:to_i)

ptr = ar.length
ans = 0

(ar.length-1).downto(0).each do |i|
  if ptr > i
    ans += 1
  end
  ptr = [ptr, i-ar[i]].min
end

puts ans


Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are $$$T$$$ rooms there. Every room has a door into it, each door can be described by the number $$$n$$$ of seals on it and their integer energies $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. All energies $$$a_i$$$ are nonzero and do not exceed $$$100$$$ by absolute value. Also, $$$n$$$ is even.In order to open a door, Naruto must find such $$$n$$$ seals with integer energies $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ that the following equality holds: $$$a_{1} \cdot b_{1} + a_{2} \cdot b_{2} + ... + a_{n} \cdot b_{n} = 0$$$. All $$$b_i$$$ must be nonzero as well as $$$a_i$$$ are, and also must not exceed $$$100$$$ by absolute value. Please find required seals for every room there.

The first line contains the only integer $$$T$$$ ($$$1 \leq T \leq 1000$$$) standing for the number of rooms in the Orochimaru's lair. The other lines contain descriptions of the doors. Each description starts with the line containing the only even integer $$$n$$$ ($$$2 \leq n \leq 100$$$) denoting the number of seals. The following line contains the space separated sequence of nonzero integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$|a_{i}| \leq 100$$$, $$$a_{i} \neq 0$$$) denoting the energies of seals.

For each door print a space separated sequence of nonzero integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$|b_{i}| \leq 100$$$, $$$b_{i} \neq 0$$$) denoting the seals that can open the door. If there are multiple valid answers, print any. It can be proven that at least one answer always exists.

NoteFor the first door Naruto can use energies $$$[-100, 1]$$$. The required equality does indeed hold: $$$1 \cdot (-100) + 100 \cdot 1 = 0$$$.For the second door Naruto can use, for example, energies $$$[1, 1, 1, -1]$$$. The required equality also holds: $$$1 \cdot 1 + 2 \cdot 1 + 3 \cdot 1 + 6 \cdot (-1) = 0$$$.

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  b = Array.new(n)

  (n / 2).times do |i|
    b[2 * i] = -a[2 * i + 1]
    b[2 * i + 1] = a[2 * i]
  end

  puts b.join(' ')
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  brr = arr.reverse
  brr.each_with_index do |_, i|
    brr[i] *= -1 if i % 2 == 0
  end
  puts brr.join ' '
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  arr = []
  (n/2).times do |i|
    lcm = a[i*2].lcm(a[i*2+1])
    arr << lcm / a[i*2]
    arr << -(lcm / a[i*2+1])
  end
  ans << arr
end
ans.each do |ar|
  ar.each do |v|
    print "#{v} "
  end
  puts ""
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  b = []
  (n / 2).times do |i|
    b.push(-a[i * 2 + 1])
    b.push(a[i * 2])
  end
  puts b.join(" ")
end


There is a robot staying at $$$X=0$$$ on the $$$Ox$$$ axis. He has to walk to $$$X=n$$$. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.The $$$i$$$-th segment of the path (from $$$X=i-1$$$ to $$$X=i$$$) can be exposed to sunlight or not. The array $$$s$$$ denotes which segments are exposed to sunlight: if segment $$$i$$$ is exposed, then $$$s_i = 1$$$, otherwise $$$s_i = 0$$$.The robot has one battery of capacity $$$b$$$ and one accumulator of capacity $$$a$$$. For each segment, you should choose which type of energy storage robot will use to go to the next point (it can be either battery or accumulator). If the robot goes using the battery, the current charge of the battery is decreased by one (the robot can't use the battery if its charge is zero). And if the robot goes using the accumulator, the current charge of the accumulator is decreased by one (and the robot also can't use the accumulator if its charge is zero).If the current segment is exposed to sunlight and the robot goes through it using the battery, the charge of the accumulator increases by one (of course, its charge can't become higher than it's maximum capacity).If accumulator is used to pass some segment, its charge decreases by 1 no matter if the segment is exposed or not.You understand that it is not always possible to walk to $$$X=n$$$. You want your robot to go as far as possible. Find the maximum number of segments of distance the robot can pass if you control him optimally.

The first line of the input contains three integers $$$n, b, a$$$ ($$$1 \le n, b, a \le 2 \cdot 10^5$$$) — the robot's destination point, the battery capacity and the accumulator capacity, respectively. The second line of the input contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$0 \le s_i \le 1$$$), where $$$s_i$$$ is $$$1$$$ if the $$$i$$$-th segment of distance is exposed to sunlight, and $$$0$$$ otherwise.

Print one integer — the maximum number of segments the robot can pass if you control him optimally.

NoteIn the first example the robot can go through the first segment using the accumulator, and charge levels become $$$b=2$$$ and $$$a=0$$$. The second segment can be passed using the battery, and charge levels become $$$b=1$$$ and $$$a=1$$$. The third segment can be passed using the accumulator, and charge levels become $$$b=1$$$ and $$$a=0$$$. The fourth segment can be passed using the battery, and charge levels become $$$b=0$$$ and $$$a=1$$$. And the fifth segment can be passed using the accumulator.In the second example the robot can go through the maximum number of segments using battery two times and accumulator one time in any order.

N, B, A = gets.split.map(&:to_i)
S = gets.chomp.split

ans = 0

b = B
a = A

S.each do |s|
  case s
  when '0'
    if a > 0
      a -= 1
    elsif b > 0
      b -= 1
    else
      break
    end
  when '1'
    if b > 0 && a < A
      b -= 1
      a += 1
    elsif a > 0
      a -= 1
    elsif b > 0
      b -= 1
    else
      break
    end
  end

  ans += 1
end

puts ans

n,a,b = gets.split.map(&:to_i)
s = gets.split.map(&:to_i)
c = b*1
n.times do |i|
    if s[i] == 0
        if c > 0
            c -= 1
        elsif a > 0
            a -= 1
        else
            puts i
            exit
        end
    else
        if a > 0 && c < b
            a -= 1
            c += 1
        elsif c > 0
            c -= 1
        else
            puts i
            exit
        end
    end
end
puts n

n,a,b = gets.split.map(&:to_i)
s = gets.split.map(&:to_i)
c = b
n.times do |i|
    if s[i] == 0
        if c > 0
            c -= 1
        elsif a > 0
            a -= 1
        else
            puts i
            exit
        end
    else
        if a > 0
            a -= 1
            c += 1
            c -= 1 if c > b
        else
            puts i
            exit
        end
    end
end
puts n


A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $$$k$$$-balanced if every substring of size $$$k$$$ of this bitstring has an equal amount of 0 and 1 characters ($$$\frac{k}{2}$$$ of each).You are given an integer $$$k$$$ and a string $$$s$$$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $$$k$$$-balanced bitstring by replacing every ? characters in $$$s$$$ with either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 3 \cdot 10^5$$$, $$$k$$$ is even)  — the length of the string and the parameter for a balanced bitstring. The next line contains the string $$$s$$$ ($$$|s| = n$$$). It is given that $$$s$$$ consists of only 0, 1, and ?. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print YES if we can replace every ? in $$$s$$$ with 0 or 1 such that the resulting bitstring is $$$k$$$-balanced, or NO if it is not possible.

NoteFor the first test case, the string is already a $$$4$$$-balanced bitstring.For the second test case, the string can be transformed into 101.For the fourth test case, the string can be transformed into 0110.For the fifth test case, the string can be transformed into 1100110.

gets.to_i.times{k=gets.split[1].to_i
a=[nil]*k
puts gets.chop.chars.zip(0..).map{|x,i|i%=k;x==??||a[i]==x||!a[i]&&a[i]=x}.all?&&[?0,?1].map{|x|a.take(k).count x}.max<=k/2 ?"YES":"NO"}


There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one.  At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints.

The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists.

Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them.

NoteThe first test sample is the one in the picture.

n = gets.to_i
path = gets.chomp.split('')
s = nil
r = nil
t = nil
l = nil
0.upto(n-1) do |i|
	s = i+1 if(path[i]=='R')&&(s.nil?)
       	r = i+1 if(path[i]!='R')&&(!s.nil?)&&(r.nil?)
	t = i if(path[i]=='L')&&(t.nil?)
	l = i if(path[i]!='L')&&(!t.nil?)&&(l.nil?)
end
s = l if s.nil?
t = r if t.nil?
puts "#{s} #{t}"

n = gets.chomp.to_i
path = gets.chomp
ls = []
rs = []
n.times do |i|
    c = path[i]
    ls << i + 1 if c == 'L'
    rs << i + 1 if c == 'R'
end
s = t = 0
if ls.length == 0
    s = rs.min
    t = rs.max + 1
elsif rs.length == 0
    s = ls.max
    t = ls.min - 1
else
    s = rs.min
    t = rs.max + 1
end
puts "#{s} #{t}"

gets.to_i
s = gets
if s.index('R').nil?
  b = s.index('L')
  a = s.index('.', b)
elsif s.index('L').nil?
  a = s.index('R') + 1
  b = s.index('.', a - 1) + 1
else
  a = s.index('R') + 1
  b = s.index('L')
end
puts "#{a} #{b}"

n=gets.to_i
a=gets.chomp.split('')
s,t=a.rindex('R'),a.index('L')
puts s ? "#{s+1} #{s+2}" : "#{t+1} #{t}"

n = gets.to_i
arr = gets.split("")
l_index = arr.index("L")
r_index = arr.index("R")
l_last_index = arr.rindex("L")
r_last_index = arr.rindex("R")

ans = false

unless l_index
	s,t = r_index,r_last_index+1
	ans = true
end

unless r_index
	s,t = l_last_index,l_index - 1
	ans = true
end

if !ans
	s,t = r_index,r_last_index
end

puts "#{s+1} #{t+1}"

#!/usr/bin/ruby -w
n = gets
s = gets
i = 0
while s[i] == '.' do
    i = i + 1
end
print i + 1
print " "
while s[i] != 'L' && s[i] != '.' do
    i = i + 1
end
if(s[i] == '.')
print i + 1
else
    print i
end
puts

n = gets.to_i
blocks = gets.chomp
s = blocks.index("R")
if s
    puts [s+1, n-blocks.reverse.index("R")+1].join(" ")
    exit
end
t = blocks.index("L")
if t
    puts [n-blocks.reverse.index("L"),t].join(" ")
end

l=gets.to_i
s=gets.split(//)
i=0
x=-1
y=-1
while (i<l) do
  if (s[i]=='R') then y=i; end
  i+=1
end
i=l-1
while (i>=0) do
  if (s[i]=='L') then x=i; end
  i-=1
end
if (x==-1) then print(y+1," ",y+2,"\n");
else
  if (y==-1) then print(x+1," ",x,"\n");
  else print(x+1," ",x+1,"\n");
  end
end

gets # Skip the first line
fp = gets.chomp
if fp.include?('R')
  if fp.include?('L')
    puts "#{fp.index('R') + 1} #{fp.rindex('R') + 1}"
  else
    puts "#{fp.index('R') + 1} #{fp.rindex('R') + 2}"
  end
else
  puts "#{fp.rindex('L') + 1} #{fp.index('L')}"
end

n=gets.to_i
a=gets.chomp.split('')
en,st=0,0
for i in 0...a.length
	break if a[i]!='.'
end
if a[i]=='R'
	st=i
	i+=1 while a[i]=='R'
	en = (a[i]=='L')? i-1 : i
else
	en=i-1
	i+=1 while a[i]=='L'
	st=i-1
end
puts "#{st+1} #{en+1}"

n = gets.to_i
moves = gets
strs = moves.index 'R'
ends = moves.rindex 'R'
if strs.nil?
    strs = moves.rindex 'L'
    ends = moves.index 'L'
    ends -= 1
else
    ends += 1
end
puts "#{strs + 1} #{ends + 1}"

def run
  n = $stdin.gets.to_i
  str = $stdin.gets.split(//)

  s = str.rindex('R')
  t = str.index('L')

  if s != nil
    puts "#{s + 1} #{s + 2}"
  else
    puts "#{t + 1} #{t}"
  end
end

run if $0 == __FILE__

class A
  def initialize
    n = $stdin.gets.chomp.to_i
    step = $stdin.gets.chomp.split('')

    s = t = 0
    s_flag = true
    t_flag = true
    r_max = 0
    l_max = 0

    step.each_with_index do |ch, index|
      if ch == 'R' && s_flag
        s = index+1
        s_flag = false
      elsif ch == 'L' && t_flag
        t = index
        t_flag = false
      end

      if ch == 'R'
        r_max = index+1
      elsif ch == 'L'
        l_max = index+1
      end
    end

    if s_flag
      s = l_max
    end

    if t_flag
      t = r_max + 1
    end

    puts "#{s} #{t}"
  end
end

a = A.new

n = gets.chomp.to_i
path = gets.chomp
s = t = 0
dir = nil
n.times do |c|
    s = c + 1 if path[c] != '.' && s == 0
    dir = path[c] if dir.nil? && path[c] != '.'
    t = c - 1 if !dir.nil? && path[c] != '.' && dir != path[c]
end
puts "#{s} #{t}"

gets.chomp.to_i
path = gets.chomp
index = 0
pos = []
finish = false
while !finish
    c = path[index]
    if c != '.'
        if c == 'R'
            index += 1
            if !pos.include?( index )
                pos << index
            else
                finish = true
            end
        else
            index -= 1
            if !pos.include?( index )
                pos << index
            else
                finish = true
            end
        end
        next
    end
    index += 1
end
s = pos.min
t = pos.max
puts "#{s} #{t}"

n = gets.chomp.to_i
path = gets.chomp
ls = []
rs = []
n.times do |i|
    c = path[i]
    ls << i + 1 if c == 'L'
    rs << i + 1 if c == 'R'
end
s = t = 0
if ls.length == 0
    s = rs.min
    t = rs.max
elsif rs.length == 0
    s = ls.max
    t = ls.min
else
    s = rs.min
    t = rs.max
end
puts "#{s} #{t}"

n = gets.to_i
arr = gets.split("")
l_index = arr.index("L")
r_index = arr.index("R")
l_last_index = arr.rindex("L")
r_last_index = arr.rindex("R")

ans = false

unless l_index
	s,t = r_index,r_last_index
	ans = true
end

unless r_index
	s,t = l_last_index,l_index
	ans = true
end

if !ans
	s,t = r_index,r_last_index
end

puts "#{s+1} #{t+1}"

n = gets.to_i
arr = gets.split("")
l_index = arr.index("L")
r_index = arr.index("R")
l_last_index = arr.rindex("L")
r_last_index = arr.rindex("R")

ans = false

unless l_index
	s,t = r_index,r_last_index+1
	ans = true
end

unless r_index
	s,t = l_last_index-1,l_index
	ans = true
end

if !ans
	s,t = r_index,r_last_index
end

puts "#{s+1} #{t+1}"

n = gets.to_i
arr = gets.split("")
l_index = arr.index("L")
r_index = arr.index("R")
l_last_index = arr.rindex("L")
r_last_index = arr.rindex("R")

ans = false

unless l_index
	s,t = r_index,r_last_index+1
	ans = true
end

unless r_index
	s,t = l_last_index,l_index
	ans = true
end

if !ans
	s,t = r_index,r_last_index
end

puts "#{s+1} #{t+1}"

l=gets.to_i
s=gets.split(//)
i=0
x=-1
y=-1
while (i<l) do
  if (s[i]=='R') then y=i; end
  i+=1
end
i=l-1
while (i>=0) do
  if (s[i]=='L') then x=i; end
  i-=1
end
if (x==-1) then print(y+1," ",y+1,"\n");
else print(x+1," ",x+1,"\n");end

l=gets.to_i
s=gets.split(//)
i=0
x=-1
y=-1
while (i<l) do
  if (s[i]=='R') then y=i; end
  i+=1
end
i=l-1
while (i>=0) do
  if (s[i]=='L') then x=i; end
  i-=1
end
if (x==-1) then print(y+1," ",y,"\n");
else
  if (y==-1) then print(x+1," ",x+2,"\n");
  else print(x+1," ",x+1,"\n");
  end
end

n=gets.to_i
a=gets.chomp.split('')
b=[]
a.each do |i|
	b<<i if i!='.'
end
if b.uniq.count==1
	if b.first=='R'
		puts "#{a.index('R')+1} #{a.rindex('R')+1}"
	elsif b.first=='L'
		puts "#{a.rindex('L')+1} #{a.index('L')+1}"
	end
else
	puts "#{a.index('R')+1} #{a.index('L')+1}"
end

n = gets.to_i
moves = gets
if moves.index 'L'
    strs = moves.index 'R'
    ends = moves.rindex 'R'
else
    strs = moves.rindex 'R'
    ends = moves.index 'R'
end
if strs.nil?
    strs = moves.index 'L'
    ends = moves.rindex 'L'
end
puts "#{strs + 1} #{ends + 1}"

n = gets.to_i
moves = gets
strs = moves.index 'R'
ends = moves.rindex 'R'
if strs.nil?
    strs = moves.index 'L'
    ends = moves.rindex 'L'
end
puts "#{strs + 1} #{ends + 1}"

n = gets.to_i
moves = gets
strs = moves.index 'R'
ends = moves.rindex 'R'
if strs.nil?
    strs = moves.index 'L'
    ends = moves.rindex 'L'
    ends -= 1
else
    ends += 1
end
puts "#{strs + 1} #{ends + 1}"

def run
  n = $stdin.gets.to_i
  str = $stdin.gets.split(//)

  s = 0, t = -1
  str.each_with_index do |item, index|
    s = index if item == 'R'
    t = index if item == 'L' and t == -1
  end

  puts "#{s} #{t}"
end

run if $0 == __FILE__

class A
  def initialize
    n = $stdin.gets.chomp.to_i
    step = $stdin.gets.chomp.split('')

    s = t = 0
    s_flag = true
    t_flag = true

    step.each_with_index do |ch, index|
      if ch == 'R' && s_flag
        s = index+1
        s_flag = false
      elsif ch == 'L' && t_flag
        t = index
        t_flag = false
      end
    end

    puts "#{s} #{t}"
  end
end

a = A.new

n = gets.to_i
path = gets.chomp.split('')
s = nil
r = nil
t = nil
l = nil
0.upto(n-1) do |i|
	s = i+1 if(path[i]=='R')&&(s.nil?)
       	r = i+1 if(path[i]!='R')&&(!s.nil?)
	t = i if(path[i]=='L')&&(t.nil?)
	l = i if(path[i]!='L')&&(!t.nil?)
end
s = l if s.nil?
t = r if t.nil?
puts "#{s} #{t}"


You are given a pair of integers $$$(a, b)$$$ and an integer $$$x$$$.You can change the pair in two different ways:   set (assign) $$$a := |a - b|$$$;  set (assign) $$$b := |a - b|$$$,  where $$$|a - b|$$$ is the absolute difference between $$$a$$$ and $$$b$$$.The pair $$$(a, b)$$$ is called $$$x$$$-magic if $$$x$$$ is obtainable either as $$$a$$$ or as $$$b$$$ using only the given operations (i.e. the pair $$$(a, b)$$$ is $$$x$$$-magic if $$$a = x$$$ or $$$b = x$$$ after some number of operations applied). You can apply the operations any number of times (even zero).Your task is to find out if the pair $$$(a, b)$$$ is $$$x$$$-magic or not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains three integers $$$a$$$, $$$b$$$ and $$$x$$$ ($$$1 \le a, b, x \le 10^{18}$$$).

For the $$$i$$$-th test case, print YES if the corresponding pair $$$(a, b)$$$ is $$$x$$$-magic and NO otherwise.

main = -> {
  t = int
  t.times do
    a, b, x = ints
    a, b = [a, b].minmax
    yesno solve(a, b, x)
  end
}

def solve(a, b, x)
  # STDERR.puts "(%d, %d, %d)" % [a, b, x]
  return true if a == x or b == x
  return false if a == 0 or b == 0
  a, b = [a, b].minmax
  c = b % a
  return true if (b - x) % a == 0 and b >= x
  solve(a, c, x)
end

# def solve(a, b, x)
#   return false if x > a and x > b
#   return true if a == x or b == x
#   return false if a == 0 or b == 0
#   a, b = [a, b].minmax
#   return true if (b - x) % a == 0
#   c = b % a
#   solve(a, c, x) or solve(b, c, x)
# end

DEBUG = true
MOD = 10**9+7
YESNO = %w(NO YES)
INF = 10**9

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]

main = -> {
  t = int
  t.times do
    a, b, x = ints
    a, b = [a, b].minmax
    yesno solve(a, b, x)
  end
}

def solve(a, b, x)
  return false if x > a and x > b
  return true if a == x or b == x
  return false if a == 0 or b == 0
  a, b = [a, b].minmax
  return true if (b - x) % a == 0
  c = b % a
  solve(a, c, x) or solve(b, c, x)
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(NO YES)
INF = 10**9

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]

main = -> {
  t = int
  t.times do
    a, b, x = ints
    yesno solve(a, b, x)
  end
}

def solve(a, b, x)
  return false if x > a and x > b
  return true if a == x or b == x
  a, b = [a, b].minmax
  while a > 0 and b > 0
    return true if (b - x) % a == 0
    c = b - a
    return true if c == x
    a, b = [a, c].minmax
  end
  false
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(NO YES)
INF = 10**9

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]


Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.

The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.

In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.

class Solution
  def initialize
    @n = gets.to_i
    @a = gets.split.map(&:to_i)
    @b = gets.split.map(&:to_i)
    @m = []
  end

  def move(i)
    return if @a[i] == @b[i]
    j = i
    j += 1 while @b[j] != @a[i]
    j.downto(i+1).each do |k|
      @m << k-1
      @b[k-1], @b[k] = @b[k], @b[k-1]
    end
  end

  def solve
    (0...@n).each {|i| move(i)}
    puts @m.size
    @m.each {|x| printf("%d %d\n", x+1, x+2)}
  end
end

solution = Solution.new
solution.solve

n=gets.to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
z=[]
n.times{|i|
	j=i;
	j+=1 while a[i]!=b[j];
	j.downto(i+1){|k|
		b[k],b[k-1]=b[k-1],b[k]
		z<<[k,k+1]
	}
}
p z.size
z.each{|x,y|
	print "#{x} #{y}\n"
}


One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated – it consists of n brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly:   It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains).  There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false. If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid.

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n, a ≠ b).

The output consists of one line, containing either yes or no depending on whether the nervous system is valid.

nodes, edges = gets.split(' ').map(&:to_i)
g = {}
edges.times do
  from, to = gets.split(' ').map(&:to_i)
  g[from] ||= []
  g[from].push(to)
  g[to] ||= []
  g[to].push(from)
end

$g = g
$visited = {}

def dfs(node, prev)
  $visited[node] = true

  ($g[node] || []).each do |nxt|
    next if nxt == prev

    if $visited[nxt]
      puts 'no'
      exit
    else
      dfs(nxt, node)
    end
  end
end

dfs($g.first.first, 0)

if $visited.size == $g.size
  puts 'yes'
else
  puts 'no'
end


The Bitlandians are quite weird people. They have very peculiar customs.As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000.Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500.Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.

The first line contains integer n (1 ≤ n ≤ 106) — the number of eggs. Next n lines contain two integers ai and gi each (0 ≤ ai, gi ≤ 1000; ai + gi = 1000): ai is the price said by A. for the i-th egg and gi is the price said by G. for the i-th egg.

If it is impossible to assign the painting, print "-1" (without quotes). Otherwise print a string, consisting of n letters "G" and "A". The i-th letter of this string should represent the child who will get the i-th egg in the required distribution. Letter "A" represents A. and letter "G" represents G. If we denote the money Uncle J. must pay A. for the painting as Sa, and the money Uncle J. must pay G. for the painting as Sg, then this inequality must hold: |Sa  -  Sg|  ≤  500.  If there are several solutions, you are allowed to print any of them.

s=0
n=gets.to_i
n.times do
	a,b=gets.chomp.split.map(&:to_i)
	s+=a
end
i=n-(s+499)/1000
puts "A"*i + "G"*(n-i)

n = gets.to_i
ta = tb = 0
n.times do
    a, b = gets.split.map{|i| i.to_i}
    ta += a
    tb += b
end
if ta % 1000 <= 500
    n.times do |i|
       if i < ta / 1000 then  print 'G'
       else print 'A'
       end
    end
elsif tb % 1000 <= 500
    n.times do |i|
        if i < tb / 1000 then print 'A'
        else print 'G'
        end
    end
else
    puts -1
end

def run
  n = $stdin.gets.to_i
  sum = 0
  $stdin.readlines.each do |line|
    a, g = line.split.map(&:to_i)
    sum += a
  end

  i = n - (sum + 499) / 1000
  puts "A" * i + "G" * (n - i)
end

run if $0 == __FILE__

n = gets.to_i

# a = []
# g = []

answer = ''
a_cur = 0
g_cur = 0

n.times do |i|
	a, g = gets.split(' ').collect!{|i| i.to_i}
	if (a_cur + a - g_cur).abs <= 500
		answer << "A"
		a_cur += a
	else
		answer << "G"
		g_cur += g
	end
end

# answer = -1  if (a_cur - g_cur).abs > 500

print answer

n = gets.to_i
s_a = 0
s_g = 0
A = "A"
ans = ""
# ans = A*n
# if n < 1000
G = "G"
n.times do |i|
	a,b = gets.split(" ")
	a = a.to_i
	b = b.to_i

	x = s_a + a
	if (x - s_g) <= 500
		s_a = x
		ans << A
	else
		s_g += b
		ans << G
	end
end

if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s = 0
(1..n).each {
	a,g = gets.chomp.split(" ").collect! {|x| x.to_i}
	s += a
}

p = s/1000.0
if p>=p.floor+0.5
	k = p.floor+1
else
	k = p.floor
end

res = "G"*k+"A"*(n-k)

puts res

n = gets.to_i
sa = 0
sg = 0
(0...n).each do |i|
    a, g = gets.split.collect{|i| i.to_i}
    if (sa+a-sg).abs <= 500
        sa += a
        print "A"
    else
        sg += g
        print "G"
    end
end
print "\n"

def run
  n = $stdin.gets
  sa = 0
  sg = 0
  ret = ""
  $stdin.readlines.each do |line|
    a, g = line.split.map(&:to_i)
    if sa <= sg + 500
      sa += a
      ret += "A"
    else
      sg += g
      ret += "G"
    end
  end

  if (sa - sg).abs <= 500
    puts ret
  else
    puts "-1"
  end
end

run if $0 == __FILE__

def run
  n = $stdin.gets.to_i
  sum = 0
  $stdin.readlines.each do |line|
    a, g = line.split.map(&:to_i)
    sum += a
  end

  i = n - (sum + 499) / 1000
  puts "A" * i + "G" * (n - 1)
end

run if $0 == __FILE__

def run
  n = $stdin.gets
  sa = 0
  sg = 0
  ret = ""
  $stdin.readlines.each do |line|
    a, g = line.split.map(&:to_i)
    if sa < sg
      sa += a
      ret += "A"
    else
      sg += g
      ret += "G"
    end
  end

  if (sa - sg).abs <= 500
    puts ret
  else
    puts "-1"
  end
end

run if $0 == __FILE__

def run
  n = $stdin.gets
  sa = 0
  sg = 0
  ret = ""
  $stdin.readlines.each do |line|
    a, g = line.split.map(&:to_i)
    if sa <= sg
      sa += a
      ret += "A"
    else
      sg += g
      ret += "G"
    end
  end

  if (sa - sg).abs <= 500
    puts ret
  else
    puts "-1"
  end
end

run if $0 == __FILE__

n = gets.to_i

a = []
g = []

a_sum = 0
g_sum = 0

n.times do |i|
	a[i], g[i] = gets.split(' ').collect!{|i| i.to_i}
	a_sum += a[i]
	g_sum += g[i]
end

# a_sr = a_sum / n
# g_sr = g_sum / n

answer = ''
a_cur = 0
g_cur = 0

# n.times do |i|
# 	if a_cur + a[i] < g_sr
# 		answer << "A"
# 		a_cur += a[i]
# 	elsif g_cur + g[i] < a_sr
# 		answer << "G"
# 		g_cur += g[i]
# 	elsif (a_cur + a_sum - g_cur - g_sum + g[i]).abs <= 500
# 		answer << "A"
# 		a_cur += a[i]
# 	elsif (g_cur + g_sum - a_cur -a_sum + a[i]).abs <= 500
# 		answer << "G"
# 		g_cur += g[i]
# 	else
# 		answer = -1
# 		break
# 	end

# 	a_sum -= a[i]
# 	g_sum -= g[i]
# end

n.times do |i|
	a_sum -= a[i]
	g_sum -= g[i]
	if (a_cur + a[i] + a_sum - g_cur - g_sum).abs <= 500
		answer << "A"
		a_cur += a[i]
	else
		answer << "G"
		g_cur += g[i]
	end
end
# print answer
answer = -1  if (a_cur - g_cur).abs > 500

print answer

n = gets.to_i

a = []
g = []

# a_sum = 0
# g_sum = 0

answer = ''
a_cur = 0
g_cur = 0

n.times do |i|
	a[i], g[i] = gets.split(' ').collect!{|i| i.to_i}
	# a_sum += a[i]
	# g_sum += g[i]

	if g_cur >= a_cur
		answer << "A"
		a_cur += a[i]
	else
		answer << "G"
		g_cur += g[i]
	end
end

answer = -1  if (a_cur - g_cur).abs > 500

print answer

n = gets.to_i

a = []
g = []

a_sum = 0
g_sum = 0
n.times do |i|
	a[i], g[i] = gets.split(' ').collect!{|i| i.to_i}
	a_sum += a[i]
	g_sum += g[i]
end

answer = -1

if (a_sum/n - g_sum/n).abs <= 500
	answer = ''
	a.sort!.reverse!
	g.sort!.reverse!
	a_cur = 0
	g_cur = 0

	n.times do |i|
		if g_cur >= a_cur
			answer << "A"
			a_cur += a[i]
		else
			answer << "G"
			g_cur += g[i]
		end
	end
end

print answer

n = gets.to_i

a = []
g = []

a_sum = 0
g_sum = 0

n.times do |i|
	a[i], g[i] = gets.split(' ').collect!{|i| i.to_i}
	a_sum += a[i]
	g_sum += g[i]
end

a_sr = a_sum / n
g_sr = g_sum / n

answer = ''
a_cur = 0
g_cur = 0

n.times do |i|
	if a_cur + a[i] < g_sr
		answer << "A"
		a_cur += a[i]
	elsif g_cur + g[i] < a_sr
		answer << "G"
		g_cur += g[i]
	elsif (a_cur + a_sum - g_cur - g_sum + g[i]).abs <= 500
		answer << "A"
		a_cur += a[i]
	elsif (g_cur + g_sum - a_cur -a_sum + a[i]).abs <= 500
		answer << "G"
		g_cur += g[i]
	else
		answer = -1
		break
	end

	a_sum -= a[i]
	g_sum -= g[i]
end

answer = -1  if (a_cur - g_cur).abs > 500

print answer

n = gets.to_i
s_a = 0
s_g = 0
ans = ""
if n < 1000
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		ans << "A"
	else
		s_g += b
		ans << "G"
	end
end
else
	n.times do
		a,b = gets.split(" ").map(&:to_i)
		(s_a + a - s_g) <= 500
	end

end
if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s_a = 0
s_g = 0
ans = "A"*n
if n < 1000
n.times do |i|
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		# ans << "A"
	else
		s_g += b
		ans[i] = "G"
	end
end
else
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		# ans << "A"
	else
		s_g += b
		ans << "G"
	end
end

end
if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s_a = 0
s_g = 0
ans = ""
if n < 1000
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		ans << "A"
	else
		s_g += b
		ans << "G"
	end
end
else
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		# ans << "A"
	else
		s_g += b
		ans << "G"
	end
end

end
if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s_a = 0
s_g = 0
ans = ""
if n < 1000
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		ans << "A"
	else
		s_g += b
		ans << "G"
	end
end
else
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		# ans << "A"
	else
		s_g += b
		# ans << "G"
	end
end

end
if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s_a = 0
s_g = 0
ans = ""
if n < 1000
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		ans << "A"
	else
		s_g += b
		ans << "G"
	end
end
else
	n.times do
		a,b = gets.split(" ").map(&:to_i)
	end

end
if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s = 0
(1..n).each {
	a,g = gets.chomp.split(" ").collect! {|x| x.to_i}
	s += a
}

p = s/1000.0
if p>=p.floor+0.5
	k = p.floor+1
else
	k = p.floor
end

res = "A"*k+"G"*(n-k)

puts res

n = gets.to_i
a = Array.new
b = Array.new
ans = Array.new(n)
(1..n).each do
    tmp = gets.split.collect{|i| i.to_i}
    a.push(tmp[0])
    b.push(tmp[1])
end
diff = (0...n).collect{|i| [a[i]-b[i],i]}.sort
tmp = 0
diff.each do |i|
    if (tmp+i[0]).abs <= (tmp-i[0]).abs
        if i[0] <= 0
            ans[i[1]] = "A"
        else
            ans[i[1]] = "G"
        end
        tmp += i[0]
    else
        if i[0] <= 0
            ans[i[1]] = "G"
        else
            ans[i[1]] = "A"
        end
        tmp -= i[0]
    end
end
if tmp.abs <= 500
    puts ans.join
else
    puts "-1"
end


As it has been found out recently, all the Berland's current economical state can be described using a simple table n × m in size. n — the number of days in each Berland month, m — the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information — the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p.

The first line contains integers n and m (1 ≤ n, m ≤ 1000). The second line contains the integer k (0 ≤ k < max(n, m)) — the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 ≤ a ≤ n) — the number of the table row, b (1 ≤ b ≤ m) — the number of the column, c — the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 ≤ p ≤ 109 + 7).

Print the number of different tables that could conform to the preserved data modulo p.

# 2**n % p
def remainder(n, p)
  return 1 if n == 0
  m = n / 2
  r = (remainder(m, p) * remainder(m, p)) % p
  return (n % 2 == 0 ? r: (r * 2) % p)
end

n, m = gets.split.map(&:to_i)
# for simplicity, assume n >= m
transpose = false
if n < m
  n, m = m, n
  transpose = true
end

plus_one = Array.new(n, 0)
minus_one = Array.new(n, 0)

k = gets.to_i
(1..k).each do
  a, b, c = gets.split.map(&:to_i)
  a, b = b, a if transpose
  if c > 0
    plus_one[a-1] += 1
  else
    minus_one[a-1] += 1
  end
end
p = gets.to_i

if (n + m) % 2 == 1
  puts 0
  exit
end

exponent = - m + 1
(0...n).each do |i|
  if (plus_one[i] + minus_one[i] == m and minus_one[i] % 2 == 0)
    puts 0
    exit
  else
    exponent += [m - plus_one[i] - minus_one[i] - 1, 0].max
  end
end

puts(remainder(exponent, p))

# 2**n % p
def remainder(n, p)
  return 1 if n == 0
  m = n / 2
  r = (remainder(m, p) * remainder(m, p)) % p
  return (n % 2 == 0 ? r: (r * 2) % p)
end

n, m = gets.split.map(&:to_i)
k = gets.to_i
has_one = false
(1..k).each do
  a, b, c = gets.split.map(&:to_i)
  has_one = true if c == 1
end
p = gets.to_i
if n > 1 and m > 1
  puts(remainder((n-1)*(m-1)-k, p))
else
  if has_one
    result = 0
  else
    result = ((n + m - 1) % 2 == 0 ? 0 : 1)
  end
  puts result
end


Nastia has received an array of $$$n$$$ positive integers as a gift.She calls such an array $$$a$$$ good that for all $$$i$$$ ($$$2 \le i \le n$$$) takes place $$$gcd(a_{i - 1}, a_{i}) = 1$$$, where $$$gcd(u, v)$$$ denotes the greatest common divisor (GCD) of integers $$$u$$$ and $$$v$$$.You can perform the operation: select two different indices $$$i, j$$$ ($$$1 \le i, j \le n$$$, $$$i \neq j$$$) and two integers $$$x, y$$$ ($$$1 \le x, y \le 2 \cdot 10^9$$$) so that $$$\min{(a_i, a_j)} = \min{(x, y)}$$$. Then change $$$a_i$$$ to $$$x$$$ and $$$a_j$$$ to $$$y$$$.The girl asks you to make the array good using at most $$$n$$$ operations.It can be proven that this is always possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_{n}$$$ ($$$1 \le a_i \le 10^9$$$) — the array which Nastia has received as a gift. It's guaranteed that the sum of $$$n$$$ in one test doesn't exceed $$$2 \cdot 10^5$$$.

For each of $$$t$$$ test cases print a single integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of operations. You don't need to minimize this number. In each of the next $$$k$$$ lines print $$$4$$$ integers $$$i$$$, $$$j$$$, $$$x$$$, $$$y$$$ ($$$1 \le i \neq j \le n$$$, $$$1 \le x, y \le 2 \cdot 10^9$$$) so that $$$\min{(a_i, a_j)} = \min{(x, y)}$$$ — in this manner you replace $$$a_i$$$ with $$$x$$$ and $$$a_j$$$ with $$$y$$$. If there are multiple answers, print any.

NoteConsider the first test case.Initially $$$a = [9, 6, 3, 11, 15]$$$.In the first operation replace $$$a_1$$$ with $$$11$$$ and $$$a_5$$$ with $$$9$$$. It's valid, because $$$\min{(a_1, a_5)} = \min{(11, 9)} = 9$$$.After this $$$a = [11, 6, 3, 11, 9]$$$.In the second operation replace $$$a_2$$$ with $$$7$$$ and $$$a_5$$$ with $$$6$$$. It's valid, because $$$\min{(a_2, a_5)} = \min{(7, 6)} = 6$$$.After this $$$a = [11, 7, 3, 11, 6]$$$ — a good array.In the second test case, the initial array is already good.

$, = " "
gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    mn, pos = 1E9.to_i + 7, -1
    n.times do |i|
        if a[i] < mn
            mn = a[i]
            pos = i
        end
    end
    puts n - 1
    n.times do |i|
        next if i == pos
        print pos + 1, i + 1, mn, mn + (i - pos).abs, "\n"
    end
end

$, = " "
gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    mn, pos = 1E9.to_i + 7, -1
    n.times do |i|
        if a[i] < mn
            mn = a[i]
            pos = i
        end
    end
    puts(n - 1)
    n.times do |i|
        next if i == pos
        print pos + 1, i + 1, mn, mn + (i - pos).abs, "\n"
    end
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.strip.split.map {|x| x.to_i }

  minv = a.min
  minv_i = a.find_index(minv)

  x = minv + 1
  while minv.gcd(x) != 1
    x += 1
  end

  printf("%d\n", n - 1)
  0.upto(n - 1) do |i|
    next if i == minv_i
    if (i % 2) != (minv_i) % 2
      printf("%d %d %d %d\n", i + 1, minv_i + 1, x, minv)
    else
      printf("%d %d %d %d\n", i + 1, minv_i + 1, minv, minv)
    end
  end
end

$, = " "
gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    mn, pos = 1E9.to_i + 7, -1
    n.times do |i|
        if a[i] < mn
            mn = a[i]
            pos = i
        end
    end
    n.times do |i|
        next if i == pos
        print pos + 1, i + 1, mn, mn + (i - pos).abs, "\n"
    end
end


Vasya is a Greencode wildlife preservation society proponent. One day he found an empty field nobody owned, divided it into n × m squares and decided to plant a forest there. Vasya will plant nm trees of all different heights from 1 to nm. For his forest to look more natural he wants any two trees growing in the side neighbouring squares to have the absolute value of difference in heights to be strictly more than 1. Help Vasya: make the plan of the forest planting for which this condition is fulfilled.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — the number of rows and columns on Vasya's field

If there's no solution, print -1. Otherwise, print n lines containing m numbers each — the trees' planting plan. In every square of the plan the height of a tree that should be planted on this square should be written. If there are several solutions to that problem, print any of them.