Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$. Bob lives near the station with number $$$1$$$, while Alice lives near the station with number $$$s$$$. The metro line has two tracks. Trains on the first track go from the station $$$1$$$ to the station $$$n$$$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.Some stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$2 \le s \le n \le 1000$$$) — the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station $$$1$$$. Next lines describe information about closed and open stations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$). If $$$a_i = 1$$$, then the $$$i$$$-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$b_i = 0$$$ or $$$b_i = 1$$$). If $$$b_i = 1$$$, then the $$$i$$$-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second track.

Print "YES" (quotes for clarity) if Bob will be able to commute to the Alice's home by metro and "NO" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).

NoteIn the first example, all stations are opened, so Bob can simply travel to the station with number $$$3$$$.In the second example, Bob should travel to the station $$$5$$$ first, switch to the second track and travel to the station $$$4$$$ then.In the third example, Bob simply can't enter the train going in the direction of Alice's home.

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

if(a[0]==0 || (a[s-1]==0 && b[s-1]==0)) then puts("NO")
elsif(a[s-1]==1) then puts("YES")
elsif(b[s-1]==0) then puts("NO")
else
	flag = 0
	for i in (s...n) do
		if(a[i]==1 && b[i]==1) then flag = 1; break; end
	end
	if(flag==1) then puts("YES")
	else puts("NO") end
end

def can_travel(alice_station, from_bob_metro, to_bob_metro)
    return "NO" if from_bob_metro[0] == 0

    return "YES" if from_bob_metro[alice_station - 1] == 1

    index = alice_station
    while index < from_bob_metro.length && from_bob_metro[index] + to_bob_metro[index] != 2
        index += 1
    end

    return "NO" if index == from_bob_metro.length
    return "YES" if to_bob_metro[alice_station - 1] == 1
    "NO"
end

number_of_stations, alice_station = gets.chomp.split(" ").map(&:to_i)
from_bob_metro = gets.chomp.split(" ").map(&:to_i)
to_bob_metro = gets.chomp.split(" ").map(&:to_i)

puts can_travel(alice_station, from_bob_metro, to_bob_metro)

n,s = gets.strip.split.map(&:to_i)
s -= 1

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

li = -1
poss = []
if a[0]==1
  0.upto(n-1).each do |i|
    if a[i]==1
      poss << i
      if b[i] == 1
        li = i
      end
    end
  end
end

# puts li
if li>-1
  li.downto(0) do |i|
    if b[i] == 1
      poss << i
    end
  end
end

puts (poss.include?(s) ? "YES" : "NO")

n, s = gets.split.map(&:to_i)
A = gets.split.map(&:to_i)
B = gets.split.map(&:to_i)
Ad = A[s..n]

if A[0] == 0
  print "NO"
elsif A[s - 1] == 1
  print "YES"
elsif B[s - 1] == 0
  print "NO"
elsif !Ad.include?(1)
  print "NO"
elsif Ad.each.with_index().any? { |v, i| v == 1 && B[i + s] == 1}
  print "YES"
else
  print "NO"
end

n, s = gets.split.map(&:to_i)
A = gets.split.map(&:to_i)
B = gets.split.map(&:to_i)
Ad = A[s..n]

if A[0] == 0
  print "NO"
elsif A[s - 1] == 1
  print "YES"
elsif B[s - 1] == 0
  print "NO"
elsif !Ad.include?(1)
  print "NO"
elsif Ad.each.with_index().any? { |v, i| v == 1 && B[i + s - 1] == 1 }
  print "YES"
else
  print "NO"
end

n, s = gets.split.map(&:to_i)
A = gets.split.map(&:to_i)
B = gets.split.map(&:to_i)
Ad = A[s..n]

if A[0] == 0
  print "NO"
elsif A[s] == 1
  print "YES"
elsif B[s] == 0
  print "NO"
elsif !Ad.include?(1)
  print "NO"
elsif Ad.with_index.any? { |(v, i)| v == 1 && B[i + s] == 1 }
  print "YES"
else
  print "NO"
end


Polycarp likes to play with numbers. He takes some integer number $$$x$$$, writes it down on the board, and then performs with it $$$n - 1$$$ operations of the two kinds:   divide the number $$$x$$$ by $$$3$$$ ($$$x$$$ must be divisible by $$$3$$$);  multiply the number $$$x$$$ by $$$2$$$. After each operation, Polycarp writes down the result on the board and replaces $$$x$$$ by the result. So there will be $$$n$$$ numbers on the board after all.You are given a sequence of length $$$n$$$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists.

The first line of the input contatins an integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the number of the elements in the sequence. The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 3 \cdot 10^{18}$$$) — rearranged (reordered) sequence that Polycarp can wrote down on the board.

Print $$$n$$$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists.

NoteIn the first example the given sequence can be rearranged in the following way: $$$[9, 3, 6, 12, 4, 8]$$$. It can match possible Polycarp's game which started with $$$x = 9$$$.

def count_factor(n, f)
  count = 0
  crt = n
  while crt % f == 0
    crt /= f
    count += 1
  end
  count
end

def arrange ns
  ns.map{ |n| [n, count_factor(n, 2), count_factor(n, 3)] }
    .sort_by { |_, c2, c3| [-c3, c2] }
    .map { |n, _, _| n }
end

def solution
  read_int
  ns = read_ints

  puts arrange(ns).join(' ')
end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']


In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.

The first line contains two integers n (1 ≤ n ≤ 103) and x (1 ≤ x ≤ n) — the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ n) — the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue. The input limits for scoring 30 points are (subproblem B1):    It is guaranteed that the number of zero elements ai doesn't exceed 20.  The input limits for scoring 100 points are (subproblems B1+B2):    The number of zero elements ai is arbitrary.

Print all possible positions of the Smart Beaver in the line in the increasing order.

#! ruby -Ku
# -*- coding: utf-8 -*-
# file = open("input.txt")
# total_sb = file.gets.split.map(&:to_i)
# follow = file.gets.split.map(&:to_i) # [i]+1 follows follow[i]
total_sb = gets.split.map(&:to_i)
follow = gets.split.map(&:to_i) # [i]+1 follows follow[i]

num_total = total_sb.shift
sb_num = total_sb.shift

chain = Struct.new("Chain", :length, :check)
chains = Array::new
num_total.times{chains << chain.new(1, false)}

# make chains
def trace_chain(follow, chains, index, length)
  if follow[index] == 0
    chains[index].length = length + 1
    return length + 1
  else
    chains[index].length = trace_chain(follow, chains, follow[index]-1, length+1)
    return chains[index].length
  end
end
# check if SB is contained
def check_sb_contains(follow, chains, index, check, sb_num)
  if sb_num-1 == index
    check = true
  end
  if follow[index] == 0
    chains[index].check = check
    return check
  else
    chains[index].check = check_sb_contains(follow, chains, follow[index]-1, check, sb_num)
    return chains[index].check
  end
end

followed = Array::new
num_total.times {followed << false}
# who is the last in each chain
follow.each do |x|
  if x != 0
    followed[x-1] = true
  end
end

# number of chain before smart beaver
offset_smart_beaver = trace_chain(follow, chains, sb_num-1, 0)
# puts offset_smart_beaver

# count each length
num_total.times do |i|
  if followed[i] == false
    trace_chain(follow, chains, i, 0)
    check_sb_contains(follow, chains, i, false, sb_num)
  end
end

# count chains number
chains_bin = Array::new
num_total.times do |i|
  if followed[i] == false && !chains[i].check
    chains_bin << chains[i].length
  end
end
chains_bin.sort!
# puts chains_bin

# count chain pattern by dp
dp_table = Array::new
dp_table << 1
chains_bin.each do |bin|
  1000.downto(0) do |i|
    if dp_table[i] != nil
      dp_table[i+bin] = 1
    end
  end
end
# puts dp_table

1000.times do |i|
  if dp_table[i] != nil
    puts i + offset_smart_beaver
  end
end

require 'set'

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

s = Set.new

a.each do |ai|
		s.add(ai) if ai > 0
end

sum = 1
dp = Array.new(1001,false)
dp[0] = true

a.each_with_index do |ai,i1|
	i = i1 + 1
	next if s.member?(i)
	flag = false
	acc = 0
	while i > 0
		sum += 1 if flag
		flag ||= i == x
		acc += 1
		i = a[i-1]
	end
	next if flag
	1000.downto(0) do |j|
		next if not dp[j]
		dp[j+acc] ||= dp[j]
	end
end

0.upto(1000) do |i|
	next if not dp[i]
	puts(sum + i)
end


Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.

The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces.

If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.

lines = IO.readlines("input.txt")

#n = lines[0].to_i
cards = []
lines[1].split(" ").each_with_index do |val,ind|
  (cards[val.to_i] ||= []) << ind.to_i+1
end

cards.compact!

File.open("output.txt", "w") do |fout|
  if cards.count{|p| p.size%2!=0 if p} != 0
    fout.puts("-1")
  else
    cards.each do |pairs|
      pairs.each_slice(2) do |pair|
        fout.puts("#{pair[0]} #{pair[1]}")
      end if pairs
    end
  end
end

lines = IO.readlines("input.txt")

n = 0
pdi = 1
pairs = []
paired = []

  n = lines[0].to_i
  i = 1
  for a in lines[1].split(" ") do
    ai = a.to_i
    if pairs[ai] == nil
      pairs[ai] = i
    else
      paired[pdi], paired[pdi+1], pairs[ai] = pairs[ai], i, nil
      pdi += 2
    end
    i += 1
  end

File.open("output.txt", "w") do |fout|
  if pdi != n*2+1
    fout.puts("-1")
  else
    i = 1
    while i <= n*2 do
      fout.puts("#{paired[i]} #{paired[i+1]}")
      i += 2
    end
  end
end

require 'scanf'

n = 0
pdi = 1
pairs = []
paired = []

File.open("input.txt", "r") do |fin|
  n = fin.scanf("%d")[0]
  i = 1
  while i <= n*2 do
    ai = fin.scanf("%d")[0]
    if pairs[ai] == nil
      pairs[ai] = i
    else
      paired[pdi], paired[pdi+1], pairs[ai] = pairs[ai], i, nil
      pdi += 2
    end
    i += 1
  end
end

File.open("output.txt", "w") do |fout|
  if pdi != n*2+1
    fout.puts("-1")
  else
    i = 1
    while i <= n*2 do
      fout.puts("#{paired[i]} #{paired[i+1]}")
      i += 2
    end
  end
end

fi=File.new('input.txt','r');fo=File.new('output.txt','w')
fi.gets;a=fi.gets.strip.split
if a.uniq.size!=a.size/2; fo.puts "-1"; exit end
a.map.with_index(1).to_a.sort{|x,y| x[0]<=>y[0]}.each_slice(2) do |b|; fo.puts "#{b[0][1]} #{b[1][1]}"; end


Petya and Vasya are inventing a new game that requires a rectangular board and one chess piece. At the beginning of the game the piece stands in the upper-left corner of the board. Two players move the piece in turns. Each turn the chess piece can be moved either one square to the right or one square down or jump k squares diagonally down and to the right. The player who can’t move the piece loses.   The guys haven’t yet thought what to call the game or the best size of the board for it. Your task is to write a program that can determine the outcome of the game depending on the board size.

The first input line contains two integers t and k (1 ≤ t ≤ 20, 1 ≤ k ≤ 109). Each of the following t lines contains two numbers n, m — the board’s length and width (1 ≤ n, m ≤ 109).

Output t lines that can determine the outcomes of the game on every board. Write «+» if the first player is a winner, and «-» otherwise.

I = open('input.txt')
O = open('output.txt', 'w')
T, K = I.gets.split.map(&:to_i)
T.times do
	n, m = I.gets.split.map{|_| _.to_i - 1}.sort
	O.puts n % (K + 1) == K || (n + m - (K == 1 ? 0 : n / (K + 1))).odd? ? :+ : :-
end

__END__
WA3: K=1

I = open('input.txt')
O = open('output.txt', 'w')
T, K = I.gets.split.map(&:to_i)
T.times do
	n, m = I.gets.split.map{|_| _.to_i - 1}.sort
	O.puts n > 0 && n % K == 0 || (n + m).odd? ? :+ : :-
end

I = open('input.txt')
O = open('output.txt', 'w')
T, K = I.gets.split.map(&:to_i)
T.times do
	n, m = I.gets.split.map{|_| _.to_i - 1}.sort
	O.puts n % (K + 1) == K || (n + m - n / (K + 1)).odd? ? :+ : :-
end

I = open('input.txt')
O = open('output.txt', 'w')
T, K = I.gets.split.map(&:to_i)
T.times do
	n, m = I.gets.split.map{|_| _.to_i - 1}.sort
	O.puts n > 0 && n % K == 0 || (n + m - n / K).odd? ? :+ : :-
end


Monocarp had a tree which consisted of $$$n$$$ vertices and was rooted at vertex $$$1$$$. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processedq = Queue()q.put(1) # place the root at the end of the queuewhile not q.empty():    k = q.pop() # retrieve the first vertex from the queue    a.append(k) # append k to the end of the sequence in which vertices were visited    for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order        q.put(y)Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.Monocarp knows that there are many trees (in the general case) with the same visiting order $$$a$$$, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all root's children are $$$1$$$.Help Monocarp to find any tree with given visiting order $$$a$$$ and minimum height.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$; $$$a_i \neq a_j$$$; $$$a_1 = 1$$$) — the order in which the vertices were visited by the BFS algorithm. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print the minimum possible height of a tree with the given visiting order $$$a$$$.

NoteIn the first test case, there is only one tree with the given visiting order:   In the second test case, there is only one tree with the given visiting order as well:   In the third test case, an optimal tree with the given visiting order is shown below:

if ARGV[0]=="LOCAL_DEV"
	define_method("debug") do |var|
		p var
	end
else
	define_method("debug") do |var|
	end
end

Q=STDIN.gets.to_i
Q.times do
	n=STDIN.gets.to_i
	a=STDIN.gets.strip.split.map(&:to_i)
	v=[]
	t=-1
	c=0
	a.each_with_index do |x,i|
		if i==0
			v<<1
			next
		end
		if t<=x
			c+=1
			t=x
		else
			v<<c
			c=1
			t=x
		end
	end
	v<<c
	#debug v

	nokori=1
	t=0
	ans=0
	v.each_with_index do |x,i|
		t+=x
		nokori-=1
		if nokori==0 && i<v.length-1
			#debug t
			nokori=t
			t=0
			ans+=1
		end
	end
	p ans
end

Q=gets.to_i
Q.times do
n=gets.to_i
a=gets.strip.split.map(&:to_i)
v=[]
t=-1
c=1
a.each_with_index do |x,i|
  if i==0
    v<<1
    next
  end
  if x<=t
    c+=1
    t=x
  else
    v<<c
    c=1
    t=x
  end
end

nokori=1
c=0
t=0
ans=0
v.each_with_index do |x,i|
  t+=x
  nokori-=1
  if nokori==0
    nokori=t
    ans+=1
  end
end
p ans-1
end

Q=gets.to_i
Q.times do
n=gets.to_i
a=gets.strip.split.map(&:to_i)
v=[]
t=-1
c=0
a.each_with_index do |x,i|
  if i==0
    v<<1
    next
  end
  if t<=x
    c+=1
    t=x
  else
    v<<c
    c=1
    t=x
  end
end
v<<c

nokori=1
c=0
t=0
ans=0
v.each_with_index do |x,i|
  t+=x
  nokori-=1
  if nokori==0
    nokori=t
    ans+=1
  end
end
p ans
end

Q=gets.to_i
Q.times do
n=gets.to_i
a=gets.strip.split.map(&:to_i)
v=[]
t=-1
c=0
a.each_with_index do |x,i|
  if i==0
    v<<1
    next
  end
  if t<=x
    c+=1
    t=x
  else
    v<<c
    c=1
    t=x
  end
end
v<<c

nokori=1
t=0
ans=0
v.each_with_index do |x,i|
  t+=x
  nokori-=1
if nokori==0 && i<v.length-1
    nokori=t
    ans+=1
  end

end
p ans
end

Q=gets.to_i
Q.times do
n=gets.to_i
a=gets.strip.split.map(&:to_i)
v=[]
t=-1
c=1
a.each_with_index do |x,i|
  if i==0
    v<<1
    next
  end
  if t<=x
    c+=1
    t=x
  else
    v<<c
    c=1
    t=x
  end
end

nokori=1
c=0
t=0
ans=0
v.each_with_index do |x,i|
  t+=x
  nokori-=1
  if nokori==0
    nokori=t
    ans+=1
  end
end
p ans-1
end

Q=gets.to_i
Q.times do
n=gets.to_i
a=gets.strip.split.map(&:to_i)
v=[]
t=-1
c=0
a.each_with_index do |x,i|
  if i==0
    v<<1
    next
  end
  if t<=x
    c+=1
    t=x
  else
    v<<c
    c=1
    t=x
  end
end
v<<c

nokori=1
c=0
t=0
ans=0
v.each_with_index do |x,i|
  t+=x
  nokori-=1
  if nokori==0
    nokori=t
    ans+=1
  end
end
p ans-1
end


The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.A Bitlandish string is a string made only of characters "0" and "1".BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p = x xor y, q = x or y. Then he replaces one of the two taken characters by p and the other one by q.The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.

The first line contains Bitlandish string a, the second line contains Bitlandish string b. The strings can have different lengths. It is guaranteed that the given strings only consist of characters "0" and "1". The strings are not empty, their length doesn't exceed 106.

Print "YES" if a can be transformed into b, otherwise print "NO". Please do not print the quotes.

# Author : Fuad Ashraful Mehmet
#Date: 18th April

a=gets.strip
b=gets.strip

idx1=a.length
idx2=b.length

n=a.length

if a.length!=b.length
    puts "NO"
    exit
end

flag1=true
flag2=true

for i in 0...n

    flag1=false unless a[i]=='0'
    flag2=false unless b[i]=='0'

    break if !flag1 && !flag2

end

if flag1  && flag2==false then puts "NO"

elsif flag1==false && flag2 then puts "NO"

else puts "YES"

end

a = gets.strip
b = gets.strip

n = a.length

if n != b.length then
  puts "NO"
  exit
end

a0 = true
b0 = true
for i in 0...n
  a0 = false unless a[i] == '0'
  b0 = false unless b[i] == '0'
  break if !a0 && !b0
end

if a0 && !b0 then puts "NO"
elsif b0 && !a0 then puts "NO"
else puts "YES" end

ori = gets.chomp
tar = gets.chomp
if ori.length == tar.length
    if ori_has = ori.include?("1") ^ tar_has = tar.include?("1") then puts "NO"
    else puts "YES"
    end
else
    puts "NO"
end

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

def check()

s = gets.chomp
t = gets.chomp

	return false if s.length != t.length
	t1 = s.index('1')
	t2 = t.index('1')

	return true if (t1 && t2)
	return false if (t1 || t2)
	return true
end

puts check() ? "YES" : "NO"

a=gets
b=gets
puts (a==b ? "YES" : (a.size!=b.size or !a.include?(?1) or !b.include?(?1)) ? "NO" : "YES")

a = gets.strip
b = gets.strip

answer = 'YES'

a_l = a.length
b_l = b.length
answer = 'NO' if a_l != b_l

answer = 'NO' if a_l == 1 && b_l == 1 && a != b

a_1 = a[/1/]
b_1 = b[/1/]

answer = 'NO' if !a_1 && b_1
answer = 'NO' if a_1 && !b_1

print answer

a = gets.strip
b = gets.strip

answer = 'YES'

a_l = a.length
b_l = b.length
answer = 'NO' if a_l != b_l

answer = 'NO' if a_l == 1 && b_l == 1 && a != b

a_1 = a.include?('1')
b_1 = b.include?('1')

answer = 'NO' if !a_1 && b_1
answer = 'NO' if a_1 && !b_1

print answer

a = gets.chomp
b = gets.chomp

if a.length != b.length
	puts "NO"
	exit
end

if a.include?("1")!=b.include?("1")
	puts "NO"
	exit
end

puts "YES"

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

def check()

s = gets.chomp
t = gets.chomp

	#return false if s.length != t.length
	t1 = s.index('1')
	t2 = t.index('1')

	return true if (t1 && t2)
	return false if (t1 || t2)
	return true
end

puts check() ? "YES" : "NO"

a = gets
b = gets

if a.length != b.length
	puts "NO"
	exit
end

if a.include?("1")!=b.include?("0")
	puts "NO"
	exit
end

puts "YES"


Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?

The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.

Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.

n,k,m = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i).sort
s=arr.inject(:+)
avg = (s+[m,n*k].min).to_f/n
for i in 0..[n-1,m].min-1
    s = s - arr[i]
    na = (s+[m-i-1,(n-i-1)*k].min).to_f/(n-i-1)
    avg = [avg,na].max
end
avg = "#{'%.10f'%avg}"
puts avg


In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.

The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.

Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.

NoteIn the first sample, the train can take the route  and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

n, m = gis

h = []
1.upto(n) do |i|
    h[i] = [-1] * n.succ
    h[i][i] = 0
end

m.times do
    u, v = gis
    h[u][v] = h[v][u] = 1
end

t1 = []
t2 = []
1.upto(n) do |i|
    t1[i] = []
    t2[i] = []
    1.upto(n) do |j|
        case h[i][j]
        when 1
            t1[i] << j
        when -1
            t2[i] << j
        end
    end
end

if t1[1].empty? || t2[1].empty? || t1[n].empty? || t2[n].empty?
    puts '-1'
    exit
end

l1 = [1]
v1 = [true] + ([false] * n)
flg = true
ct = 0
while flg && !l1.empty? do
    ct += 1
    l2 = []
    l1.each do |k|
        if t1[k][-1] == n
            flg = false
            break
        end
        t1[k].each do |x|
            next if v1[x]
            v1[x] = true
            l2 << x
        end
    end
    l1 = l2
end

if flg
    puts '-1'
    exit
end

l1 = [1]
v1 = [true] + ([false] * n)
flg = true
cb = 0
while flg && !l1.empty? do
    cb += 1
    l2 = []
    l1.each do |k|
        if t2[k][-1] == n
            flg = false
            break
        end
        t2[k].each do |x|
            next if v1[x]
            v1[x] = true
            l2 << x
        end
    end
    l1 = l2
end

if flg
    puts '-1'
    exit
end

puts [ct,cb].max

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

n, m = gis

h = []
1.upto(n) do |i|
    h[i] = [-1] * n.succ
    h[i][i] = 0
end

m.times do
    u, v = gis
    h[u][v] = h[v][u] = 1
end

t1 = []
t2 = []
1.upto(n) do |i|
    t1[i] = []
    t2[i] = []
    1.upto(n) do |j|
        case h[i][j]
        when 1
            t1[i] << j
        when -1
            t2[i] << j
        end
    end
end

if t1[1].empty? || t2[1].empty? || t1[n].empty? || t2[n].empty?
    puts '-1'
    exit
end

def fnc(t, n)
    l1 = [1]
    v1 = [true] + ([false] * n)
    c = 0
    while !l1.empty? do
        c += 1
        l2 = []
        l1.each do |k|
            if t[k][-1] == n
                return c
            end
            t[k].each do |x|
                next if v1[x]
                v1[x] = true
                l2 << x
            end
        end
        l1 = l2
    end
    return -1
end

ct = fnc t1, n
if ct < 0
    puts '-1'
    exit
end

cb = fnc t2, n
if cb < 0
    puts '-1'
    exit
end

puts [ct,cb].max

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

$stdout = STDERR

n, m = gis

h = {}

m.times do
    u, v = gis

    h[u] = [false] * (n + 1) if !h.key? u
    h[u][v] = true

    h[v] = [false] * (n + 1) if !h.key? v
    h[v][u] = true

end

l1 = []
l2 = []

1.upto(n - 1) do |i|
    if h[n][i]
        l1 << i
    else
        l2 << i
    end
end

p h, "-----"
p l1, l2, "-----"

if l1.empty? || l2.empty?
    STDOUT.puts '-1'
    exit
end

if !(l1 & l2).empty?
    STDOUT.puts 1
    exit
end

c = 1

loop {
    c += 1

    l1t = {}
    l1.each do |k|
        if !h.key? k
            next
        end
        1.upto(n - 1) do |i|
            next if i == k
            if h[k][i]
                l1t[i] = 1
            end
        end
    end
    l1 = l1t.keys

    l2t = {}
    l2.each do |k|
        1.upto(n - 1) do |i|
            next if i == k
            if (!h.key?(k)) || !h[k][i]
                l2t[i] = 1
            end
        end
    end
    l2 = l2t.keys

    p l1, l2, "-----"

    if l1.empty? || l2.empty?
        STDOUT.puts '-1'
        exit
    end

    if !(l1 & l2).empty?
        STDOUT.puts c
        exit
    end
}

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

$stdout = STDERR

n, m = gis

h = {}

m.times do
    u, v = gis

    h[u] = [false] * (n + 1) if !h.key?(u)
    h[u][v] = true

    h[v] = [false] * (n + 1) if !h.key?(v)
    h[v][u] = true

end

if !h.key?(n)
    STDOUT.puts '-1'
    exit
end

l1 = []
l2 = []

1.upto(n - 1) do |i|
    if h[n][i]
        l1 << i
    else
        l2 << i
    end
end

#p h, "-----"
#p l1, l2, "-----"

if l1.empty? || l2.empty?
    STDOUT.puts '-1'
    exit
end

if !((l1 & l2) & [1]).empty?
    STDOUT.puts '1'
    exit
end

c = 1

mp = {}

loop {
    c += 1

    l1t = {}
    l1.each do |k|
        if !h.key? k
            next
        end
        1.upto(n - 1) do |i|
            next if i == k
            if h[k][i]
                l1t[i] = 1
            end
        end
    end
    l1 = l1t.keys

    l2t = {}
    l2.each do |k|
        1.upto(n - 1) do |i|
            next if i == k
            if (!h.key?(k)) || (!(h[k][i]))
                l2t[i] = 1
            end
        end
    end
    l2 = l2t.keys

    s = l1.sort * " " + "," + l2.sort * " "
    if mp.key? s
        puts '-1'
        exit
    end
    mp[s] = 1

    #p l1, l2, "-----"

    if l1.empty? || l2.empty?
        STDOUT.puts '-1'
        exit
    end

    if l1t.key?(1) && l2t.key?(1)
        STDOUT.puts c
        exit
    end
}

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

$stdout = STDERR

n, m = gis

h = {}

m.times do
    u, v = gis

    h[u] = [false] * (n + 1) if !h.key?(u)
    h[u][v] = true

    #h[v] = [false] * (n + 1) if !h.key?(v)
    #h[v][u] = true

end

if !h.key?(n)
    STDOUT.puts '-1'
    exit
end

l1 = []
l2 = []

1.upto(n) do |i|
    if h[n][i]
        l1 << i
    else
        l2 << i
    end
end

#p h, "-----"
#p l1, l2, "-----"

if l1.empty? || l2.empty?
    STDOUT.puts '-1'
    exit
end

if !((l1 & l2) & [1]).empty?
    STDOUT.puts '1'
    exit
end

c = 1

mp = {}

loop {
    c += 1

    l1t = {}
    l1.each do |k|
        if !h.key? k
            next
        end
        1.upto(n) do |i|
            next if i == k
            if h[k][i]
                l1t[i] = 1
            end
        end
    end
    l1 = l1t.keys

    l2t = {}
    l2.each do |k|
        1.upto(n) do |i|
            next if i == k
            if (!h.key?(k)) || (!(h[k][i]))
                l2t[i] = 1
            end
        end
    end
    l2 = l2t.keys

    s = (l1.sort * " ") + "," + (l2.sort * " ")
    if mp.key? s
        puts '-1'
        exit
    end
    mp[s] = 1

    #p l1, l2, "-----"

    if l1.empty? || l2.empty?
        STDOUT.puts '-1'
        exit
    end

    if l1t.key?(1) && l2t.key?(1)
        STDOUT.puts c
        exit
    end
}

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

$stdout = STDERR

n, m = gis

h = {}

m.times do
    u, v = gis

    h[u] = [false] * (n + 1) if !h.key? u
    h[u][v] = true

    h[v] = [false] * (n + 1) if !h.key? v
    h[v][u] = true

end

l1 = []
l2 = []

1.upto(n - 1) do |i|
    if h[n][i]
        l1 << i
    else
        l2 << i
    end
end

p h, "-----"
p l1, l2, "-----"

if l1.empty? || l2.empty?
    STDOUT.puts '-1'
    exit
end

if !(l1 & l2).empty?
    STDOUT.puts 1
    exit
end

c = 1

loop {
    c += 1

    l1t = {}
    l1.each do |k|
        if !h.key? k
            next
        end
        1.upto(n) do |i|
            next if i == k
            if h[k][i]
                l1t[i] = 1
            end
        end
    end
    l1 = l1t.keys

    l2t = {}
    l2.each do |k|
        1.upto(n) do |i|
            next if i == k
            if (!h.key?(k)) || !h[k][i]
                l2t[i] = 1
            end
        end
    end
    l2 = l2t.keys

    p l1, l2, "-----"

    if l1.empty? || l2.empty?
        STDOUT.puts '-1'
        exit
    end

    if !((l1 & l2) - [n]).empty?
        STDOUT.puts c
        exit
    end
}

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

$stdout = STDERR

n, m = gis

h = {}

m.times do
    u, v = gis

    h[u] = [false] * (n + 1) if !h.key?(u)
    h[u][v] = true

    h[v] = [false] * (n + 1) if !h.key?(v)
    h[v][u] = true

end

if !h.key?(n)
    STDOUT.puts '-1'
    exit
end

l1 = []
l2 = []

1.upto(n - 1) do |i|
    if h[n][i]
        l1 << i
    else
        l2 << i
    end
end

#p h, "-----"
#p l1, l2, "-----"

if l1.empty? || l2.empty?
    STDOUT.puts '-1'
    exit
end

if !((l1 & l2) & [1]).empty?
    STDOUT.puts '1'
    exit
end

c = 1

mp = {}

loop {
    c += 1

    l1t = {}
    l1.each do |k|
        if !h.key? k
            next
        end
        1.upto(n) do |i|
            next if i == k
            if h[k][i]
                l1t[i] = 1
            end
        end
    end
    l1 = l1t.keys

    l2t = {}
    l2.each do |k|
        1.upto(n) do |i|
            next if i == k
            if (!h.key?(k)) || (!(h[k][i]))
                l2t[i] = 1
            end
        end
    end
    l2 = l2t.keys

    s = l1.sort * " " + "," + l2.sort * " "
    if mp.key? s
        puts '-1'
        exit
    end
    mp[s] = 1

    #p l1, l2, "-----"

    if l1.empty? || l2.empty?
        STDOUT.puts '-1'
        exit
    end

    if l1t.key?(1) && l2t.key?(1)
        STDOUT.puts c
        exit
    end
}

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

$stdout = STDERR

n, m = gis

h = {}

m.times do
    u, v = gis

    #h[u] = [false] * (n + 1) if !h.key?(u)
    #h[u][v] = true

    h[v] = [false] * (n + 1) if !h.key?(v)
    h[v][u] = true

end

if !h.key?(n)
    STDOUT.puts '-1'
    exit
end

l1 = []
l2 = []

1.upto(n) do |i|
    if h[n][i]
        l1 << i
    else
        l2 << i
    end
end

#p h, "-----"
#p l1, l2, "-----"

if l1.empty? || l2.empty?
    STDOUT.puts '-1'
    exit
end

if !((l1 & l2) & [1]).empty?
    STDOUT.puts '1'
    exit
end

c = 1

mp = {}

loop {
    c += 1

    l1t = {}
    l1.each do |k|
        if !h.key? k
            next
        end
        1.upto(n) do |i|
            next if i == k
            if h[k][i]
                l1t[i] = 1
            end
        end
    end
    l1 = l1t.keys

    l2t = {}
    l2.each do |k|
        1.upto(n) do |i|
            next if i == k
            if (!h.key?(k)) || (!(h[k][i]))
                l2t[i] = 1
            end
        end
    end
    l2 = l2t.keys

    s = (l1.sort * " ") + "," + (l2.sort * " ")
    if mp.key? s
        puts '-1'
        exit
    end
    mp[s] = 1

    #p l1, l2, "-----"

    if l1.empty? || l2.empty?
        STDOUT.puts '-1'
        exit
    end

    if l1t.key?(1) && l2t.key?(1)
        STDOUT.puts c
        exit
    end
}

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

$stdout = STDERR

n, m = gis

h = {}

m.times do
    u, v = gis

    h[u] = [false] * (n + 1) if !h.key?(u)
    h[u][v] = true

    h[v] = [false] * (n + 1) if !h.key?(v)
    h[v][u] = true

end

if !h.key?(n)
    STDOUT.puts '-1'
    exit
end

l1 = []
l2 = []

1.upto(n) do |i|
    if h[n][i]
        l1 << i
    else
        l2 << i
    end
end

#p h, "-----"
#p l1, l2, "-----"

if l1.empty? || l2.empty?
    STDOUT.puts '-1'
    exit
end

if !((l1 & l2) & [1]).empty?
    STDOUT.puts '1'
    exit
end

c = 1

mp = {}

loop {
    c += 1

    l1t = {}
    l1.each do |k|
        if !h.key? k
            next
        end
        1.upto(n) do |i|
            next if i == k
            if h[k][i]
                l1t[i] = 1
            end
        end
    end
    l1 = l1t.keys

    l2t = {}
    l2.each do |k|
        1.upto(n) do |i|
            next if i == k
            if (!h.key?(k)) || (!(h[k][i]))
                l2t[i] = 1
            end
        end
    end
    l2 = l2t.keys

    s = (l1.sort * " ") + "," + (l2.sort * " ")
    if mp.key? s
        puts '-1'
        exit
    end
    mp[s] = 1

    #p l1, l2, "-----"

    if l1.empty? || l2.empty?
        STDOUT.puts '-1'
        exit
    end

    if l1t.key?(1) && l2t.key?(1)
        STDOUT.puts c
        exit
    end
}


In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor.On the current level, the hero is facing $$$n$$$ caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave $$$i$$$, he will have to fight $$$k_i$$$ monsters in a row: first a monster with armor $$$a_{i, 1}$$$, then a monster with armor $$$a_{i, 2}$$$ and so on, finally, a monster with armor $$$a_{i, k_i}$$$.The hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order.Each time the hero beats a monster, the hero's power increases by $$$1$$$.Find the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of caves. The $$$i$$$-th of the next $$$n$$$ lines contains an integer $$$k_i$$$ ($$$1 \le k_i \le 10^5$$$) — the number of monsters in the $$$i$$$-th cave, followed by $$$k_i$$$ integers $$$a_{i, 1}, a_{i, 2}, \ldots, a_{i, k_i}$$$ ($$$1 \le a_{i, j} \le 10^9$$$) — armor levels of the monsters in cave $$$i$$$ in order the hero has to fight them. It is guaranteed that the sum of $$$k_i$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.

NoteIn the first test case, the hero has to beat a single monster with armor $$$42$$$, it's enough to have power $$$43$$$ to achieve that.In the second test case, the hero can pass the level with initial power $$$13$$$ as follows:   enter cave $$$2$$$:   beat a monster with armor $$$12$$$, power increases to $$$14$$$;  beat a monster with armor $$$11$$$, power increases to $$$15$$$;   enter cave $$$1$$$:   beat a monster with armor $$$10$$$, power increases to $$$16$$$;  beat a monster with armor $$$15$$$, power increases to $$$17$$$;  beat a monster with armor $$$8$$$, power increases to $$$18$$$.

class Cave
  attr_accessor :count
  attr_accessor :max
  def initialize()
    a = gets.split.map {|i| i.to_i}
    a = a[1...a.length]
    a = a.map.with_index do |item, idx|
      item - idx
    end
    @count = a.length
    @max = a.max
  end
  def <=>(other)
    if other.is_a?(Cave) == false
      return nil
    end
    if max < other.max
      return -1
    elsif max > other.max
      return 1
    else
      return other.count <=> count
    end
  end
end
def solve
  n = gets.to_i
  a = (1..n).map { |xx| Cave.new }
  a.sort!
  #p a

  res, power, pcount = 0, 0, 0
  for i in a
    if i.max > power
      power = i.max
      res = i.max + 1 - pcount
    end
    power += i.count
    pcount += i.count
  end
  puts res
  #puts "res: #{res}"
end
t = gets.to_i
while t > 0
  t -= 1
  solve
end

t = gets.to_i
t.times do

n = gets.to_i
caves = Array.new(n) do
  gets.split.map!(&:to_i).drop(1)
end

data = caves.map do |a|
  k = a.size
  req = a.map.with_index { |ai, i| ai - i + 1 }.max
  [req, -k]
end.sort!

pw = 0
diff = 0
data.each do |req, kk|
  if pw < req
    diff += req - pw
    pw = req
  end
  pw += -kk
end

p diff

end

class Cave
  attr_accessor :count
  attr_accessor :max
  def initialize()
    a = gets.split.map {|i| i.to_i}
    a = a[1...a.length]
    a = a.map.with_index do |item, idx|
      item - idx
    end
    @count = a.length
    @max = a.max
  end
  def <=>(other)
    if other.is_a?(Cave) == false
      return nil
    end
    if max < other.max
      return -1
    elsif max > other.max
      return 1
    else
      return other.count <=> count
    end
  end
end
def solve
  n = gets.to_i
  a = (1..n).map { |xx| Cave.new }
  a.sort!
  p a

  res, power, pcount = 0, 0, 0
  for i in a
    if i.max > power
      power = i.max
      res = i.max + 1 - pcount
    end
    power += i.count
    pcount += i.count
  end
  puts "res: #{res}"
end
t = gets.to_i
while t > 0
  t -= 1
  solve
end


You are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root is vertex $$$1$$$. There is also a string $$$s$$$ denoting the color of each vertex: if $$$s_i = \texttt{B}$$$, then vertex $$$i$$$ is black, and if $$$s_i = \texttt{W}$$$, then vertex $$$i$$$ is white.A subtree of the tree is called balanced if the number of white vertices equals the number of black vertices. Count the number of balanced subtrees.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. In this problem, all trees have root $$$1$$$.The tree is specified by an array of parents $$$a_2, \dots, a_n$$$ containing $$$n-1$$$ numbers: $$$a_i$$$ is the parent of the vertex with the number $$$i$$$ for all $$$i = 2, \dots, n$$$. The parent of a vertex $$$u$$$ is a vertex that is the next vertex on a simple path from $$$u$$$ to the root.The subtree of a vertex $$$u$$$ is the set of all vertices that pass through $$$u$$$ on a simple path to the root. For example, in the picture below, $$$7$$$ is in the subtree of $$$3$$$ because the simple path $$$7 \to 5 \to 3 \to 1$$$ passes through $$$3$$$. Note that a vertex is included in its subtree, and the subtree of the root is the entire tree.  The picture shows the tree for $$$n=7$$$, $$$a=[1,1,2,3,3,5]$$$, and $$$s=\texttt{WBBWWBW}$$$. The subtree at the vertex $$$3$$$ is balanced.

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 4000$$$) — the number of vertices in the tree. The second line of each test case contains $$$n-1$$$ integers $$$a_2, \dots, a_n$$$ ($$$1 \le a_i < i$$$) — the parents of the vertices $$$2, \dots, n$$$. The third line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of the characters $$$\texttt{B}$$$ and $$$\texttt{W}$$$ — the coloring of the tree. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of balanced subtrees.

NoteThe first test case is pictured in the statement. Only the subtrees at vertices $$$2$$$ and $$$3$$$ are balanced.In the second test case, only the subtree at vertex $$$1$$$ is balanced.In the third test case, only the subtrees at vertices $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ are balanced.

Node = Struct.new(:id, :balance, :parent)

gets.to_i.times do
  n = gets.to_i
  nodes = Array.new(n) { |i| Node.new(i, nil, nil) }
  gets.split.map(&:to_i).each_with_index do |p, i|
    nodes[i + 1].parent = nodes[p - 1]
  end
  gets.strip.chars.each_with_index do |c, i|
    nodes[i].balance = (c == 'W') ? 1 : -1
  end

  nodes.reverse.each do |node|
    next unless node.parent
    node.parent.balance += node.balance
  end

  p nodes.count { _1.balance == 0 }
end


You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.

The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.

Print the minimum non-zero element before each operation in a new line.

NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.

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

sub=0
idx=0
k.times.each do |i|
  while idx<n && (ary[idx]-sub)==0 do
    idx+=1
  end
  v = 0
  if idx >= n
    v = 0
  else
    v = (ary[idx]-sub)
    sub += v
  end
  puts v
end

n,k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort
i = 0
sum = 0
k.times do |j|
    while i < n && a[i]-sum <= 0
        i += 1
        #break if i == n
    end
    if i == n
        puts 0
    else
        puts a[i]-sum
        sum = a[i]
    end
end

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

arr.sort!
index = 0
sbst = 0
k.times do
    if index >= n
        puts 0
    else
        min = arr[index] - sbst
        puts min
        sbst += min
        for i in index..(n - 1) do
            if arr[i] - sbst > 0
                index = i
                break
            else i == n - 1
                index = n
            end
        end
    end
end

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
a.sort!
j = a.index{|x| x > 0}
if j == nil
    j = a.size
end
pj = 0
k.times do
    if j == a.size
        puts 0
        next
    end
    puts(a[j] - pj)
    pj += (a[j] - pj)

    i = j + 1
    i += 1 while i < a.size && a[i] == a[j]
    j = i
end

nk = gets.chomp.split(" ").map(&:to_i)
arr = gets.chomp.split(" ").map(&:to_i)
n = nk[0]
k = nk[1]
tosubtr = 0

arr.sort!
#p arr

i = 0
k.times do

  if i >= n
    puts 0
  else
    x = arr[i]

    while ((x-tosubtr)==0 and i<n-1)
      i += 1
      x = arr[i]
    end

    if i==n
      puts 0
      continue
    end

#    puts "#{x} #{tosubtr}"

    if x-tosubtr<=0
      puts 0
    else
      puts x-tosubtr
      tosubtr = x
    end

  end
  i += 1
end

n,k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort
i = 0
sum = 0
k.times do |j|
    while i < n && a[i]-sum <= 0
        i += 1
        #break if i == n
    end
    if i == n
        puts 0
    else
        puts a[i]-sum
        sum += a[i]
    end
end

nk = gets.chomp.split(" ").map(&:to_i)
arr = gets.chomp.split(" ").map(&:to_i)
n = nk[0]
k = nk[1]
tosubtr = 0

arr.sort!
#p arr

i = 0
k.times do

  if i >= n
    puts 0
  else
    x = arr[i]

    while ((x-tosubtr)==0 and i<n-1)
      i += 1
      x = arr[i]
    end

    if i==n
      puts 0
      continue
    end

#    puts "#{x} #{tosubtr}"

    if x-tosubtr<=0
      puts 0
    else
      puts x-tosubtr
      tosubtr += x
    end

  end
  i += 1
end


Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!The computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options.You have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.

The first line contains three integers a, b and c (0 ≤ a, b, c ≤ 105)  — the number of computers that only have USB ports, the number of computers, that only have PS/2 ports, and the number of computers, that have both options, respectively. The next line contains one integer m (0 ≤ m ≤ 3·105)  — the number of mouses in the price list. The next m lines each describe another mouse. The i-th line contains first integer vali (1 ≤ vali ≤ 109)  — the cost of the i-th mouse, then the type of port (USB or PS/2) that is required to plug the mouse in.

Output two integers separated by space — the number of equipped computers and the total cost of the mouses you will buy.

NoteIn the first example you can buy the first three mouses. This way you will equip one of the computers that has only a USB port with a USB mouse, and the two PS/2 mouses you will plug into the computer with PS/2 port and the computer with both ports.

a,b,c=gets.split.map(&:to_i)
r=s=0
H=Hash.new{|h,k|h[k]=[]}
gets.to_i.times{
	x,y=gets.split
	H[y]<<x.to_i
}
H['USB'].sort!
a=H['USB'].size if a>H['USB'].size
r+=a
s+=H['USB'].shift(a).reduce(0,:+)
H['PS/2'].sort!
b=H['PS/2'].size if b>H['PS/2'].size
r+=b
s+=H['PS/2'].shift(b).reduce(0,:+)
q=(H['USB']+H['PS/2']).sort
c=q.size if c>q.size
r+=c
s+=q.shift(c).reduce(0,:+)
puts '%d %d'%[r,s]

#!/usr/bin/env ruby

usb, ps2, usb_ps2 = gets.split.map {|v| v.to_i}
mouses_n = gets.to_i

mouses_prices = { USB: [],
                  :'PS/2' => []}

mouses_n.times do |n|
  price, type = gets.split
  mouses_prices[type.to_sym] << price.to_i
end

mouses_prices[:USB].sort!
mouses_prices[:'PS/2'].sort!

total_mouse = 0
total_price = 0

usb.times do
  break if mouses_prices[:USB].empty?
  total_price += mouses_prices[:USB].shift
  total_mouse += 1
end

ps2.times do
  break if mouses_prices[:'PS/2'].empty?
  total_price += mouses_prices[:'PS/2'].shift
  total_mouse += 1
end

usb_ps2_remainings = mouses_prices[:USB] + mouses_prices[:'PS/2']
usb_ps2_remainings.sort!

usb_ps2.times do
  break if usb_ps2_remainings.empty?
  total_price += usb_ps2_remainings.shift
  total_mouse += 1
end

puts "#{total_mouse} #{total_price}"

#!/usr/bin/env ruby

usb, ps2, usb_ps2 = gets.split.map {|v| v.to_i}
mouses_n = gets.to_i

mouses_prices = { USB: [],
                  :'PS/2' => []}

mouses_n.times do |n|
  price, type = gets.split
  mouses_prices[type.to_sym] << price.to_i
end

mouses_prices[:USB].sort!
mouses_prices[:'PS/2'].sort!

total_mouse = 0
total_price = 0

usb.times do
  break if mouses_prices[:USB].empty?
  total_price += mouses_prices[:USB].shift
  total_mouse += 1
end

ps2.times do
  break if mouses_prices[:'PS/2'].empty?
  total_price += mouses_prices[:'PS/2'].shift
  total_mouse += 1
end

usb_ps2.times do
  if !mouses_prices[:USB].empty?
    total_price += mouses_prices[:USB].shift
    total_mouse += 1
    next
  end
  if !mouses_prices[:'PS/2'].empty?
    total_price += mouses_prices[:'PS/2'].shift
    total_mouse += 1
    next
  end
  break
end

puts "#{total_mouse} #{total_price}"


Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.Each tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has $$$a$$$ sticks and $$$b$$$ diamonds?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^9$$$) — the number of sticks and the number of diamonds, respectively.

For each test case print one integer — the maximum number of emeralds Polycarp can earn.

NoteIn the first test case Polycarp can earn two emeralds as follows: craft one sword and one shovel.In the second test case Polycarp does not have any diamonds, so he cannot craft anything.

def solve(a, b)
  min = [a, b].min
  max = [a, b].max
  [(max + min) /3, min].min
end

amount = gets.chomp.to_i
amount.times do
  input = gets.chomp.split(" ")
  puts solve(input[0].to_i, input[1].to_i)
end

t = gets.chomp.to_i

results = []

(1..t).each do |_t|

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

  a.sort!.reverse!

  a,b = a

 if a > 2*b
  results[_t] = b
 else
  results[_t] = (a + b) /3
 end

end

results.each do |res|
  puts res
end

t = gets.chomp.to_i

results = []

(1..t).each do |_t|

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

  a.sort!.reverse!

  if a[0] % 2 == 0
    if a[1] - (a[0]/2 - 1) >= 4
      results[_t] = a[0] / 2 + 1
    else
      results[_t] = [a[0]/2, a[1]].min
    end
  else
    x = a[1] - a[0] / 2

    if x > 1
      results[_t] =a[0]/2 + 1
    else
      results[_t] = [a[0]/2, a[1]].min
    end
  end

end

results.each do |res|
  puts res
end

def compute(a,b,x)
  return b if b <= x

  a -= 2*x
  b -= x

  return x if [a,b].max < 2

  return x if [a,b].min < 1

  return x + 1 if [a,b].max < 4

  return x + 1 if [a,b].min < 2

  x + 2
end

t = gets.chomp.to_i

results = []

(1..t).each do |_t|

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

  a.sort!.reverse!

  x = a[0] / 2

  results[_t] = [compute(a[0], a[1], x), compute(a[0], a[1], x-1)].max

end

results.each do |res|
  puts res
end


For some binary string $$$s$$$ (i.e. each character $$$s_i$$$ is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length $$$2$$$ were written. For each pair (substring of length $$$2$$$), the number of '1' (ones) in it was calculated.You are given three numbers:  $$$n_0$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$0$$$;  $$$n_1$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$1$$$;  $$$n_2$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$2$$$. For example, for the string $$$s=$$$"1110011110", the following substrings would be written: "11", "11", "10", "00", "01", "11", "11", "11", "10". Thus, $$$n_0=1$$$, $$$n_1=3$$$, $$$n_2=5$$$.Your task is to restore any suitable binary string $$$s$$$ from the given values $$$n_0, n_1, n_2$$$. It is guaranteed that at least one of the numbers $$$n_0, n_1, n_2$$$ is greater than $$$0$$$. Also, it is guaranteed that a solution exists.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then test cases follow. Each test case consists of one line which contains three integers $$$n_0, n_1, n_2$$$ ($$$0 \le n_0, n_1, n_2 \le 100$$$; $$$n_0 + n_1 + n_2 > 0$$$). It is guaranteed that the answer for given $$$n_0, n_1, n_2$$$ exists.

Print $$$t$$$ lines. Each of the lines should contain a binary string corresponding to a test case. If there are several possible solutions, print any of them.

gets.to_i.times{
    a,b,c=gets.split.map &:to_i
    if c>0
        s=[1]*(c+1)
    else
        s=[0]
    end

    while b>0
        s<<1-s[-1]
        b-=1
    end
    a+=1 if s[-1]==1 and a>0
    s+=[0]*a
    puts s*''
}


Recently Petya walked in the forest and found a magic stick.Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer:   If the chosen number $$$a$$$ is even, then the spell will turn it into $$$\frac{3a}{2}$$$;  If the chosen number $$$a$$$ is greater than one, then the spell will turn it into $$$a-1$$$. Note that if the number is even and greater than one, then Petya can choose which spell to apply.Petya now has only one number $$$x$$$. He wants to know if his favorite number $$$y$$$ can be obtained from $$$x$$$ using the spells he knows. The spells can be used any number of times in any order. It is not required to use spells, Petya can leave $$$x$$$ as it is.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^9$$$) — the current number and the number that Petya wants to get.

For the $$$i$$$-th test case print the answer on it — YES if Petya can get the number $$$y$$$ from the number $$$x$$$ using known spells, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

g = gets.chomp.to_i
g.times{

x,y = gets.split(" ").map{|x|x.to_i}

if x==y
puts "YES"
elsif x%2!=0 and x < 2
puts "NO"
elsif x%2==0 and x!=2
puts "YES"
elsif x%2==0 and x==2 and y==3
puts "YES"
elsif x%2!=0 and x > 3
puts "YES"
elsif x > y
puts "YES"
else
puts "NO"
end

}

g = gets.chomp.to_i
g.times{

x,y = gets.split(" ").map{|x|x.to_i}

if x==y
puts "YES"
elsif x%2!=0 and x < 2
puts "NO"
elsif x%2==0 and x!=2
puts "YES"
elsif x%2==0 and x==2 and y==3
puts "YES"
elsif x%2!=0 and x > 3
puts "YES"
else
puts "NO"
end

}


You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given.One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.For example, if the string s is abacaba and the query is l1 = 3, r1 = 6, k1 = 1 then the answer is abbacaa. If after that we would process the query l2 = 1, r2 = 4, k2 = 2 then we would get the string baabcaa.

The first line of the input contains the string s (1 ≤ |s| ≤ 10 000) in its initial state, where |s| stands for the length of s. It contains only lowercase English letters. Second line contains a single integer m (1 ≤ m ≤ 300) — the number of queries. The i-th of the next m lines contains three integers li, ri and ki (1 ≤ li ≤ ri ≤ |s|, 1 ≤ ki ≤ 1 000 000) — the description of the i-th query.

Print the resulting string s after processing all m queries.

NoteThe sample is described in problem statement.

s = gets.chomp.split('')
m = gets.to_i
for i in 0..m-1
	l, r, k = gets.split(' ').map{|i| i.to_i}
	l -= 1
	r -= 1
	s = (l > 0 ? s[0..l-1] : []) + s[l..r].rotate(-k) + s[r+1..s.length-1]
end

puts s.reduce{|a, b| a << b}

s = gets
m = gets.to_i
while m>0
    l,r,k = gets.split(" ").map(&:to_i)
    new_s = s[l-1,(r-l+1)]
    pre = s[0,l-1]
    post = s[r,s.size]
    k = k%(r-l+1)
    ass = new_s[new_s.size-k,new_s.size]
    arr = ass + new_s.chomp(ass)
    s = pre + arr + post
    m-=1
end
puts s

str = gets.chomp
m = gets.chomp.to_i
for i in 1..m do
  l, r, k = gets.split.map(&:to_i)
  k =  k % (r - l + 1)
  str[l-1..r-1] = str[r-k..r-1] + str[l-1..r-1-k]
end
puts str

s = gets.to_s
m = gets.to_i

m.times do
  l, r, k = gets.split(' ').map{ |x| x.to_i }
  l -= 1
  r -= 1
  k = k % (r-l+1)
  s[l..r] = s[r-k+1..r] + s[l..r-k] if l != r
end

puts s

# c598-B

def process_query(str, l,r,k)
	n = str.size
	a = l-1
	b = r - k % (r-a)
	c = r
	str[0,a] + str[b, c-b] + str[a, b-a] + str[c, n-c]
end

str = gets
gets.to_i.times do
	l, r, k = gets.split.map {|x| Integer(x)}
	str = process_query(str, l, r, k)
end
puts str

#!/usr/bin/env ruby

s = gets.strip # < 10000
m = gets.to_i

m.times.map do
  l_i, r_i, k_i = gets.split(' ').map(&:to_i)
  l_i -= 1
  r_i -= 1

  window_len = r_i - l_i + 1
  k_i = k_i.modulo(window_len)

  slice_len = window_len - k_i
  substr = s.slice!(l_i, slice_len)
  #p s + ' ' + substr
  insertIdx = l_i+k_i
  #p insertIdx
  s.insert(insertIdx, substr)
  #p s
end

puts s

def rotate(s, l, r, k)
  len = r - l + 1
  k = k % len
  result = ''
  result += s[0..l-2] if (l - 2 >= 0)
  result += s[r-k..r-1] if (r-k <= r-1)
  result += s[l-1..r-1-k] if (l-1 <= r-1-k)
  result += s[r..-1] if (r < s.length)
end

s = gets
m = gets.to_i
(1..m).each do
  (l, r, k) = gets.split(' ').map(&:to_i)
  s = rotate(s, l, r, k)
end

puts s

s = gets.chomp.split("")
m = gets.chomp.to_i
m.times do
  l, r, k = gets.chomp.split(" ").map(&:to_i)
  kk = k % (r - l + 1)
  sr = []
  kk.times do
    sr.unshift(s.slice!(r-1))
    r -= 1
  end
  s.insert(l-1, sr).flatten!
end
puts s.join("")

#!/usr/bin/ruby

str = gets.strip()
len = gets.to_i
for iter in 0..len - 1
    l, r, k = gets.split(' ')
    l = l.to_i
    r = r.to_i
    k = k.to_i
    substr = str[l-1..r-1]
    k %= substr.length
    substr = substr[-k, k] + substr[0, substr.length-k]
    substr = substr + str[r..-1]
    if l >= 2
        str = str[0..l-2] + substr
    else
        str = substr
    end
end
puts str

s = gets
m = gets.to_i

def shift(s, step)
  return s if step == 0
  s[-step..-1] + s[0..s.size-step-1]
end

m.times do
  l,r,k = gets.split.map(&:to_i)
  l-=1
  r-=1
  k %= r + 1 - l
  s[l..r] = shift(s[l..r], k)
end
puts(s)

str = gets.chomp
m = gets.chomp.to_i
for i in 1..m do
  l, r, k = gets.split.map(&:to_i)
  for n in 1..k do
    newStr = ""
    newStr << str[r-1]
    newStr << str[l-1..r-2]
    str[l-1..r-1] = newStr
  end
end
puts str

s = gets.to_s
m = gets.to_i

m.times do
  l, r, k = gets.split(' ').map{ |x| x.to_i }
  l -= 1
  r -= 1
  s[l..r] = s[r-k+1..r] + s[l..r-k] if l != r
end

puts s

s = gets.to_s
m = gets.to_i

m.times do
  l, r, k = gets.split(' ').map{ |x| x.to_i }
  l -= 1
  r -= 1
  s[l..r] = s[r-k+1..r] + s[l..r-k]
end

puts s

def rotate(s, l, r, k)
  len = r - l + 1
  k = k % len
  result = ''
  result += s[0..l-2] if (l - 2 > 0)
  result += s[r-k..r-1]
  result += s[l-1..r-1-k]
  result += s[r..-1] if (r < s.length)

end

s = gets
m = gets.to_i
(1..m).each do
  (l, r, k) = gets.split(' ').map(&:to_i)
  s = rotate(s, l, r, k)
end

puts s

s = gets
m = gets.to_i

def shift(s, step)
  return s if step == 0
  s[step..-1] + s[0..step-1]
end

m.times do
  l,r,k = gets.split.map(&:to_i)
  k %= r + 1 - l
  s[l..r] = shift(s[l..r], k)
end
puts(s)

s = gets
m = gets.to_i

def shift(s, step)
  return s if step == 0
  s[0..step-1] + s[step..-1]
end

m.times do
  l,r,k = gets.split.map(&:to_i)
  l-=1
  r-=1
  k %= r + 1 - l
  s[l..r] = shift(s[l..r], k)
end
puts(s)

s = gets
m = gets.to_i

def shift(s, step)
  return s if step == 0
  s[step..-1] + s[0..step-1]
end

m.times do
  l,r,k = gets.split.map(&:to_i)
  l-=1
  r-=1
  k %= r + 1 - l
  s[l..r] = shift(s[l..r], k)
end
puts(s)


A multi-subject competition is coming! The competition has $$$m$$$ different subjects participants can choose from. That's why Alex (the coach) should form a competition delegation among his students. He has $$$n$$$ candidates. For the $$$i$$$-th person he knows subject $$$s_i$$$ the candidate specializes in and $$$r_i$$$ — a skill level in his specialization (this level can be negative!). The rules of the competition require each delegation to choose some subset of subjects they will participate in. The only restriction is that the number of students from the team participating in each of the chosen subjects should be the same.Alex decided that each candidate would participate only in the subject he specializes in. Now Alex wonders whom he has to choose to maximize the total sum of skill levels of all delegates, or just skip the competition this year if every valid non-empty delegation has negative sum.(Of course, Alex doesn't have any spare money so each delegate he chooses must participate in the competition).

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le m \le 10^5$$$) — the number of candidates and the number of subjects. The next $$$n$$$ lines contains two integers per line: $$$s_i$$$ and $$$r_i$$$ ($$$1 \le s_i \le m$$$, $$$-10^4 \le r_i \le 10^4$$$) — the subject of specialization and the skill level of the $$$i$$$-th candidate.

Print the single integer — the maximum total sum of skills of delegates who form a valid delegation (according to rules above) or $$$0$$$ if every valid non-empty delegation has negative sum.

NoteIn the first example it's optimal to choose candidates $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, so two of them specialize in the $$$2$$$-nd subject and other two in the $$$3$$$-rd. The total sum is $$$6 + 6 + 5 + 5 = 22$$$.In the second example it's optimal to choose candidates $$$1$$$, $$$2$$$ and $$$5$$$. One person in each subject and the total sum is $$$6 + 6 + 11 = 23$$$.In the third example it's impossible to obtain a non-negative sum.

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

ans = Array.new(n+1,0)
counter = Array.new(m+1,0) # how many student in ths subject
sum = Array.new(m+1,0) # total point in this subject
students = []
n.times do
    students << gets.split.map(&:to_i)
end

students.sort_by!{|s| -s[1] }

# puts students.inspect

students.each do |s|
    counter[s[0]] += 1
    sum[s[0]] += s[1]

    if sum[s[0]] > 0
        ans[counter[s[0]]] += sum[s[0]]
    end
end

# puts ans.inspect
puts ans.max


In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.

The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.

In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.

NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.

#!/usr/bin/ruby
n,m=gets.split.map(&:to_i)
h={}
gets.split.each{|e|h[e.to_i]=1}
r=[]
(1..1/0.0).each{|i|
	if !h[i]
		break if m<i
		m-=i
		r<<i
	end
}
p r.size
puts r*' '

n, m = gets.chomp.split.map(&:to_i)
hash = {}.tap do |h|
  gets.chomp.split.map(&:to_i).each { |idx| h[idx] = true }
 end

values = []
(1..(10**9)).each do |idx|
  break if idx > m
  next if hash.key?(idx)

  m -= idx
  values << idx
end
puts values.length
puts values.join(' ')

n, m = gets.chomp.split.map(&:to_i)
hash = {}.tap do |h|
  gets.chomp.split.map(&:to_i).each { |idx| h[idx] = true }
 end

values = []
sum = 0
(1..(10**9)).each do |idx|
  next if hash.key?(idx)
  break if sum + idx > m

  sum += idx
  values << idx
end
puts values.length
puts values.join(' ')

n, m = readline.split(' ').collect(&:to_i)
h = Hash[readline.split(' ').collect(&:to_i).collect{|num| [num, true]}]
res = []
ct = 0
left = m

1.upto(m) do |item|
  if item > left
    break
  end
  if !h.has_key?(item)
    res.push(item)
    left -= item
    ct += 1
  end
end

puts ct
res.each_with_index do |item, ind|
  if ind != 0
    print " "
  end
  print item
end
puts ""

n, m = readline.split(' ').collect(&:to_i)
h = Hash[readline.split(' ').collect(&:to_i).collect{|num| [num, true]}]
res = []
ct = 0
left = m

1.upto(m) do |item|
  if item > left
    break
  end
  if !h.has_key?(item)
    res.insert(-1, item)
    left -= item
    ct += 1
  end
end

puts ct
res.each_with_index do |item, ind|
  if ind != 0
    print " "
  end
  print item
end
puts ""

a=gets.chomp.split(" ")
cost=a[1].to_i
b=gets.chomp.split(" ").map {|i| i.to_i}
b.sort!
ans=0
ar=[]
i=1
j=0
loop do

if i!=b[j]
cost-=i
if cost>=0
ans+=1
ar << i
else
break
end

else
j+=1
end

i+=1
break if i == 1000000000

end

puts "#{ans}"
puts ar.join(" ")

buf = gets.split(' ')
n,m=buf[0].to_i, buf[1].to_i
buf = gets.split(' ')
hash = Hash.new
buf.each do |x|
	hash[x.to_i] = 1
end
ans = Array.new
for i in 1..1000000
	break if i>m
	if !hash[i]
		m-=i
		ans<<i
	end
end
puts ans.size
puts ans.join(' ')

require 'set'

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

current = 1
ans = []

until m - current < 0
    if alreadyHas.include? current
        current += 1
        next
    else
        ans << current
        m -= current
        current += 1
    end
end

puts ans.length

ans.each do |a|
    print "#{a} "
end

puts ''

buf = gets.split(' ')
n,m=buf[0].to_i, buf[1].to_i
buf = gets.split(' ')
hash = Hash.new
buf.each do |x|
	hash[x.to_i] = 1
end
ans = Array.new
for i in 1..100000
	break if i>m
	if !hash[i]
		m-=i
		ans<<i
	end
end
puts ans.size
puts ans.join(' ')


Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).

You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.

NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.

# /**
#  * Ashesh Vidyut (Drift King) *
#  */
n, m = gets.chomp.split(" ").map { |i| i.to_i}
a = gets.chomp.split(" ").map { |i| i.to_i}
b = gets.chomp.split(" ").map { |i| i.to_i}
a.sort!
b.sort!
b.reverse!
ans = 0
for i in 0...([m,n].min)
  if a[i] < b[i]
    ans+= b[i] - a[i]
  end
end
puts ans


Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has sequence a consisting of n integers.The subsequence of the sequence a is such subsequence that can be obtained from a by removing zero or more of its elements.Two sequences are considered different if index sets of numbers included in them are different. That is, the values of the elements do not matter in the comparison of subsequences. In particular, any sequence of length n has exactly 2n different subsequences (including an empty subsequence).A subsequence is considered lucky if it has a length exactly k and does not contain two identical lucky numbers (unlucky numbers can be repeated any number of times).Help Petya find the number of different lucky subsequences of the sequence a. As Petya's parents don't let him play with large numbers, you should print the result modulo prime number 1000000007 (109 + 7).

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105). The next line contains n integers ai (1 ≤ ai ≤ 109) — the sequence a.

On the single line print the single number — the answer to the problem modulo prime number 1000000007 (109 + 7).

NoteIn the first sample all 3 subsequences of the needed length are considered lucky.In the second sample there are 4 lucky subsequences. For them the sets of indexes equal (the indexation starts from 1): {1, 3}, {1, 4}, {2, 3} and {2, 4}.

M = 1000000007

def gcd(a, b)
    if b == 0
        [a, 1, 0]
    else
        g, x, y = gcd(b, a % b)
        [g, y, x - a / b * y]
    end
end

def inv(x, p)
    gcd(x, p)[1] % p
end

n, m = gets.split.map(&:to_i)
a = Hash.new(0)
b = 0
gets.split.each do |_|
    if _ =~ /[^47]/
        b += 1
    else
        a[_] += 1
    end
end

r = a.size
c = [1] + [0] * r
a.each do |k, v|
    r.downto(1) do |i|
        c[i] = (c[i] + c[i - 1] * v) % M
    end
end

s = 0
t = 1
0.upto([m, b].min) do |i|
    s += t * c[m - i] if m - i <= r
    t = t * (b - i) * inv(i + 1, M) % M
end
p s % M


You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k > 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  p = gets.chomp.split(" ").map(&:to_i).reverse
  num = Array.new(n+1,false)
  arr = []
  max = p.max
  pre = 0
  i = 0
  while i < n
    num[p[i]] = true
    if p[i] == max
      arr << p[pre..i].reverse
      while num[max]
        max -= 1
      end
      pre = i+1
    end
    i += 1
  end
  ans << arr
end
ans.each do |arr|
  puts arr.join(" ")
end


You have given an array $$$a$$$ of length $$$n$$$ and an integer $$$x$$$ to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be $$$q$$$. If $$$q$$$ is divisible by $$$x$$$, the robot adds $$$x$$$ copies of the integer $$$\frac{q}{x}$$$ to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if $$$q$$$ is not divisible by $$$x$$$, the robot shuts down.Please determine the sum of all values of the array at the end of the process.

The first input line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 10^5$$$, $$$2 \leq x \leq 10^9$$$) — the length of the array and the value which is used by the robot. The next line contains integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the initial values in the array. It is guaranteed that the sum of values $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output one integer — the sum of all elements at the end of the process.

NoteIn the first test case the array initially consists of a single element $$$[12]$$$, and $$$x=2$$$. After the robot processes the first element, the array becomes $$$[12, 6, 6]$$$. Then the robot processes the second element, and the array becomes $$$[12, 6, 6, 3, 3]$$$. After the robot processes the next element, the array becomes $$$[12, 6, 6, 3, 3, 3, 3]$$$, and then the robot shuts down, since it encounters an element that is not divisible by $$$x = 2$$$. The sum of the elements in the resulting array is equal to $$$36$$$.In the second test case the array initially contains integers $$$[4, 6, 8, 2]$$$, and $$$x=2$$$. The resulting array in this case looks like $$$ [4, 6, 8, 2, 2, 2, 3, 3, 4, 4, 1, 1, 1, 1, 1, 1]$$$.

def read
  gets.split.map &:to_i
end
gets.to_i.times do
  n, x = read
  a = read
  res, b = a.sum, a.dup
  while true
    ok = true
    (0...n).each do |i|
      break unless ok
      if b[i] % x == 0
        b[i] /= x
        res += a[i]
      else
        ok = false
      end
    end
    break unless ok
  end
  puts res
end

t = gets.chomp.to_i
t.times do
  n, x = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  brr = [0] * arr.size
  min = 10 ** 10
  min_i = -1
  sum = [0] * (arr.size + 1)
  arr.each_with_index do |el, ind|
    sum[ind + 1] = sum[ind] + el
    t = 0
    el1 = el
    while el1 % x == 0
      el1 /= x
      t += 1
    end
    brr[ind] = t
    if t < min
      min = t
      min_i = ind
    end
  end
  res = sum[arr.size] * (min + 1) + sum[min_i]
  puts res
end

t = gets.to_i
ans = []
t.times do
  n,x = gets.chomp.split(" ").map(&:to_i)
  a = gets.chomp.split(" ").map(&:to_i)
  b = a.dup
  arr = Array.new(n,0)
  n.times do |i|
    while b[i] % x == 0
      b[i] /= x
      arr[i] += 1
    end
  end
  min = arr.min
  judge = false
  sum = 0
  n.times do |i|
    judge = true if arr[i] == min
    if judge
      sum += a[i] * (min+1)
    else
      sum += a[i] * (min+2)
    end
  end
  ans << sum
end
puts ans

def read
  gets.split.map &:to_i
end
gets.to_i.times do
  n, x = read
  a = read
  res, b = a.sum, a
  while true
    ok = true
    (0...n).each do |i|
      break unless ok
      if b[i] % x == 0
        b[i] /= x
        res += a[i]
      else
        ok = false
      end
    end
    break unless ok
  end
  puts res
end


Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!Your task is to write a program which calculates two things:  The maximum beauty difference of flowers that Pashmak can give to Parmida.  The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.

The first line of the input contains n (2 ≤ n ≤ 2·105). In the next line there are n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ 109).

The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.

NoteIn the third sample the maximum beauty difference is 2 and there are 4 ways to do this:  choosing the first and the second flowers;  choosing the first and the fifth flowers;  choosing the fourth and the second flowers;  choosing the fourth and the fifth flowers.

#!/usr/bin/ruby

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

b.sort!

a1 = b[0]
a2 = b[b.length-1]

c1 = 0
c2 = 0

b.each { |x|
  if x == a1
    c1 += 1
  end }

b.each { |x|
  if x == a2
    c2 += 1
  end }

if a1 == a2
  ans = b.length * (b.length - 1) / 2
  puts  "0 #{ans}"
else
  puts  "#{a2 - a1} #{c1 * c2}"
end

n = gets.to_i
b = gets.split.map{|r| r.to_i}.sort

if b[n-1] > b[0]
   counters = b.select{|r| r == b[n-1]}.size
   xounterz = b.select{|r| r == b[0]}.size
   puts (b[n-1]-b[0]).to_s + " " + (counters*xounterz).to_s
else
   puts "0" + ' ' + (b.size * (b.size - 1)/2).to_s
end

n = gets.to_i
x = gets.split.map(&:to_i)
l, r = x.max, x.min
if l > r
  puts (l - r).to_s + " " + (x.select{|i| i == l}.size * x.select{|i| i == r}.size).to_s
else
  puts "0" + " " + (x.size * (x.size - 1) / 2).to_s
end

n, b = gets.to_i, gets.split.map { |x| x.to_i }.sort
max_d = b.last - b.first
arr = Hash.new(0)
b.each_with_index { |x| arr[x] += 1 }
if arr.size == 1
  print max_d, " ", arr[b.last] * (arr[b.last] - 1) / 2
else
  print max_d, " ", arr[b.last] * arr[b.first]
end

gets
x=gets.split.map{|e| e.to_i}
min1=x.min
max1=x.max
c1=x.count{|e|
	e==min1
}
c2=x.count{|e|
	e==max1
}

if min1==max1 then
	puts [0,(c1*(c1-1))/2]*" "
else
	puts [max1-min1,c1*c2]*" "
end

n = gets.to_i
flowers = Hash.new(0)

min, max = gets.chomp.split.map { |value| value.to_i }.each { |value| flowers[value] += 1 }.sort.minmax

dif = max - min
path = 0

if dif != 0
    flowers.each { |key, value| path += value * flowers[key - dif] }
else
    path = n * (n - 1) / 2
end

puts "#{dif} #{path}"

n = gets.to_i
flowers = Hash.new(0)

min, max = gets.chomp!.split.map! { |value| value.to_i }.each { |value| flowers[value] += 1 }.sort!.minmax

dif = max - min
path = 0

if dif != 0
    flowers.each { |key, value| path += value * flowers[key - dif] }
else
    path = n * (n - 1) / 2
end

puts "#{dif} #{path}"

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
min, min_counter = 10**9, 0
max, max_counter = 0, 0
gets.split.each { |i|
    i = i.to_i
    if i < min
        min = i
        min_counter = 0
    end

    if i == min
        min_counter += 1
    end

    if i > max
        max = i
        max_counter = 0
    end

    if i == max
        max_counter += 1
    end
}

if max != min
    puts "#{max - min} #{min_counter * max_counter}"
else
    # n C 2
    # -> n! / (2! * (n-2)!)
    # -> (n * (n -1)) / 2!
    # -> n * (n - 1) / 2
    combination = max_counter * (max_counter - 1) / 2
    puts "#{max - min} #{combination}"
end

# pair of two flowers
# first: maximum beauty difference
# second: how many ways to create the diff?

n = Integer(gets)
nums = gets.chomp.split
b = Array.new
for i in 0...n
    b[i] = Integer(nums[i])
end

b.sort!
min = Array.new
max = Array.new
min[0] = b[0]
max[0] = b[n-1]

gap = b[n-1] - b[0]
for i in 0...n-1
    if b[i+1] == b[0]
        min.push(b[i+1])
    end
    if b[n-i-2] == b[n-1]
        max.push(b[n-i-2])
    end
end

if gap != 0
    print gap , " " , min.length * max.length
else
    if n != 2
        ways = n * (n-1) / 2
        print gap , " " , ways
    else
        print gap, " " , "1"
    end
end

def read_ints; STDIN.gets.split.map(&:to_i); end
n = gets.to_i
a = read_ints
_max = a.max
_min = a.min
print _max-_min
a1 = 0
a2 = 0
i=0
n.times do
  if(a[i] == _max)
    a1+=1
  elsif (a[i] == _min)
    a2+=1
  end
  i+=1
end
print ' '
if(_max == _min)
  puts a1 * (a1-1) / 2
else
puts a1 * a2
end

n = gets.to_i
b = {}
h = Hash.new { |h, k| h[k] = 0 }
a = gets.split(/\s+/).map {|q| r = q.to_i; h[r]+=1; r}

r = 0
diff = a.max - a.min
if diff > 0
  a.each {|q| r += h[q + diff] }
else
  h.each {|k,v| r += v*(v-1)/2 if v > 1 }
end

puts "#{diff} #{r}"

gets

freq = {}
flowers = []
gets.split(/\s+/).each do |f|
  f = f.to_i

  if freq[f].nil?
    freq[f] = 1
  else
    freq[f] += 1
  end
  flowers << f
end

flowers.sort!

first = flowers[0]
last = flowers[-1]

if(first == last)
  puts "#{last - first} #{(freq[first] * (freq[last]-1))/2}"
else
  puts "#{last - first} #{freq[first] * freq[last]}"
end

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

max = a.max
min = a.min

cmax = a.count(max)
cmin = a.count(min)

count = max == min ? cmax*(cmax-1)/2 : cmax*cmin

puts "#{max - min} #{count}"

line = gets
n = line.to_i
line = gets
f = line.split.map(&:to_i)
f_s = f.sort
d = f_s.last - f_s.first
f_m = {}
f.map do |i|
	next unless [f_s.first, f_s.last].include?(i)
	f_m[i] ||= 0
	f_m[i] += 1
end
w = if f_s.first != f_s.last
	f_m[f_s.first] * f_m[f_s.last]
else
	(n * (n-1))/2
end
puts "#{d} #{w}"

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

h, l = tab.max, tab.min

if h > l
  puts (h-l).to_s + " " +
    (tab.select{|x| x == h}.size * tab.select{|x| x == l}.size).to_s
else
  puts "0 " + (tab.size * (tab.size-1)/2).to_s
end

#!/usr/bin/ruby

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

b.sort!

a1 = b[0]
a2 = b[b.length-1]

c1 = 0
c2 = 0

b.each { |x|
  if x == a1
    c1 += 1
  end }

b.each { |x|
  if x == a2
    c2 += 1
  end }

if a1 == a2
  c1 = 0
end

puts  "#{a2 - a1} #{c1 * c2}"

#!/usr/bin/ruby

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

b.sort!

a1 = b[0]
a2 = b[b.length-1]

c1 = 0
c2 = 0

b.each { |x|
  if x == a1
    c1 += 1
  end }

b.each { |x|
  if x == a2
    c2 += 1
  end }

puts  "#{a2 - a1} #{c1 * c2}"

n = gets.to_i
b = gets.split.map{|r| r.to_i}.sort

counters = b.select{|r| r == b[n-1]}.size
xounterz = b.select{|r| r == b[0]}.size

puts (b[n-1]-b[0]).to_s + " " + (counters*xounterz).to_s

n = gets.to_i
b = gets.split.map{|r| r.to_i}.sort

counters = 1
xounterz = 1
for i in 1..n-2
  if b[i] == b[0]
     counters+=1
   elsif b[i] == b[n-1]
     xounterz+=1
  end
end

puts b[n-1]-b[0]
puts counters*xounterz

n = gets.to_i
b = gets.split.map{|r| r.to_i}.sort

counters = 1
xounterz = 1
for i in 1..n-2
  if b[i] == b[0]
     counters+=1
  elsif b[i] == b[n-1]
     xounterz+=1
  end
end

max = [b[n-1]-b[0], counters*xounterz]
puts max

n = gets.to_i
b = gets.split.map{|r| r.to_i}.sort

counters = 1
xounterz = 1
for i in 1..n-2
  if b[i] == b[0]
     counters+=1
   elsif b[i] == b[n-1]
     xounterz+=1
  end
end

puts (b[n-1]-b[0]).to_s + " " + (counters*xounterz).to_s

n = gets.to_i
b = gets.split.map{|r| r.to_i}.sort

if b[n-1] > b[0]
   counters = b.select{|r| r == b[n-1]}.size
   xounterz = b.select{|r| r == b[0]}.size
   puts (b[n-1]-b[0]).to_s + " " + (counters*xounterz).to_s
else
   puts "0 1"
end

n = gets.to_i
b = gets.split.map{|r| r.to_i}.sort

counters = 1
xounterz = 1
for i in 1..n-2
  if b[i] == b[0]
     counters+=1
  elsif b[i] == b[n-1]
     xounterz+=1
  end
end

max = [b[n-1]-b[0], counters*xounterz]
max

n = gets.to_i
x = gets.split.map(&:to_i)
l, r = x.max, x.min
if l > r
  puts (l - r).to_s + " " + (x.select{|i| i == l}.size * x.select{|i| i == r}.size).to_s
else
  puts "0" + (x.size * (x.size - 1) / 2).to_s
end

n, b = gets.to_i, gets.split.map { |x| x.to_i }.sort
max_d = b.last - b.first
am = 0
b.each do |x|
  (x..b.last).step(1) do |j|
    am += 1 if (j - x).abs == max_d
  end
end
print max_d, " ",am

n, b = gets.to_i, gets.split.map { |x| x.to_i }.sort
max_d = b.last - b.first
arr = Hash.new(0)
b.each_with_index { |x| arr[x] += 1 }
print max_d, " ", arr[b.last] * arr[b.first]

n, b = gets.to_i, gets.split.map { |x| x.to_i }.sort
max_d = b.last - b.first
am = 0
b.each do |x|
 b[b.index(x) + 1..b.last].each do |y|
   am += 1 if (y - x).abs == max_d
  end
end
print max_d, " ",am

n, b = gets.to_i, gets.split.map { |x| x.to_i }.sort
max_d = b.last - b.first
arr = Hash.new(0)
b.each_with_index { |x| arr[x] += 1 }
if arr.size == 1
  print max_d, " ", arr[b.last] - 1
else
  print max_d, " ", arr[b.last] * arr[b.first]
end

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
min, min_counter = 10**9, 0
max, max_counter = 0, 0
gets.split.each { |i|
    i = i.to_i
    if i < min
        min = i
        min_counter = 0
    end

    if i == min
        min_counter += 1
    end

    if i > max
        max = i
        max_counter = 0
    end

    if i == max
        max_counter += 1
    end
}

if max != min
    puts "#{max - min} #{min_counter * max_counter}"
else
    puts "0 0"
end

# pair of two flowers
# first: maximum beauty difference
# second: how many ways to create the diff?

n = Integer(gets)
nums = gets.chomp.split
b = Array.new
for i in 0...n
    b[i] = Integer(nums[i])
end

b.sort!
min = Array.new
max = Array.new
min[0] = b[0]
max[0] = b[n-1]

gap = b[n-1] - b[0]
for i in 0...n-1
    if b[i+1] == b[0]
        min.push(b[i+1])
    end
    if b[n-i-2] == b[n-1]
        max.push(b[n-i-2])
    end
end
ways = 0
while n >= 2
    ways += (n-1) * n
    n -= 1
end
if gap != 0
    print gap , " " , min.length * max.length
else
    print gap , " " , ways
end

n = Integer(gets)
nums = gets.chomp.split
b = Array.new
for i in 0...n
    b[i] = Integer(nums[i])
end

b.sort!
min = Array.new
max = Array.new
min[0] = b[0]
max[0] = b[n-1]

gap = b[n-1] - b[0]
for i in 0...n-1
    if b[i+1] == b[0]
        min.push(b[i+1])
    end
    if b[n-i-2] == b[n-1]
        max.push(b[n-i-2])
    end
end

if gap != 0
    print gap , " " , min.length * max.length
else
    if n != 2
        ways = 0
        while n >= 2
            ways += (n-1) * n
            n -= 1
        end
        print gap , " " , ways
    else
        print gap, " " , "1"
    end
end

def read_ints; STDIN.gets.split.map(&:to_i); end
n = gets.to_i
a = read_ints
_max = a.max
_min = a.min
print _max-_min
a1 = 0
a2 = 0
i=0
n.times do
  if(a[i] == _max)
    a1+=1
  elsif (a[i] == _min)
    a2+=1
  end
  i+=1
end
print ' '
puts a1 * a2

n = gets.to_i
b = {}
h = Hash.new { |h, k| h[k] = 0 }
a = gets.split(/\s+/).map {|q| r = q.to_i; h[r]+=1; r}

r = 0
diff = a.max - a.min
if diff > 0
  a.each {|q| r += h[q + diff] }
else
  h.each {|k,v| r += v-1 if v > 1 }
end

puts "#{diff} #{r}"

n = gets.to_i
h = Hash.new { |h, k| h[k] = 0 }
a = gets.split(/\s+/).map {|q| r = q.to_i; h[r]+=1; r}

r = 0
diff = a.max - a.min
a.each {|q| r += h[q + diff] }

puts "#{diff} #{r}"

n = gets.to_i
b = {}
h = Hash.new { |h, k| h[k] = 0 }
a = gets.split(/\s+/).map {|q| r = q.to_i; h[r]+=1; r}

r = 0
diff = a.max - a.min
if diff > 0
  a.each {|q| r += h[q + diff] }
else
  h.each {|k,v| r += 2**(v-1)-1 if v > 1 }
end

puts "#{diff} #{r}"

gets

freq = {}
flowers = []
gets.split(/\s+/).each do |f|
  f = f.to_i

  if freq[f].nil?
    freq[f] = 1
  else
    freq[f] += 1
  end
  flowers << f
end

flowers.sort!

first = flowers[0]
last = flowers[-1]

if(first == last)
  puts "#{last - first} #{freq[first] * (freq[last]-1)}"
else
  puts "#{last - first} #{freq[first] * freq[last]}"
end

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

puts "#{a.max - a.min} #{a.count(a.max)*a.count(a.min)}"

line = gets
n = line.to_i
line = gets
f = line.split.map(&:to_i)
f_s = f.sort
d = f_s.last - f_s.first
f_m = {}
f.map do |i|
	next unless [f_s.first, f_s.last].include?(i)
	f_m[i] ||= 0
	f_m[i] += 1
end
w = if f_m.size > 1
	f_m[f_s.first] * f_m[f_s.last]
else
	(n * n-1)/2
end
puts "#{d} #{w}"

line = gets
n = line.to_i
line = gets
f = line.split.map(&:to_i)
f_s = f.sort
d = f_s.last - f_s.first
f_m = {}
f.map do |i|
	next unless [f_s.first, f_s.last].include?(i)
	f_m[i] ||= 0
	f_m[i] += 1
end
w = if f_m.size > 1
	f_m[f_s.first] * f_m[f_s.last]
else
	1
end
puts "#{d} #{w}"

line = gets
n = line.to_i
line = gets
f = line.split.map(&:to_i)
f_s = f.sort
d = f_s.last - f_s.first
f_m = {}
f.map do |i|
	next unless [f_s.first, f_s.last].include?(i)
	f_m[i] ||= 0
	f_m[i] += 1
end
w = if f_s.first != f_s.last
	f_m[f_s.first] * f_m[f_s.last]
else
	1
end
puts "#{d} #{w}"

line = gets
n = line.to_i
line = gets
f = line.split.map(&:to_i)
f_s = f.sort
d = f_s.last - f_s.first
f_m = {}
f.map do |i|
	next unless [f_s.first, f_s.last].include?(i)
	f_m[i] ||= 0
	f_m[i] += 1
end
w = if f_s.first == f_s.last
	f_m[f_s.first] * f_m[f_s.last]
else
	(n * (n-1))/2
end
puts "#{d} #{w}"

line = gets
n = line.to_i
line = gets
f = line.split.map(&:to_i)
f_s = f.sort
d = f_s.last - f_s.first
f_m = {}
f.map do |i|
	next unless [f_s.first, f_s.last].include?(i)
	f_m[i] ||= 0
	f_m[i] += 1
end
w = f_m[f_s.first] * f_m[f_s.last]
puts "#{d} #{w}"

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

h, l = tab.max, tab.min

if h > l
  puts (h-l).to_s + " " +
    (tab.select{|x| x == h}.size * tab.select{|x| x == l}.size).to_s
else
  puts "0 " + (tab.size * (tab.size-1)).to_s
end

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

h, l = tab.max, tab.min

if h != l
  puts (h-l).to_s + " " +
    (tab.select{|x| x == h}.size * tab.select{|x| x == l}.size).to_s
else
  puts "0 " + (tab.size * (tab.size-1)).to_s
end

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

h, l = tab.max, tab.min

puts (h-l).to_s + " " +
  (tab.select{|x| x == h}.size * tab.select{|x| x == l}.size).to_s