Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold:  there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj;  value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them.

The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106).

Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order.

NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5).

n = gets.to_i
a = gets.split.map(&:to_i)
ll = Array.new(n)
rr = Array.new(n)

i = 0
loop do
  r = i+1
  while r < n
    break if a[r] % a[i] != 0
    r += 1
  end
  rr[i] = r-1
  break if r == n
  i = r
end

i = n-1
loop do
  l = i-1
  while l >= 0
    break if a[l] % a[i] != 0
    l -= 1
  end
  i.downto(l+1) do |j|
    ll[j] = l+1
  end
  break if l < 0
  i = l
end

best = 0
n.times do |i|
  best = [best, rr[i]-ll[i]].max if rr[i]
end

ans = []
n.times do |i|
  if rr[i] and rr[i]-ll[i] == best
    ans << ll[i]+1
  end
end

puts "#{ans.size} #{best}"
puts ans.join(' ')
# p ll, rr

n=gets.to_i
a=gets.split.map(&:to_i)
def f a,n,d
  h={}
  b=[]
  (n+1).times do |i|
    j=d>0 ? n-i-1 : i
    h.delete_if do |k,v|
      if i==n||a[j]%k>0
        p=v>j ? j : v
        q=v>j ? v : j
        p=0 if p<0
        q=n-1 if q==n
        (p..q).each {|x|b[x]=j+d if a[x]==k}
        true
      else
        false
      end
    end
    h[a[j]]||=j
  end
  b
end
r=f(a,n,-1)
l=f(a,n,1)

b=n.times.map{|x|r[x]-l[x]}
m=b.max
c=n.times.map{|x| l[x]+1 if b[x]==m}.select{|x|x}.sort.uniq
puts "#{c.size} #{m}"
puts c.join(' ')

n=gets.to_i
a=gets.split.map(&:to_i)
l=[]
r=[]
h={}
(n+1).times do |i|
  h.delete_if do |k,v|
    if i==n||a[i]%k>0
      (v..i).each {|x|r[x]=i-1 if a[x]==k}
      true
    else
      false
    end
  end
  h[a[i]]||=i if a[i]
end

(n+1).times do |i|
  h.delete_if do |k,v|
    if i==n||a[n-1-i]%k>0
      ([n-1-i,0].max..v).each {|x|l[x]=n-i if a[x]==k}
      true
    else
      false
    end
  end
  h[a[n-1-i]]||=n-1-i if a[i]
end

b=n.times.map{|x|r[x]-l[x]}
m=b.max
c=n.times.map{|x| l[x]+1 if b[x]==m}.select{|x|x}.sort.uniq
puts "#{c.size} #{m}"
puts c.join(' ')

n=gets.to_i
a=gets.split.map(&:to_i)
l=[]
r=[]
h={}
n.times do |i|
  h.delete_if do |k,v|
    if a[i]%k>0
      (v..i).each {|x|r[x]=i-1 if a[x]==k}
      true
    else
      false
    end
  end
  h[a[i]]||=i
end

h.delete_if do |k,v|
    (v..n-1).each {|x|r[x]=n-1 if a[x]==k}
    true
end

n.times do |i|
  h.delete_if do |k,v|
    if a[n-1-i]%k>0
      (n-1-i..v).each {|x|l[x]=n-i if a[x]==k}
      true
    else
      false
    end
  end
  h[a[n-1-i]]||=n-1-i
end

h.delete_if do |k,v|
  (0..v).each {|x|l[x]=0 if a[x]==k}
  true
end

b=n.times.map{|x|r[x]-l[x]}
m=b.max
c=n.times.map{|x| l[x]+1 if b[x]==m}.select{|x|x}.sort.uniq
puts "#{c.size} #{m}"
puts c.join(' ')

n=gets.to_i
a=gets.split.map(&:to_i)
l=[]
r=[]
h={}
n.times do |i|
  h.delete_if do |k,v|
    if a[i]%k>0
      (v..i).each {|x|r[x]=i-1 if a[x]==k}
      true
    else
      false
    end
  end
  h[a[i]]||=i
end

h.delete_if do |k,v|
    (v..n-1).each {|x|r[x]=n-1 if a[x]==k}
    true
end

n.times do |i|
  h.delete_if do |k,v|
    if a[n-1-i]%k>0
      (n-1-i..v).each {|x|l[x]=n-i if a[x]==k}
      true
    else
      false
    end
  end
  h[a[n-1-i]]||=n-1-i
end

h.delete_if do |k,v|
  (0..v).each {|x|l[x]=0 if a[x]==k}
  true
end

b=n.times.map{|x|r[x]-l[x]}
m=b.max
puts "#{b.count(m)} #{m}"
n.times.map{|x| print "#{l[x]+1} " if b[x]==m}

n=gets.to_i
a=gets.split.map(&:to_i)
def f a,n,d
  h={}
  b=[]
  (n+1).times do |i|
    j=d>0 ? n-i-1 : i
    h.delete_if do |k,v|
      if i==n||a[j]%k>0
        ([[v,j].min,0].max..[[v,j].max,n-1].min).each {|x|b[x]=j+d if a[x]==k}
        true
      else
        false
      end
    end
    h[a[j]]||=j
  end
  b
end
r=f(a,n,1)
l=f(a,n,-1)

b=n.times.map{|x|r[x]-l[x]}
m=b.max
c=n.times.map{|x| l[x]+1 if b[x]==m}.select{|x|x}.sort.uniq
puts "#{c.size} #{m}"
puts c.join(' ')

n=gets.to_i
a=gets.split.map(&:to_i)
l=[]
r=[]
h={}
n.times do |i|
  h.delete_if do |k,v|
    if a[i]%k>0
      (v..i).each {|x|r[x]=i-1 if a[x]==k}
      true
    else
      false
    end
  end
  h[a[i]]||=i
end

h.delete_if do |k,v|
    (v..n-1).each {|x|r[x]=n-1 if a[x]==k}
    true
end

n.times do |i|
  h.delete_if do |k,v|
    if a[n-1-i]%k>0
      (n-1-i..v).each {|x|l[x]=n-i if a[x]==k}
      true
    else
      false
    end
  end
  h[a[n-1-i]]||=n-1-i
end

h.delete_if do |k,v|
  (0..v).each {|x|l[x]=0 if a[x]==k}
  true
end

b=n.times.map{|x|r[x]-l[x]}
m=b.max
puts "#{b.count(m)} #{m}"
puts n.times.map{|x| l[x]+1 if b[x]==m}.select{|x|x}.sort.uniq


You've got an array, consisting of n integers a1, a2, ..., an. Also, you've got m queries, the i-th query is described by two integers li, ri. Numbers li, ri define a subsegment of the original array, that is, the sequence of numbers ali, ali + 1, ali + 2, ..., ari. For each query you should check whether the corresponding segment is a ladder. A ladder is a sequence of integers b1, b2, ..., bk, such that it first doesn't decrease, then doesn't increase. In other words, there is such integer x (1 ≤ x ≤ k), that the following inequation fulfills: b1 ≤ b2 ≤ ... ≤ bx ≥ bx + 1 ≥ bx + 2... ≥ bk. Note that the non-decreasing and the non-increasing sequences are also considered ladders.

The first line contains two integers n and m (1 ≤ n, m ≤ 105) — the number of array elements and the number of queries. The second line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where number ai stands for the i-th array element. The following m lines contain the description of the queries. The i-th line contains the description of the i-th query, consisting of two integers li, ri (1 ≤ li ≤ ri ≤ n) — the boundaries of the subsegment of the initial array. The numbers in the lines are separated by single spaces.

Print m lines, in the i-th line print word "Yes" (without the quotes), if the subsegment that corresponds to the i-th query is the ladder, or word "No" (without the quotes) otherwise.

n,m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
plus = Array.new(n+2, 0)
minus = Array.new(n+2,0)
a<<0
n.times do |i|
	j = n-i-1
	if ( a[j]<=a[j+1])
		plus[n-i] = plus[n-i+1] +1
	else
		plus[n-i] = 0
	end
	if ( a[j]>=a[j+1])
		minus[n-i] = minus[n-i+1] +1
	else
		minus[n-i] = 0
	end
end
m.times do
	l,r = gets.split.map(&:to_i)
	x = l + plus[l]
	if ( x>=r)
		puts "Yes"
	else
		x = x+minus[x]
		if (x>=r)
			puts "Yes"
		else
			puts "No"
		end
	end
end

def binary(l, r, lx, rx)
	x = (lx+rx)/2
	#puts "#{lx} #{rx} #{x}"
	if ( lx >= rx)
		return 0
	end
	if ( $minus[x]-$minus[l-1]>0)
		return binary(l, r, lx, x)
	elsif ( $plus[r]-$plus[x]>0)
		return binary(l, r, x+1, rx)
	elsif ( $minus[x]-$minus[l-1]==0 && $plus[r]-$plus[x]==0)
		return 1
	else
		return 0
	end
end

n,m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
$plus = [0]
$minus = [0]
n.times do |i|
	if (i==0)
		$plus << 0
		$minus << 0
	else
		if (a[i]>a[i-1])
			$plus << $plus[-1] + 1
		else
			$plus << $plus[-1]
		end;
		if (a[i]<a[i-1])
			$minus << $minus[-1] + 1
		else
			$minus << $minus[-1]
		end
	end
end
m.times do
	l,r = gets.split.map(&:to_i)
	puts ($plus[r]-$plus[l-1]==0 || binary(l, r, l, r)==1) ? "Yes" : "No"
end


Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n × n matrix with a diamond inscribed into it.You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.

The only line contains an integer n (3 ≤ n ≤ 101; n is odd).

***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***

size = gets.chomp.to_i

(1..(size/2 + 1)).each do |i|
	dn = (2 * i - 1)
	print "*" * ((size - dn) / 2)
	print "D" * dn
	print "*" * ((size - dn) / 2)
	puts ""
end

((size/2 + 2)..size).each do |j|
	i = size - j + 1
	dn = (2 * i - 1)
	print "*" * ((size - dn) / 2)
	print "D" * dn
	print "*" * ((size - dn) / 2)
	puts ""
end

n = gets.chomp.to_i
start = (n / 2) + 1
dNum = 0

(0...n).each do |row|
	if row <= n / 2
		dNum = 2 * (row + 1) - 1
		start -= 1
	else
		dNum = (-2 * row + (2 * n - 1))
		start += 1 if row > n / 2
	end

	(0...n).each do |col|
		if col >= start && dNum > 0
			print 'D'
			dNum -= 1
		else
			print '*'
		end
	end

	puts ''
end

class Crystal
  def initialize(size)
    @size = size
  end

  def draw_diamond
    @size.times do |i|
      if i <= @size / 2
        cut_size = @size / 2 - i
      else
        cut_size = i - @size / 2
      end
      puts(("*" * cut_size ) +
          ("D" * (@size - cut_size * 2)) +
          ("*" * cut_size ))
    end
  end
end

Crystal.new(gets.to_i).draw_diamond

#!/usr/bin/env ruby

n = gets.to_i

arr = []
(n/2).times do |r|
  l = ("D" * (r+1)).rjust((n+1)/2, "*")
  arr << l + l.reverse[1..-1]
end

puts arr
puts "D" * n
puts arr.reverse

n = gets.to_i

i = 1
while i<=n
    t = (n-i)/2
    for j in 1..t
        print "*"
    end
    for j in 1..i
        print "D"
    end
    for j in 1..t
        print "*"
    end
    puts ""
    i+=2
end
i = n-2
while i>=1
    t = (n-i)/2
    for j in 1..t
        print "*"
    end
    for j in 1..i
        print "D"
    end
    for j in 1..t
        print "*"
    end
    puts ""
    i-=2
end

class A

  def run
    n = $stdin.gets.to_i
    (1..n).each do |i|
      pad = (n - 2 * i + 1).abs / 2
      fill = n - pad * 2
      puts '*' * pad + 'D' * fill + '*' * pad
    end
  end

end

A.new.run if __FILE__ == $0

n = gets.to_i
(0...n).each do |i|
  a = (n / 2 - i).abs
  b = n - a * 2
  puts '*' * a + 'D' * b + '*' * a
end

n = gets.to_i

size = 1

while size <= n
  ((n - size) / 2).times do print '*' end
  size.times do print 'D' end
  ((n - size) / 2).times do print '*' end
  puts ''
  size += 2
end

size -= 2

while size != 1
  size -= 2
  ((n - size) / 2).times do print '*' end
  size.times do print 'D' end
  ((n - size) / 2).times do print '*' end
  puts ''
end

n = gets.to_i
max_stars = (n - 1) / 2
counter = 0
n.times do |iteration|
  counter = (iteration - max_stars).abs
  puts "*" * counter + "D" * (n - 2 * counter).abs + "*" * counter
end

n = gets.to_i

n.times do |i|
  aaa = n - (n/2 - i).abs * 2
  bbb = (n-aaa)/2
  puts "*" * bbb + "D" * aaa + "*" * bbb
end

n=gets.to_i

n2=n/2
arr=[]
n2.times{|i|
	s=i-n2
	d=1
	str=""
	n.times{
		if 0<=s then
			str<<"D"
		else
			str<<"*"
		end
		s=s+d
		if s==i then
			d=-1
		end
	}
	arr<<str
	puts str
}
puts "D"*n
arr.reverse.each{|e|
	puts e
}

n = gets.to_i
max = n / 2
str = []
for i in 0...max + 1
    rep = max - i
    str[i] = '*' * rep + 'D' * (n - 2 * rep) + '*' * rep
end
puts str + str[0...max].reverse

n = gets.to_i
max = n / 2
str = []
for i in 0..max
    rep = max - i
    str[i] = '*' * rep + 'D' * (n - 2 * rep) + '*' * rep
end
puts str + str[0...max].reverse

def f(n, io)
  h = n / 2
  n.times.each do |i|
    a = (h - i).abs
    d = n - 2*a
    s = '*'*a + 'D'*d + '*'*a
    io.puts s
  end
end

f(STDIN.gets.strip.to_i, STDOUT)

d = gets.chomp
n = Integer(d)
q = n / 2
t = 0
for i in 1..n
    if i > q
        t = n - i + 1
    else
        t = i
    end
    r = q - t + 1
    r.times do
        print "*"
    end
    (t * 2 - 1).times do
        print "D"
    end
    r.times do
        print "*"
    end
    puts ""
end

n = gets.to_i
a = Array.new(n)
i = Array.new(n / 2, "*")
j = ["D"]
for k in 0...n / 2 do
  a[k] = a[n - 1 - k] = (i + j + i).join
  i.pop
  2.times do
    j.push "D"
  end
end

a[n / 2] = Array.new(n, "D").join
puts a

n = gets.to_i
n.times do |i|
  nasterisks, nds = (n/2 - i).abs
  nds = n - nasterisks*2
  nasterisks.times { print '*' }
  nds.times { print 'D' }
  nasterisks.times { print '*' }
  puts
end

n=gets.to_i

diamond=Array.new(n){Array.new(n) {'*'}}
for i in 0..(n/2) do
    for j in (n/2-i)..(n/2+i) do
        diamond[i][j]='D'
        diamond[n-i-1][j]='D'
    end
end

for i in 0...n do
    for j in 0...n do
        print diamond[i][j]
    end
    puts ''
end

n = gets.to_i

str = ""

i = 1
while i < n
  stars = (n - i) / 2

  str += ('*' * stars)
  str += ('D' * i)
  str += ('*' * stars)
  str += "\n"

  i += 2
end

str += ('D' * n) + "\n"

i -= 2
while i > 0
  stars = (n - i) / 2

  str += ('*' * stars)
  str += ('D' * i)
  str += ('*' * stars)
  str += "\n"

  i -= 2
end

puts str

n = gets.to_i
max_stars = (n / 3.0).ceil
counter = 0
n.times do |iteration|
  counter = (iteration - max_stars).abs
  puts "*" * counter + "D" * (n - 2 * counter).abs + "*" * counter
end


Recently, Polycarp completed $$$n$$$ successive tasks.For each completed task, the time $$$s_i$$$ is known when it was given, no two tasks were given at the same time. Also given is the time $$$f_i$$$ when the task was completed. For each task, there is an unknown value $$$d_i$$$ ($$$d_i>0$$$) — duration of task execution.It is known that the tasks were completed in the order in which they came. Polycarp performed the tasks as follows:  As soon as the very first task came, Polycarp immediately began to carry it out.  If a new task arrived before Polycarp finished the previous one, he put the new task at the end of the queue.  When Polycarp finished executing the next task and the queue was not empty, he immediately took a new task from the head of the queue (if the queue is empty — he just waited for the next task). Find $$$d_i$$$ (duration) of each task.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The descriptions of the input data sets follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains exactly $$$n$$$ integers $$$s_1 < s_2 < \dots < s_n$$$ ($$$0 \le s_i \le 10^9$$$). The third line of each test case contains exactly $$$n$$$ integers $$$f_1 < f_2 < \dots < f_n$$$ ($$$s_i < f_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each of $$$t$$$ test cases print $$$n$$$ positive integers $$$d_1, d_2, \dots, d_n$$$ — the duration of each task.

NoteFirst test case:The queue is empty at the beginning: $$$[ ]$$$. And that's where the first task comes in. At time $$$2$$$, Polycarp finishes doing the first task, so the duration of the first task is $$$2$$$. The queue is empty so Polycarp is just waiting.At time $$$3$$$, the second task arrives. And at time $$$7$$$, the third task arrives, and now the queue looks like this: $$$[7]$$$.At the time $$$10$$$, Polycarp finishes doing the second task, as a result, the duration of the second task is $$$7$$$.And at time $$$10$$$, Polycarp immediately starts doing the third task and finishes at time $$$11$$$. As a result, the duration of the third task is $$$1$$$.    An example of the first test case.

#require "prime"
#input of int(split by space)
def get_i()
    return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
    return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
    return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
    return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
    return bool ? y : n
end
#output grid(two dimensional array)
def puts_grid(grid,join_char="")
    grid.each do|line|
        puts line.join(join_char)
    end
end

Dirxy4=[[1,0],[-1,0],[0,1],[0,-1]]
Dirxy8=[[1,0],[1,-1],[1,1],[0,-1],[0,1],[-1,0],[-1,-1],[-1,1]]

INF=Float::INFINITY

#MOD=998_244_353
MOD=10**9+7

T=gets.to_i
T.times do
    n=gets.to_i
    s=get_i
    f=get_i
    ans=[]
    prev=-1
    n.times do |i|
        ans<<f[i]-[s[i],prev].max
        prev=f[i]
    end
    puts ans.join(" ")
end

t = gets.to_i

t.times do
  n = gets.to_i
  s = gets.split.map(&:to_i)
  f = gets.split.map(&:to_i)

  ans = []
  prev = s[0]
  now = f[0]
  1.upto(n-1) do |i|
    if now <= s[i]
      ans << now - prev
      now = f[i]
      prev = s[i]
    else
      ans << now - prev
      prev = now
      now = f[i]
    end
  end
  ans << now - prev
  puts ans.join(" ")
end


Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split!Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).The little walrus's text looks in the following manner: TEXT ::= SENTENCE | SENTENCE SPACE TEXTSENTENCE ::= WORD SPACE SENTENCE | WORD ENDEND ::= {'.', '?', '!'}WORD ::= LETTER | LETTER WORDLETTER ::= {'a'..'z', 'A'..'Z'}SPACE ::= ' 'SPACE stands for the symbol of a space.So, how many messages did Fangy send?

The first line contains an integer n, which is the size of one message (2 ≤ n ≤ 255). The second line contains the text. The length of the text does not exceed 104 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty.

On the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print "Impossible" without the quotes.

NoteLet's take a look at the third sample. The text will be split into three messages: "Hello!", "Do you like fish?" and "Why?".

def min2(x, y)
    if x < y then return x
    else return y
    end
end

def min3(x, y, z)
    if x < y then
        if z < x then return z
        else return x
        end
    else
        if z < y then return z
        else return y
        end
    end
end

def min(x, y, z)
    if x && y && z then return min3(x,y,z)
    elsif x && y then return min2(x,y)
    elsif x && z then return min2(x,z)
    elsif y && z then return min2(y,z)
    elsif x then return x
    elsif y then return y
    else return z
    end
end

n = gets.to_i
s = gets.chomp
s = s.gsub("..", ".").gsub("!!", "!").gsub("??", "?")
result = ""
k = []
dot = s.index(".")
ask = s.index("?")
exp = s.index("!")
k[0] = min(dot, ask, exp)
i = 0
while k[i] && k[i] != s.size-1 do
    i += 1
    dot = s.index(".", k[i-1] + 1)
    ask = s.index("?", k[i-1] + 1)
    exp = s.index("!", k[i-1] + 1)
    k[i] = min(dot, ask, exp)
end
k = k.compact
k = k.sort
str = []
str[0] = s[0..k[0]]
if str[0].size > n
    then result = "Impossible"
else
    i = 1
    while i < k.size do
        str[i] = s[k[i-1]+1..k[i]]
        if str[i].start_with? " " then
            str[i] = str[i][1..-1]
        end
        if str[i].size > n then
            result = "Impossible"
        end
        i += 1
    end
end
if result != "Impossible" then
    if s.size < n then
        result = 1
    else
        result = 0
        i = 0
        while i < k.size do
            sum = str[i].size
            while i + 1 < k.size && sum + str[i+1].size + 1 <= n do
                i += 1
                sum += str[i].size + 1
            end
            i += 1
            result += 1
        end
    end
end
puts "#{result}"

n = gets.to_i
s = gets.scan(/.*?[\.?!]/).map{|_| _.strip.size}
x, y = 0, 0
s.each do |_|
	if _ > n
		puts :Impossible
		exit
	elsif x == 0
		x = _
	else
		x += 1 + _
		if x > n
			x = _
			y += 1
		end
	end
end
if x > 0
	y += 1
end
p y

n = gets.to_i
s = gets.strip
a = s.split(/[.?!] ?/)
if a.any?{|x|x.size > n}
  puts "Impossible"
else
  p s.scan(/.{,#{n-1}}[.?!] ?/).size
end

msgSize, txt=gets.to_i, [gets]
while txt.last.size>msgSize
  if (idx=txt.last[0, msgSize].rindex(/[?.!]/))==nil
    print "Impossible"
    exit
  else
    txt<<txt.last[idx+2...txt.last.size]
  end
end
print txt.keep_if{|v|v!=""}.size

N = gets.to_i
str = gets.chomp

count = 1
current = -1

sentences = str.split(/[.?!]/).map{|e| e.gsub(/^ /, '')}

#p sentences
s = ""
sentences.each {|e|
#  print current

  e += "."
  if e.size > N
    puts "Impossible"
    exit
  end
  current += e.size + 1
  s += " " + e
#  p [e, current]
  if current > N
#    p e
    count += 1
    current = e.size # check! 10 ab ab. ab. abcd abcd.
    s = e
  end
}
puts count

n = gets.to_i
s = gets.strip
if s.split(/[.?!] ?/).any? { |t| t.size >= n }
  puts :Impossible
else
  puts s.scan(/.{,#{n - 1}}[.?!] ?/).size
end

n = STDIN.gets.to_i
text = STDIN.gets.strip
sentences = text.split(/[?|.|!]/)
if !!sentences.find{|s| s.strip.length+1 > n}
  puts "Impossible"
  exit
end
left = n
count = 1
while sentence = sentences.shift
  len = sentence.length + 1
  if left >= len
    #puts sentence
    left -= len
  else
    #puts "new #{sentence}"
    count += 1
    left = n - (sentence.strip.length + 1)
  end
end
puts count

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+\s?/
count = 0
total_size = 0
str = ""
loop do
  if text.sub!(regexp, '').nil? || (str = $&).strip.size > max_size
    puts "Impossible"
    exit
  end
  if total_size + str.size <= max_size
    total_size += str.size
  else
    if total_size + str.strip.size <= max_size
      total_size = 0
      count += 1
    else
      total_size = str.size
      count += 1
    end
  end

  if text == ""
    puts count + 1
    exit
  end
end

n = gets.to_i
s = gets.strip
a = s.split(/[.?!] ?/)
if a.any? {|x| x.size > n}
  puts "Impossible"
else
  puts s.scan(/.{,#{n-1}}[.?!] ?/).size
end

def min2(x, y)
    if x < y then return x
    else return y
    end
end

def min3(x, y, z)
    if x < y then
        if z < x then return z
        else return x
        end
    else
        if z < y then return z
        else return y
        end
    end
end

def min(x, y, z)
    if x && y && z then return min3(x,y,z)
    elsif x && y then return min2(x,y)
    elsif x && z then return min2(x,z)
    elsif y && z then return min2(y,z)
    elsif x then return x
    elsif y then return y
    else return z
    end
end

n = gets.to_i
s = gets.chomp
s = s.gsub("..", ".").gsub("!!", "!").gsub("??", "?")
result = ""
k = []
dot = s.index(".")
ask = s.index("?")
exp = s.index("!")
k[0] = min(dot, ask, exp)
i = 0
while k[i] && k[i] != s.size-1 do
    i += 1
    dot = s.index(".", k[i-1] + 1)
    ask = s.index("?", k[i-1] + 1)
    exp = s.index("!", k[i-1] + 1)
    k[i] = min(dot, ask, exp)
end
k = k.compact
k = k.sort
str = []
str[0] = s[0..k[0]]
if str[0].size > n
    then result = "Impossible"
else
    i = 1
    while i < k.size do
        str[i] = s[k[i-1]+1..k[i]]
        if str[i].start_with? " " then
            str[i] = str[i][1..-1]
        end
        if str[i].size > n then
            result = "Impossible"
        end
        i += 1
    end
end
if result != "Impossible" then
    if s.size < n then
        result = 1
    else
        result = 0
        i = 0
        while i < k.size do
            sum = str[i].size
            while i + 1 < k.size && sum + str[i+1].size + 1 < n do
                i += 1
                sum += str[i].size + 1
            end
            i += 1
            result += 1
        end
    end
end
puts "#{result}"

def min2(x, y)
    if x < y then return x
    else return y
    end
end

def min3(x, y, z)
    if x < y then
        if z < x then return z
        else return x
        end
    else
        if z < y then return z
        else return y
        end
    end
end

def min(x, y, z)
    if x && y && z then return min3(x,y,z)
    elsif x && y then return min2(x,y)
    elsif x && z then return min2(x,z)
    elsif y && z then return min2(y,z)
    elsif x then return x
    elsif y then return y
    else return z
    end
end

n = gets.to_i
s = gets.chomp
result = ""
k = []
dot = s.index(".")
ask = s.index("?")
exp = s.index("!")
k[0] = min(dot, ask, exp)
st = s[k[0]+1..-1]
i = 0
while k[i] && k[i] != s.size-1 do
    i += 1
    if st.include? "." then
        k[i] = st.index(".") + k[i-1] + 1
    elsif st.include? "?" then
        k[i] = st.index("?") + k[i-1] + 1
    else
        k[i] = st.index("!")
        if k[i] then
            k[i] += k[i-1] + 1
        end
    end
    if k[i] then
        st = s[k[i]+1..-1]
    end
end
k = k.compact
k = k.sort
str = []
str[0] = s[0..k[0]]
if str[0].size > n
    then result = "Impossible"
else
    i = 1
    while i < k.size do
        str[i] = s[k[i-1]+1..k[i]]
        if str[i].start_with? " " then
            str[i] = str[i][1..-1]
        end
        if str[i].size > n then
            result = "Impossible"
        end
        i += 1
    end
end
if result != "Impossible" then
    if s.size < n then
        result = 1
    else
        result = 0
        i = 0
        while i < k.size do
            sum = k[i]
            while i + 1 < k.size && sum + k[i+1] + 1 < n do
                i += 1
                sum += k[i] + 1
            end
            i += 1
            result += 1
        end
    end
end
puts "#{result}"

def min2(x, y)
    if x < y then return x
    else return y
    end
end

def min3(x, y, z)
    if x < y then
        if z < x then return z
        else return x
        end
    else
        if z < y then return z
        else return y
        end
    end
end

def min(x, y, z)
    if x && y && z then return min3(x,y,z)
    elsif x && y then return min2(x,y)
    elsif x && z then return min2(x,z)
    elsif y && z then return min2(y,z)
    elsif x then return x
    elsif y then return y
    else return z
    end
end

n = gets.to_i
s = gets.chomp
s = s.gsub("..", ".").gsub("!!", "!").gsub("??", "?")
result = ""
k = []
dot = s.index(".")
ask = s.index("?")
exp = s.index("!")
k[0] = min(dot, ask, exp)
i = 0
while k[i] && k[i] != s.size-1 do
    i += 1
    dot = s.index(".", k[i-1] + 1)
    ask = s.index("?", k[i-1] + 1)
    exp = s.index("!", k[i-1] + 1)
    k[i] = min(dot, ask, exp)
end
k = k.compact
k = k.sort
str = []
str[0] = s[0..k[0]]
if str[0].size > n
    then result = "Impossible"
else
    i = 1
    while i < k.size do
        str[i] = s[k[i-1]+1..k[i]]
        if str[i].start_with? " " then
            str[i] = str[i][1..-1]
        end
        if str[i].size > n then
            result = "Impossible"
        end
        i += 1
    end
end
if result != "Impossible" then
    if s.size < n then
        result = 1
    else
        result = 0
        i = 0
        while i < k.size do
            sum = str[i].size
            while i + 1 < k.size && sum + str[i+1].size + 1 <= n do
                i += 1
                sum += str[i].size + 1
            end
            i += 1
            result += 1
        end
    end
end
p k
p str
puts "#{result}"

msgSize, txt=gets.to_i, [gets]
while txt.last.size>msgSize
  if (idx=txt.last[0, msgSize].rindex(/[?.!]/))==nil
    print "Impossible"
    exit
  else
    txt<<txt.last[idx+2...txt.last.size]
  end
end
print txt.size

N = gets.to_i
str = gets.chomp

count = 1
current = 0

sentences = str.split(/[.?!]/).map{|e| e.gsub(/^ /, '')}

#p sentences
s = ""
sentences.each {|e|
  e += "."
  if e.size > N
    puts "Impossible"
    exit
  end
  current += e.size + 1
  s += " " + e
  if current - 1 > N
#    p e
    count += 1
    current = e.size # check! 10 ab ab. ab. abcd abcd.
    s = e
  end
}
puts count

n = STDIN.gets.to_i
text = STDIN.gets.strip
sentences = text.split(/[?|.|!]/)
if !!sentences.find{|s| s.length+1 > n}
  puts "Impossible"
  exit
end
left = n
count = 1
while sentence = sentences.shift
  len = sentence.length + 1
  if left > len
    left -= len
  else
    count += 1
    left = n - (sentence.strip.length + 1)
  end
end
puts count

n = STDIN.gets.to_i
text = STDIN.gets.strip
sentences = text.split(/[?|.|!]/)
if !!sentences.find{|s| s.length+1 > n}
  puts "Impossible"
  exit
end
left = n
count = 1
while sentence = sentences.shift
  len = sentence.length + 1
  if left >= len
    puts sentence
    left -= len
  else
    puts "new #{sentence}"
    count += 1
    left = n - (sentence.strip.length + 1)
  end
end
puts count

n = STDIN.gets.to_i
text = STDIN.gets.strip
sentences = text.split(/[?|.|!]/)
if !!sentences.find{|s| s.length+1 > n}
  puts "Impossible"
  exit
end
left = n
count = 1
while sentence = sentences.shift
  len = sentence.length + 1
  if left >= len
    #puts sentence
    left -= len
  else
    #puts "new #{sentence}"
    count += 1
    left = n - (sentence.strip.length + 1)
  end
end
puts count

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /\s?[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+(?=\s?)/
count = 0
total_size = 0
loop do
  text.strip!
  size = 0
  if text.sub!(regexp){|s| size = s.size; nil}.nil? || size > max_size
    puts "Impossible"
    exit
  end
  if total_size + size <= max_size
    total_size += size
  else
    count += 1
    total_size = size
  end

  if text == ""
    puts count + 1
    exit
  end
end

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]\s?/
count = 0
loop do
  size = 0
  res = text.sub!(regexp){|s| size = s.size; nil}
  if res.nil? || size > max_size
    puts "Impossible"
    exit
  end
  count += 1
  if text == ""
    puts count
    exit
  end
end

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /\s?[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+(?=\s?)/
count = 0
total_size = 0
loop do
  size = 0
  if text.sub!(regexp){|s| size = s.size; nil}.nil? || size > max_size
    puts "Impossible"
    exit
  end
  if total_size + size <= max_size
    total_size += size
  else
    count += 1
    total_size = size
  end

  if text == ""
    puts count + 1
    exit
  end
end

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+\s?/
count = 0
total_size = 0
loop do
  size = 0
  if text.sub!(regexp){|s| size = s.size; nil}.nil? || size > max_size
    puts "Impossible"
    exit
  end
  if total_size + size < max_size
    total_size += size
  else
    count += 1
    total_size = size
  end

  if text == ""
    puts count + 1
    exit
  end
end

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+(?=\s?)/
count = 0
total_size = 0
loop do
  size = 0
  if text.sub!(regexp){|s| size = s.size; nil}.nil? || size > max_size
    puts "Impossible"
    exit
  end
  if total_size + size <= max_size
    total_size += size
  else
    count += 1
    total_size = size
  end

  if text == ""
    puts count + 1
    exit
  end
end

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+\s?/
count = 0
total_size = 0
loop do
  size = 0
  if text.sub!(regexp){|s| size = s.size; nil}.nil? || size > max_size
    puts "Impossible"
    exit
  end
  if total_size + size <= max_size
    total_size += size
  else
    count += 1
    total_size = size
  end

  if text == ""
    puts count + 1
    exit
  end
end

n = gets.to_i
text = gets.chomp
x = n
ret = 0
impossible = false
text.split(/[\!\.\?]/).each do |sentence|
  if sentence.size + 1 > n
    impossible = true
    break
  end
  ret += 1
end

if impossible
  puts "Impossible"
else
  puts ret
end


The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≤ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.Help the Beaver to write a program that will encrypt messages in the described manner.

The first input line contains three integers n, m and c, separated by single spaces.  The second input line contains n integers ai (0 ≤ ai < c), separated by single spaces — the original message.  The third input line contains m integers bi (0 ≤ bi < c), separated by single spaces — the encryption key. The input limitations for getting 30 points are:    1 ≤ m ≤ n ≤ 103  1 ≤ c ≤ 103  The input limitations for getting 100 points are:    1 ≤ m ≤ n ≤ 105  1 ≤ c ≤ 103

Print n space-separated integers — the result of encrypting the original message.

NoteIn the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.

n,m,c = gets.split.map{|e| e.to_i}
a = gets.split.map{|e| e.to_i}
b = gets.split.map{|e| e.to_i}
ch = []
ch[0]=0
r = []
n-=1
m-=1
for i in 0..m
  ch[i+1]=(ch[i]+b[i]).modulo(c)
end

for i in 0..n
  z = [m+1, i+1].min
  k = [0, m-n+i].max
  r[i] = (a[i]+ch[z]-ch[k]).modulo(c)
end
puts r.join(' ')

n,m,c = gets.split.map{|e| e.to_i}
a = gets.split.map{|e| e.to_i}
b = gets.split.map{|e| e.to_i}
ch = []
ch[0] = b[0]
r = []
n-=1
m-=1
for i in 1..m
  ch[i]=(ch[i-1]+b[i]).modulo(c)
end

r[0]=(a[0]+b[0]).modulo(c)
r[n]=(a[n]+b[m]).modulo(c)
for i in 1..n-1
  if i>=m && n-i>=m
    r[i] = (a[i]+ch[m]).modulo(c)
    next
  end
  if i<n-i
    r[i] = (a[i]+ch[i]).modulo(c)
  else
    r[i] = (a[i]+ch[m]-ch[n-i-1]).modulo(c)
  end
end
puts r.join(' ')


Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.Sasha and Masha are about to buy some coconuts which are sold at price $$$z$$$ chizhiks per coconut. Sasha has $$$x$$$ chizhiks, Masha has $$$y$$$ chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.Consider the following example. Suppose Sasha has $$$5$$$ chizhiks, Masha has $$$4$$$ chizhiks, and the price for one coconut be $$$3$$$ chizhiks. If the girls don't exchange with chizhiks, they will buy $$$1 + 1 = 2$$$ coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have $$$6$$$ chizhiks, Masha will have $$$3$$$ chizhiks, and the girls will buy $$$2 + 1 = 3$$$ coconuts. It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).

The first line contains three integers $$$x$$$, $$$y$$$ and $$$z$$$ ($$$0 \le x, y \le 10^{18}$$$, $$$1 \le z \le 10^{18}$$$) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.

Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.

NoteThe first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy $$$3 + 4 = 7$$$ coconuts.

x,y,z = gets.split.map(&:to_i)
a = (x+y)/z
b = x%z+y%z >= z ? [z-x%z,z-y%z].min : 0
puts "#{a} #{b}"

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

sasha = input_array[0]
masha = input_array[1]
price = input_array[2]

sasha_coconut, sasha_mod = sasha.divmod(price)
masha_coconut, masha_mod = masha.divmod(price)

max = sasha_coconut + masha_coconut

if sasha_mod > masha_mod
  swap = price - sasha_mod
  sasha += swap
  masha -= swap
else
  swap = price - masha_mod
  masha += swap
  sasha -= swap
end

max_temp = (sasha / price) + (masha / price)
max_temp = 0 if max_temp.eql?(nil)

if max_temp > max
  puts "#{max_temp} #{swap}"
else
  puts "#{max} 0"
end

x, y, z = gets.split.map(&:to_i)

a = (x/z) + (y/z)
am = x % z
bm = y % z
aa = (am + bm)/z
if aa > 0
  b = [z-am, z-bm].min
else
  b = 0
end
a += aa
puts "#{a} #{b}"

x,y,z = gets.split.map(&:to_i)
if x/z+y/z < (x+y)/z
    puts "#{(x+y)/z} #{z-[x%z,y%z].max}"
else
    puts "#{x/z+y/z} 0"
end

def prog()
  str = gets
  x,y,z = str.split(" ").map(&:to_i)
  calc(x,y,z)
end

def calc(x,y,z)
  min = 0
  num = 0
  if (x%z + y%z >= z)
    max = (x%z > y%z) ? (x%z) : (y%z)
    min = z - max
    num = 1
  end
  puts "#{x/z + y/z + num} #{min}"
end

prog()

# frozen_string_literal: true

class ChungaChanga
  def initialize(sasha_chizhics, masha_chizhics, coconut_price)
    @sasha_chizhics = sasha_chizhics
    @masha_chizhics = masha_chizhics
    @coconut_price  = coconut_price
  end

  def calculate
    sasha_coconuts, remaining_sasha_chizhics = @sasha_chizhics.divmod(@coconut_price)
    masha_coconuts, remaining_masha_chizhics = @masha_chizhics.divmod(@coconut_price)

    if (remaining_sasha_chizhics + remaining_masha_chizhics) < @coconut_price
      [sasha_coconuts + masha_coconuts, 0]
    else
      bigger_remaining = [remaining_sasha_chizhics, remaining_masha_chizhics].max
      [sasha_coconuts + masha_coconuts + 1, @coconut_price - bigger_remaining]
    end
  end
end

input = gets.chomp.split(' ').map(&:to_i)
result = ChungaChanga.new(*input).calculate
puts result.join(' ')

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

sasha = input_array[0]
masha = input_array[1]
price = input_array[2]

sasha_coconut, sasha_mod = sasha.divmod(price)
masha_coconut, masha_mod = masha.divmod(price)

if sasha_mod.eql?(0) || masha_mod.eql?(0)
  max = sasha_coconut + masha_coconut
  puts "#{max} 0"
else
  if sasha_mod > masha_mod
    swap = price - sasha_mod
    sasha += swap
    masha -= swap
  else
    swap = price - masha_mod
    masha += swap
    sasha -= swap
  end
  max = (sasha / price) + (masha / price)
  puts "#{max} #{swap}"
end

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

sasha = input_array[0]
masha = input_array[1]
price = input_array[2]

sasha_coconut, sasha_mod = sasha.divmod(price)
masha_coconut, masha_mod = masha.divmod(price)

if sasha_mod.eql?(0) && masha_mod.eql?(0)
  max = sasha_coconut + masha_coconut
  puts "#{max} 0"
else
  if sasha_mod > masha_mod
    swap = price - sasha_mod
    sasha += swap
    masha -= swap
  else
    swap = price - masha_mod
    masha += swap
    sasha -= swap
  end
  max = (sasha / price) + (masha / price)
  puts "#{max} #{swap}"
end

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

sasha = input_array[0]
masha = input_array[1]
price = input_array[2]

max = (sasha / price) + (masha / price)

# Choose big number
big_number = [sasha, masha].max
small_number = [sasha, masha].min

mod = big_number % price
swap = price - mod

big_number += swap
small_number -= swap

max_temp = (big_number / price) + (small_number / price)
if max_temp > max
  puts "#{max_temp} #{swap}"
else
  puts "#{max} 0"
end

x, y, z = gets.split.map(&:to_i)

a = (x/z) + (y/z)
am = x % z
bm = y % z
aa = (am + bm)/z
if aa > 0
  b = [am % z, bm%z].min
else
  b = 0
end
a += aa
puts "#{a} #{b}"

x, y, z = gets.split.map(&:to_i)

a = (x + y) / z
b = [x%z, y%z].min
puts "#{a} #{b}"

x, y, z = gets.split.map(&:to_i)

a = (x/z) + (y/z)
am = x % z
bm = y % z
aa = (am + bm)/z
if aa > 0
  b = (am+bm)%z
else
  b = 0
end
a += aa
puts "#{a} #{b}"

x, y, z = gets.split.map(&:to_i)

a = (x + y) / z
if (x+y) >= z
  b = [x%z, y%z].min
else
  b = 0
end
puts "#{a} #{b}"

x, y, z = gets.split.map(&:to_i)

a = (x + y) / z
b = [x, y].min % z
puts "#{a} #{b}"

def prog()
  str = gets
  x,y,z = str.split(" ").map(&:to_i)
  calc(x,y,z)
end

def calc(x,y,z)
  min = 0
  num = 0
  if (x%z + y%z >= z)
    min = (x%z > y%z) ? (y%z) : (x%z)
    num = (x%z + y%z)/z
  end
  puts "#{x/z + y/z + min} #{num}"
end

prog()

def prog()
  str = gets
  x,y,z = str.split(" ").map(&:to_i)
  calc(x,y,z)
end

def calc(x,y,z)
  min = 0
  num = 0
  if (x%z + y%z >= z)
    min = (x%z > y%z) ? (y%z) : (x%z)
    num = (x%z + y%z)/z
  end
  puts "#{x/z + y/z + num} #{min}"
end

prog()

x, y, z = gets.split(' ').map(&:to_i)
puts "#{(x + y) / z} #{[x % z, y % z].min}"


Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types:  Replace $$$i$$$-th element in the array with integer $$$x$$$.  Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query:   If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$) — position of replaced element and it's new value.  If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$) — new value of each element in the array.

Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.

NoteConsider array from the example and the result of performing each query:  Initial array is $$$[1, 2, 3, 4, 5]$$$.  After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$.  After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$.  After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$.  After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$.  After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.

n,q=gets.split.map(&:to_i)
arr=gets.split.map(&:to_i)
sum=arr.sum
hash=Hash.new(0)
cur_mod=1
q.times do
    mod, *arg=gets.split.map(&:to_i)
    if mod==2
        cur_mod=2
        hash=Hash.new(arg[0])
        puts sum= n*arg[0]
    elsif cur_mod==1
        sum+=arg[1]-arr[arg[0]-1]
        arr[arg[0]-1]=arg[1]
        puts sum
    else
        sum+=arg[1]-hash[arg[0]]
        hash[arg[0]]=arg[1]
        puts sum
    end
end

  n, q = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)
  b = [ 0 ] * n
  sum = a.inject(:+)
  all_t = -1
  all_x = 0
  q.times do |t|
    qq = gets.split.map(&:to_i)
    if qq[0] == 1 then
      _, i, x = qq
      if b[i-1] > all_t then
        c = a[i-1]
      else
        c = all_x
      end
      sum +=  x - c
      a[i-1] = x
      b[i-1] = t
    else
      _, x = qq
      all_t = t
      all_x = x
      sum = x * n
    end
    puts sum
  end

n,q=gets.split.map(&:to_i)
arr=gets.split.map(&:to_i)
sum=arr.sum
hash=Hash.new(0)
cur_mod=1
q.times do
    mod, *arg=gets.split.map(&:to_i)
    if mod==2
        cur_mod=2
        hash=Hash.new(arg[0])
        puts sum= n*arg[0]
    elsif cur_mod==1
        sum+=arg[1]-arr[arg[0]-1]
        puts sum
    else
        sum+=arg[1]-hash[arg[0]]
        hash[arg[0]]=arg[1]
        puts sum
    end
end


Andryusha is an orderly boy and likes to keep things in their place.Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?

The first line contains the single integer n (1 ≤ n ≤ 105) — the number of sock pairs. The second line contains 2n integers x1, x2, ..., x2n (1 ≤ xi ≤ n), which describe the order in which Andryusha took the socks from the bag. More precisely, xi means that the i-th sock Andryusha took out was from pair xi. It is guaranteed that Andryusha took exactly two socks of each pair.

Print single integer — the maximum number of socks that were on the table at the same time.

NoteIn the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.In the second example Andryusha behaved as follows:   Initially the table was empty, he took out a sock from pair 2 and put it on the table.  Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table.  Socks (1, 2) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe.  Sock (2) was on the table. Andryusha took out a sock from pair 3 and put it on the table.  Socks (2, 3) were on the table. Andryusha took out a sock from pair 2, and put this pair into the wardrobe.  Sock (3) was on the table. Andryusha took out a sock from pair 3 and put this pair into the wardrobe.  Thus, at most two socks were on the table at the same time.

n=gets.to_i
x=gets.split
h=Hash.new(0)

ans=0
c1=0
x.each{|e|
		if h.key?(e) then
			h.delete(e)
			c1-=1
		else
			h[e]=1
			c1+=1
		end
		ans=[ans,c1].max
}
puts ans

#其实这些简单问题刚好适合ruby解决，让我可以掌握ruby的基本语法！
#就模拟整个过程，得到那个最大数就可以！
n=gets.chomp.to_i
exist=Array.new(100001)
socks=gets.chomp.split(" ")
table=0
count=0
for i in 0..2*n
    if exist[socks[i].to_i]
        exist[socks[i].to_i]=0
        count=count-1 if table > 0
    else
        exist[socks[i].to_i]=1
        count=count+1
    end
    if count>table
        table=count
    end
end
puts table

require 'set'
n=gets.chomp.to_i
#table=Array.new
table = Set.new
socks=gets.chomp.split(" ")
max=0
count=0
#超时了，ruby里不提供类似red black的插入？
for i in 0..2*n
    if table.include?(socks[i])
        table.delete(socks[i])
        count=count-1 if count > 0
    else
        table.add(socks[i])
        count=count+1
    end
    if count>max
        max=count
    end
end
puts max

gets
v, res = Hash.new(nil), []
gets.split.each { |s|
  if v[s]
    v.delete(s)
  else
    v[s] = true
    res.push(v.length)
  end
}
p res.max

#!/usr/bin/ruby
gets;t={};r=0;gets.split.each{|e|
	if t.has_key?(e)
		t.delete(e)
	else
		t[e]=1
		r=[r,t.size].max
	end
};p r

n = gets.strip.to_i
s = gets.strip.split.map(&:to_i)
track = Array.new((2 * n) + 1, false)
ans = count = 0
(2 * n).times do |i|
    curr = s[i]
    if track[curr]
        ans = [ans, count].max
        count -= 1
    else
        track[curr] = true
        count += 1
    end
end
puts ans

n = gets.to_i
a = gets.split.map(&:to_i)
vis = Array.new(n + 1)
cnt = 0
mx = 0
a.each do |x|
  cnt -= 2 if vis[x]
  vis[x] = true
  cnt += 1
  mx = [cnt, mx].max
end
p mx

gets
b, c, maxc  = Hash.new, 0, 0
for a in gets.chomp.split.map{|x| Integer(x)}
  if b.include?(a) then
     b[a], c = true, c-1 if not b[a]
  else
    b[a], c = false, c+1
  end
  maxc = [c, maxc].max
end
puts maxc

n = gets.strip.to_i
s = gets.strip.split.map(&:to_i)
track = {}
ans = 0
n.times do |i|
    curr = s[i]
    track[curr] = 0 if !track[curr]
    track[curr] += 1
    ans += 1 if track[curr] < 2
end
puts ans


This problem is a simplified version of D2, but it has significant differences, so read the whole statement.Polycarp has an array of $$$n$$$ ($$$n$$$ is even) integers $$$a_1, a_2, \dots, a_n$$$. Polycarp conceived of a positive integer $$$k$$$. After that, Polycarp began performing the following operations on the array: take an index $$$i$$$ ($$$1 \le i \le n$$$) and reduce the number $$$a_i$$$ by $$$k$$$.After Polycarp performed some (possibly zero) number of such operations, it turned out that all numbers in the array became the same. Find the maximum $$$k$$$ at which such a situation is possible, or print $$$-1$$$ if such a number can be arbitrarily large.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even integer $$$n$$$ ($$$4 \le n \le 40$$$) ($$$n$$$ is even). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$). It is guaranteed that the sum of all $$$n$$$ specified in the given test cases does not exceed $$$100$$$.

For each test case output on a separate line an integer $$$k$$$ ($$$k \ge 1$$$) — the maximum possible number that Polycarp used in operations on the array, or $$$-1$$$, if such a number can be arbitrarily large.

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	a = a.sort
	res = 0; tmp = a[0]
	a.map! {|ai| ai - tmp}
	a.map! {|x| res = res.gcd(x)}
	puts res != 0? res:-1
end

gets.to_i.times do

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

a_min = a.min
a.map! { |ai| ai - a_min }
a.delete_if { |ai| ai == 0 }

if a.empty?
  puts -1
else
  puts a.inject(0, :gcd)
end

end


You have $$$n$$$ students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the $$$i$$$-th student skill is denoted by an integer $$$a_i$$$ (different students can have the same skills).So, about the teams. Firstly, these two teams should have the same size. Two more constraints:  The first team should consist of students with distinct skills (i.e. all skills in the first team are unique).  The second team should consist of students with the same skills (i.e. all skills in the second team are equal). Note that it is permissible that some student of the first team has the same skill as a student of the second team.Consider some examples (skills are given):  $$$[1, 2, 3]$$$, $$$[4, 4]$$$ is not a good pair of teams because sizes should be the same;  $$$[1, 1, 2]$$$, $$$[3, 3, 3]$$$ is not a good pair of teams because the first team should not contain students with the same skills;  $$$[1, 2, 3]$$$, $$$[3, 4, 4]$$$ is not a good pair of teams because the second team should contain students with the same skills;  $$$[1, 2, 3]$$$, $$$[3, 3, 3]$$$ is a good pair of teams;  $$$[5]$$$, $$$[6]$$$ is a good pair of teams. Your task is to find the maximum possible size $$$x$$$ for which it is possible to compose a valid pair of teams, where each team size is $$$x$$$ (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the skill of the $$$i$$$-th student. Different students can have the same skills. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the maximum possible size $$$x$$$ for which it is possible to compose a valid pair of teams, where each team size is $$$x$$$.

NoteIn the first test case of the example, it is possible to construct two teams of size $$$3$$$: the first team is $$$[1, 2, 4]$$$ and the second team is $$$[4, 4, 4]$$$. Note, that there are some other ways to construct two valid teams of size $$$3$$$.

t = gets.chomp.to_i

(1..t).each{
    n = gets.chomp.to_i
    a = gets.chomp.split.map{|x| x.to_i}
    count = Hash.new 0
    a.each{|x|
        count[x] += 1;
    }

    max_diff = count.keys.size
    max_same = count.values.max

    if max_same == max_diff then
        puts (max_same - 1)
    else
        puts [max_same, max_diff].min
    end
}

1.upto(gets.to_i) do
  gets
  h = Hash.new { 0 }
  gets.split(' ').map(&:to_i).each { |x| h[x] += 1 }

  u = h.keys.size
  m = h.max_by(&:last).last

  puts [[u-1, m].min, [u, m-1].min].max
end

t=gets.to_i
(1).upto(t) do
  n=gets.to_i
  freq=Array.new(n+1,0)
  a=gets.split(' ').map(&:to_i)
  x=0
  y=0
  a.each do |e|
    freq[e]+=1
    y=[y,freq[e]].max
    x+=1 if freq[e]==1
  end
  if(y>x)
    puts x
  elsif y==x
    puts x-1
  else
    puts y
  end
end

t=gets.to_i
(1).upto(t) do
  n=gets.to_i
  freq=Array.new(n+1,0)
  a=gets.split(' ').map(&:to_i)
  x=0
  y=0
  a.each do |e|
    freq[e]+=1
    y=[y,freq[e]].max
    x+=1 if freq[e]==1
  end
  puts [y,x-1].min
end


On the way to school, Karen became fixated on the puzzle game on her phone!  The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!

The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500).

If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done:   row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row".  col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column".  If there are multiple optimal solutions, output any one of them.

NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level:  In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level:  Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3.

N, M = $stdin.gets.split.map(&:to_i)
mat = []
N.times {
  mat << $stdin.gets.split.map(&:to_i).to_a
}
@@swapped = 0
if N > M # apply transpose
  nmat = Array.new(M) { Array.new(N) }
  for i in 0...M
    for j in 0...N
      nmat[i][j] = mat[j][i]
    end
  end
  mat, nmat = nmat, mat
  N, M = M, N
  @@swapped = 1
end
ans = []
N.times { |i|
  x = mat[i].min
  x.times {
    ans << [["row", "col"][@@swapped], i + 1]
  }
  for j in 0...M
    mat[i][j] -= x
  end
}
M.times { |i|
  x = mat.map { |t| t[i] }.min
  x.times {
    ans << [["col", "row"][@@swapped], i + 1]
  }
  for j in 0...N
    mat[j][i] -= x
  end
}
(puts -1; exit) if mat.map { |t| t.max }.max > 0
puts ans.length
ans.length.times { |i|
  puts ans[i].join(' ')
}

N, M = $stdin.gets.split.map(&:to_i)
mat = []
N.times {
  mat << $stdin.gets.split.map(&:to_i).to_a
}
ans = []
N.times { |i|
  x = mat[i].min
  x.times {
    ans << ["row", i + 1]
  }
  for j in 0...M
    mat[i][j] -= x
  end
}
M.times { |i|
  x = mat.map { |t| t[i] }.min
  x.times {
    ans << ["col", i + 1]
  }
  for j in 0...N
    mat[j][i] -= x
  end
}
(puts -1; exit) if mat.map { |t| t.max }.max > 0
puts ans.length
ans.length.times { |i|
  puts ans[i].join(' ')
}

N, M = $stdin.gets.split.map(&:to_i)
mat = []
N.times {
  mat << $stdin.gets.split.map(&:to_i).to_a
}
if N > M # apply transpose
  nmat = Array.new(M) { Array.new(N) }
  for i in 0...M
    for j in 0...N
      nmat[i][j] = mat[j][i]
    end
  end
  mat, nmat = nmat, mat
  N, M = M, N
end
ans = []
N.times { |i|
  x = mat[i].min
  x.times {
    ans << ["row", i + 1]
  }
  for j in 0...M
    mat[i][j] -= x
  end
}
M.times { |i|
  x = mat.map { |t| t[i] }.min
  x.times {
    ans << ["col", i + 1]
  }
  for j in 0...N
    mat[j][i] -= x
  end
}
(puts -1; exit) if mat.map { |t| t.max }.max > 0
puts ans.length
ans.length.times { |i|
  puts ans[i].join(' ')
}


User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≤ k ≤ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak < bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≤ i, j ≤ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.

The first line contains an integer n (1 ≤ n ≤ 300) — the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn — the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≤ i < j ≤ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≤ i ≤ n, Ai, i = 0 holds.

In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.

NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4).   A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.

UF=Hash.new{|_,k|k}
def u a,b;UF[f a]=UF[f b]end
def f c;c==UF[c]?c:UF[c]=f(UF[c])end

n=gets.to_i
a=gets.split.map(&:to_i)
m=(1..n).map{gets.chomp.chars.map{|c|c>?0}}
r=0...n
r.each{|i|r.each{|j|
  u(i,j) if m[i][j]
}}
group=r.map{|i|f i}
g=a.group_by.with_index{|i,j|group[j]}
g.values.map(&:sort!)
puts r.map{|i|g[group[i]].shift}*" "

n = gets.to_i
ps = gets.split.map(&:to_i)
aij = []
n.times do |i|
  aij[i] = gets.split("").map(&:to_i)
end

ret = Array.new(n)
gs = []
gn = []
gi = 0
ni = 0
flags = Array.new(n){ |x| false }
while ni
  gs[gi] = []
  gn[gi] = []
  target = [ni]
  flags[ni] = true
  until target.size == 0 do
    x = target.pop
    gs[gi] << x
    gn[gi] << ps[x]
    aij[x].each_with_index do |y,j|
      if y==1 && !flags[j]
        target << j
        flags[j] = true
      end
    end
  end
  gs[gi].sort!
  gn[gi].sort!
  gs[gi].each_with_index do |x,i|
    ret[x] = gn[gi][i]
  end
  STDERR.puts "#{ni} #{ret.join(" ")}"
  ni = flags.index{ |x| x==false }
  gi += 1
end
puts ret.join(" ")

class DSU
	def initialize n
		@p = Array.new(n) { |i, v| v = i }
	end
	def find x
		return x if @p[x] == x
		@p[x] = find @p[x]
	end
	def merge a, b
		@p[find(a)] = find(b)
	end
	def query? a, b
		find(a) == find(b)
	end
end

n = gets.to_i
dsu = DSU.new n
p = gets.split.map { |x| x.to_i - 1 }
n.times do |i|
	s = gets.chomp
	n.times do |j|
		if s[j] == '1' and !dsu.query?(i, j)
			dsu.merge i, j
		end
	end
end

ans = Array.new n
n.times do |i|
	if dsu.find(i) == i
		a = []
		b = []
		n.times do |j|
			if dsu.find(j) == i
				a << j
				b << p[j]
			end
		end
		b.sort!
		a.size.times do |j|
			ans[a[j]] = b[j] + 1
		end
	end
end
puts ans.join ' '

n = gets.to_i
ps = gets.split.map(&:to_i)
aij = []
n.times do |i|
  aij[i] = gets.split("").map(&:to_i)
end

ret = Array.new(n)
gs = []
gn = []
gi = 0
ni = 0
flags = Array.new(n){ |x| false }
while ni < n
  gs[gi] = []
  gn[gi] = []
  target = [ni]
  flags[ni] = true
  ni += 1
  until target.size == 0 do
    x = target.pop
    gs[gi] << x
    gn[gi] << ps[x]
    aij[x].each_with_index do |y,j|
      if y==1 && !flags[j]
        target << j
        flags[j] = true
      end
    end
  end
  gs[gi].sort!
  gn[gi].sort!
  gs[gi].each_with_index do |x,i|
    ret[x] = gn[gi][i]
  end
  break if ni == n
  (ni...n).each do |x|
    ni = x
    break unless flags[x]
  end
  gi += 1
end
puts ret.join(" ")

n = gets.to_i
ps = gets.split.map(&:to_i)
aij = []
n.times do |i|
  aij[i] = gets.split("").map(&:to_i)
end

ret = Array.new(n)
gs = []
gn = []
gi = 0
ni = 0
flags = Array.new(n){ |x| false }
while ni < n
  gs[gi] = []
  gn[gi] = []
  target = [ni]
  flags[ni] = true
  ni += 1
  #break if ni == n
  until target.size == 0 do
    x = target.pop
    gs[gi] << x
    gn[gi] << ps[x]
    aij[x].each_with_index do |y,j|
      if y==1 && !flags[j]
        target << j
        flags[j] = true
      end
    end
  end
  gs[gi].sort!
  gn[gi].sort!
  gs[gi].each_with_index do |x,i|
    ret[x] = gn[gi][i]
  end
  (ni...n).each do |x|
    ni = x
    break unless flags[x]
  end
  gi += 1
end
puts ret.join(" ")

n = gets.to_i
ps = gets.split.map(&:to_i)
aij = []
n.times do |i|
  aij[i] = gets.split("").map(&:to_i)
end

ret = Array.new(n)
gs = []
gn = []
gi = 0
ni = 0
flags = Array.new(n){ |x| false }
while ni < n
  gs[gi] = []
  gn[gi] = []
  target = [ni]
  flags[ni] = true
  ni += 1
  break if ni == n
  until target.size == 0 do
    x = target.pop
    gs[gi] << x
    gn[gi] << ps[x]
    aij[x].each_with_index do |y,j|
      if y==1 && !flags[j]
        target << j
        flags[j] = true
      end
    end
  end
  gs[gi].sort!
  gn[gi].sort!
  gs[gi].each_with_index do |x,i|
    ret[x] = gn[gi][i]
  end
  (ni...n).each do |x|
    ni = x
    break unless flags[x]
  end
  gi += 1
end
puts ret.join(" ")


Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1, s2, ..., sn. All those strings consist of uppercase and lowercase Latin letters. String w has the length of |w|, its characters are numbered from 1 to |w|.First Petya should find all the occurrences of forbidden substrings in the w string. During the search of substrings the case of letter shouldn't be taken into consideration. That is, strings "aBC" and "ABc" are considered equal.After that Petya should perform the replacement of all letters covered by the occurrences. More formally: a letter in the position i should be replaced by any other one if for position i in string w there exist pair of indices l, r (1 ≤ l ≤ i ≤ r ≤ |w|) such that substring w[l ... r] is contained in the collection s1, s2, ..., sn, when using case insensitive comparison. During the replacement the letter's case should remain the same. Petya is not allowed to replace the letters that aren't covered by any forbidden substring.Letter letter (uppercase or lowercase) is considered lucky for the hockey players. That's why Petya should perform the changes so that the letter occurred in the resulting string as many times as possible. Help Petya to find such resulting string. If there are several such strings, find the one that comes first lexicographically.Note that the process of replacements is not repeated, it occurs only once. That is, if after Petya's replacements the string started to contain new occurrences of bad substrings, Petya pays no attention to them.

The first line contains the only integer n (1 ≤ n ≤ 100) — the number of forbidden substrings in the collection. Next n lines contain these substrings. The next line contains string w. All those n + 1 lines are non-empty strings consisting of uppercase and lowercase Latin letters whose length does not exceed 100. The last line contains a lowercase letter letter.

Output the only line — Petya's resulting string with the maximum number of letters letter. If there are several answers then output the one that comes first lexicographically. The lexicographical comparison is performed by the standard < operator in modern programming languages. The line a is lexicographically smaller than the line b, if a is a prefix of b, or there exists such an i (1 ≤ i ≤ |a|), that ai < bi, and for any j (1 ≤ j < i) aj = bj. |a| stands for the length of string a.

4
hello
party
abefglghjdhfgj
IVan
petrsmatchwin
a

#sharyo
def isupper(c)
    if (/[[:upper:]]/.match(c))
	return true
	end
 return false
end
n=gets.to_i
m=Hash.new
v=Array.new
for i in 0..n-1
   x=gets.chop
   y=""
  x.split('').each{|j|
   	y+=j.downcase
   }
   m[y]=true
end
a=gets.chop.split('')
b=a.join
n=b.length

b=b.split('')

for i in 0..n-1
a[i]=a[i].downcase
end
c=Array.new(n,false)

for i in 0..n-1
	x=""
	for j in i..n-1
		x+=a[j]
		if m[x]
			v.push([i,j])
		end
	end
end
v.each do |(x,y)|
	for j in x..y
		c[j]=true
	end
end
z=gets.chop
for i in 0..n-1
	next unless c[i]
	if z.downcase!=b[i].downcase
		if 	isupper(b[i])
			b[i]=z.upcase
		else
            b[i]=z
		end

	elsif b[i].downcase=='a'
        if isupper(b[i])
			b[i]='B'
		else
            b[i]='b'
		end

	else
		if 	isupper(b[i])
			b[i]='A'
		else
            b[i]='a'
		end
	end

end

print b.join

n = gets.to_i
ps = (1..n).map { |s| gets.strip }
t = gets.strip
c = gets.strip
x = [0] * t.size
(0...t.size).each do |i|
  ps.each do |s|
    x[i, s.size] = [1] * s.size if t[i, s.size].downcase == s.downcase
  end
end
x.size.times do |i|
  if x[i] == 1
    if t[i].downcase == c.downcase
      if t[i].downcase == t[i]
        t[i] = c == ?a || c == ?A ? ?b : ?a
      else
        t[i] = c == ?a || c == ?A ? ?B : ?A
      end
    else
      if t[i].downcase == t[i]
        t[i] = c
      else
        t[i] = c.upcase
      end
    end
  end
end
puts t

n = gets.chomp.to_i
ss = Array.new(n)
for i in 1..n
  ss[i-1] = gets.chomp.upcase
end
s0 = gets.chomp
c = gets.chomp
s = s0.upcase
ii = Array.new(s.length).map!{|x| false}
for i in 1..n
  previdx = 0
  while true
    wkidx = s.index(ss[i-1], previdx)
    if wkidx != nil then
      for j in 0..ss[i-1].length-1
        ii[wkidx+j] = true
      end
    else
      break
    end
    previdx = wkidx+1
  end
end

c2 = c.upcase
for i in 0..s0.length-1
  next if ii[i] == false
  wkup = false
  wkup = true if s0[i] == s[i]
  wk = c
  if s[i] == c2 then
    if c == "a" then
      wk = "b"
    else
      wk = "a"
    end
  end
  wk = wk.upcase if wkup
  s0[i] = wk
end
puts s0

fw = []
gets.to_i.times do
  fw << gets.strip.downcase
end
ret = gets.strip
str = ret.downcase
letter = gets.strip
fw.each do |w|
  pos = 0
  while i = str.index(w, pos)
    (i...(i + w.size)).each do |n|
      if str[n] == letter
        if str[n] == 'a'
          c = 'b'
        else
          c = 'a'
        end
      else
        c = letter
      end
      ret[n] = ret[n] == ret[n].upcase ? c.upcase : c
    end
    pos += 1
  end
end
puts ret

def optimal_letter(ch,l)
	return(ch<?a ? l.upcase : l) if ch.downcase!=l
	case ch
		when ?a then ?b
		when ?A then ?B
		when ?b..?z then ?a
		else ?A
	end
end

s=1.upto(gets.to_i).map{gets.upcase.chomp}
w,l=gets.chomp,gets.chomp
up_w=w.upcase
replace_flag=[false]*w.size
s.uniq.each{|str|
	size=str.size
	0.upto(w.size-size).map{|idx|up_w.index(str,idx)}.uniq.compact.each{|idx|
		replace_flag[idx...idx+size]=[true]*size
	}
}
w.size.times{|i|print replace_flag[i] ? optimal_letter(w[i],l) : w[i]}

#sharyo
def isupper(c)
    if (/[[:upper:]]/.match(c))
	return true
	end
 return false
end
n=gets.to_i
m=Hash.new
v=Array.new
for i in 0..n-1
   x=gets.chop
   y=""
  x.split('').each{|j|
   	y+=j.downcase
   }
   m[y]=true
end
a=gets.chop.split('')
b=a.join
n=b.length

b=b.split('')

for i in 0..n-1
a[i]=a[i].downcase
end
c=Array.new(n,false)

for i in 0..n-1
	x=""
	for j in i..n-1
		x+=a[j]
		if m[x]
			v.push([i,j])
		end
	end
end
v.each do |(x,y)|
	for j in x..y
		c[j]=true
	end
end
z=gets.chop
for i in 0..n-1
	next unless c[i]
	if z.downcase!=b[i]
		if 	isupper(b[i])
			b[i]=z.upcase
		else
            b[i]=z
		end

	elsif b[i].downcase=='a'
        if isupper(b[i])
			b[i]='B'
		else
            b[i]='b'
		end

	else
		if 	isupper(b[i])
			b[i]='A'
		else
            b[i]='a'
		end
	end

end

print b.join

begin
n = gets.to_i
ps = (1..n).map { |s| gets.strip }
t = gets.strip
c = gets.strip
x = [0] * t.size
(0...t.size).each do |i|
  ps.each do |s|
    x[i, s.size] = [1] * s.size if t[i, s.size].downcase == s.downcase
  end
end
x.size.times do |i|
  if x[i] == 1
    if t[i] == c
      t[i] = c == ?a ? ?b : ?a
    else
      if /[a-z]/.match?(t[i])
        t[i] = c
      else
        t[i] = c.upcase
      end
    end
  end
end
puts t
rescue => e
  puts e
end

begin
n = gets.to_i
ps = (1..n).map { |s| gets.strip }
t = gets.strip
c = gets.strip
x = [0] * t.size
(0...t.size).each do |i|
  ps.each do |s|
    x[i, s.size] = [1] * s.size if t[i, s.size].downcase == s.downcase
  end
x.size.times do |i|
  if x[i] == 1
    if t[i] == c
      t[i] = c == ?a ? ?b : ?a
    else
      if t[i].match?(/[a-z]/)
        t[i] = c
      else
        t[i] = c.upcase
      end
    end
  end
end
puts t
end
rescue => e
  puts e
end

n = gets.to_i
ps = (1..n).map { |s| gets.strip }
t = gets.strip
c = gets.strip
x = [0] * t.size
(0...t.size).each do |i|
  ps.each do |s|
    x[i, s.size] = [1] * s.size if t[i, s.size].downcase == s.downcase
  end
end
x.size.times do |i|
  if x[i] == 1
    if t[i] == c
      t[i] = c == ?a ? ?b : ?a
    else
      if t[i].downcase == t[i]
        t[i] = c
      else
        t[i] = c.upcase
      end
    end
  end
end
puts t

def optimal_letter(ch,l)
	return(ch<?a ? l.upcase : l) if ch.downcase!=l
	case ch
		when ?a then ?b
		when ?A then ?B
		when ?b..?z then ?a
		else ?A
	end
end
AST=?*.ord
gets
forbidden_substrings=gets(nil).split
letter,w=2.times.map{forbidden_substrings.pop}
replace_flag=forbidden_substrings.map{|str|w.gsub(/#{str}/i,?**str.size).bytes.to_a}.transpose.map{|bytes|bytes.any?{|b|b==AST}}
w.size.times{|i|print replace_flag[i] ? optimal_letter(w[i],letter) : w[i]}

fw = []
gets.to_i.times do
  fw << gets.strip.downcase
end
ret = gets.strip
str = ret.downcase
letter = gets.strip
fw.each do |w|
  if i = str.index(w)
    (i...(i + w.size)).each do |n|
      if str[n] == letter
        if str[n] == 'a'
          c = 'b'
        else
          c = 'a'
        end
      else
        c = letter
      end
      ret[n] = ret[n] == ret[n].upcase ? c.upcase : c
    end
  end
end
puts ret

fw = []
gets.to_i.times do
  fw << gets.strip.downcase
end
ret = gets.strip
str = ret.downcase
letter = gets.strip
fw.each do |w|
  pos = 0
  while i = str.index(w, pos)
    (i...(i + w.size)).each do |n|
      if str[n] == letter
        if str[n] == 'a'
          c = 'b'
        else
          c = 'a'
        end
      else
        c = letter
      end
      ret[n] = ret[n] == ret[n].upcase ? c.upcase : c
    end
    pos += w.size
  end
end
puts ret


When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a $$$2 \times n$$$ grid where each row is a permutation of the numbers $$$1,2,3,\ldots,n$$$.The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column.Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo $$$10^9+7$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 4 \cdot 10^5$$$). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers $$$1,2,3,\ldots,n$$$ and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$.

For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo $$$10^9+7$$$. The answer for each test case should be on a separate line.

NoteThe two possible puzzle configurations for example $$$1$$$ are:  $$$[1,4,2,3]$$$ in the first row and $$$[3,2,1,4]$$$ in the second;  $$$[3,2,1,4]$$$ in the first row and $$$[1,4,2,3]$$$ in the second.

gets.to_s.to_i.times do
  n = gets.to_s.to_i
  a = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  b = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  c = a.zip(b).sort {|x, y| x[0] <=> y[0] }.map {|x| x[1] }
  result = 1
  c.each_with_index do |ci, i|
    next if ci < 0
    result = (result * 2) % 1000000007
    j = i
    c[j], j = -1, c[j] until j < 0
  end
  puts result
end

gets.to_s.to_i.times do
  n = gets.to_s.to_i
  a = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  b = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  c = a.zip(b).sort {|x, y| x[0] <=> y[0] }
  visited = [false] * c.size
  result = 1
  c.each_index do |i|
    result = (result * 2) % 1000000007 unless visited[i]
    j = i
    while !visited[j]
      visited[j] = true
      j = c[j][1]
    end
  end
  puts result
end

gets.to_s.to_i.times do
  n = gets.to_s.to_i
  a = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  b = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  c = a.zip(b).sort {|x, y| x[0] <=> y[0] }
  visited = [false] * c.size
  result = 0
  c.each_index do |i|
    result += 1 unless visited[i]
    j = i
    while !visited[j]
      visited[j] = true
      j = c[j][1]
    end
  end
  puts 2.pow(result, 1000000007)
end


A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:  Employee A is the immediate manager of employee B  Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?

The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.  It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.

Print a single integer denoting the minimum number of groups that will be formed in the party.

NoteFor the first example, three groups are sufficient, for example:   Employee 1  Employees 2 and 4  Employees 3 and 5

a = $<.read.split.map(&:to_i)
p (1.upto(a[0]).map do |i|
  c = 1
  c += 1 while (i = a[i]) != -1
  c
end.max)

# coding: utf-8

# if __FILE__ == $0
# end

# 5
# -1 : 1번 사원의 상사는 없음
# 1  : 2번 사원의 상사는 1번임
# 2  : 3번 사원의 상사는 2번임
# 1  : 4번 사원의 상사는 1번임
# -1 : 5번 사원의 상사는 없음
# transitive를 허용하지 않음(2의 상사는 3인데, 3의 상사는 1이면 2-1은 같이 있을 수 없다)

# 이거 LCA (Lowest Common Ancestor) 문제로 접근하면 간단하고,
# 그림을 적어도 한번은 그려보길 권함
# depth마다 수평하게 잘라내면 어떤 상사도 겹치지 않는다.
# 즉, 최고 depth의 수는 만들 수 있는 적절한 그룹의 수가 된다.

n = gets.to_i
ee = []
n.times {
    ee << gets.to_i - 1 # -1 -> -2
}
map = {}
groups_max = 0
for i in 0...n
    map[i] = []
    j = i
    loop do
        sup = ee[j]
        if sup < 0
            break
        else
            map[i] << sup
            j = sup
        end
    end

    if map[i].length > groups_max
        groups_max = map[i].length
    end
end

puts groups_max + 1 # value excludes itself

n = gets.to_i
mg = n.times.map{gets.to_i}
mx = 0
n.times do |i|
  m = i
  cnt = 1
  n.times do
    if mg[m] == -1
      mx = [cnt, mx].max
      break
    end
    m = mg[m] - 1
    cnt += 1
  end
end
puts mx

n = gets.to_i
mg = [nil] + n.times.map{gets.to_i}
$e = Array.new(n + 1){Array.new}
1.upto(n){|i| $e[[0, mg[i]].max] << i}
$cnt = []

def dfs(u, lv)
  $cnt[u] = lv
  $e[u].each do |v|
    dfs(v, lv + 1)
  end
end

dfs(0, 0)
puts $cnt.max

def dep(v)
  result = 1
  pos = v
  while pos > 0
    result += 1
    pos = $a[pos]
  end

  result
end

n = gets.to_i

$a = (1..n).map { gets.to_i }
$a.unshift 0
puts $a.map { |x| dep(x) }.max

# 115A

a = (0...gets.to_i).map { gets.to_i - 1 }
max = 1
a.each { |x|
  len = 1
  while x != -2
    x = a[x]
    len += 1
  end
  max = len if len > max
}
puts max

# The following O(n) solution works on my machine but fails on codeforces with RUNTIME_ERROR
=begin
class Node
  attr_accessor :parent
  attr_reader :children

  def initialize()
    @children = []
  end

  def len
    @children.size > 0 ? @children.map(&:len).max + 1 : 1
  end
end

n = gets.to_i
nodes = Array.new(n)
n.times { |i|
  p = gets.to_i - 1
  node = nodes[i] || Node.new
  if p >= 0
    parent = nodes[p] || Node.new
    node.parent = parent
    parent.children << node
    nodes[p] = parent
  end
  nodes[i] = node
}

puts nodes.select { |node| node.parent.nil? }.map(&:len).max
=end

n=gets.to_i
g=Array.new(n+1)
(1).upto(n) {|i| g[i]=[]}
q=Queue.new
(1).upto(n) do |i|
  p=gets.to_i
  g[p].push(i) if(p!=-1)
  q.push([i,1]) if(p==-1)
end
mx=0
while !(q.empty?) do
  cur = q.pop
  mx=cur[1]
  g[cur[0]].each do |node|
    q.push([node,mx+1])
  end
end
puts mx

n = gets.to_i
e = Array.new(n) { [] }
roots = []
n.times {|i|
  j = gets.to_i
  if j == -1
    roots << i
  else
    e[j-1] << i
  end
}

def depth(i, e)
  return 1 if e[i].empty?
  e[i].map{|c| depth(c, e)}.max + 1
end

puts roots.map{|r| depth(r, e)}.max

n = gets.chomp.to_i
maxlevel = 0
a = Array.new(n)
for i in 0..n-1
  a[i] = gets.chomp.to_i
end
for i in 0..n-1
  lvl = 1
  j = i
  while a[j] != -1
    j = a[j]-1
    lvl += 1
  end
  maxlevel = lvl if maxlevel < lvl
end
puts maxlevel

n = gets.strip.to_i

pairs = []
rank = Array.new(n,0)
n.times do |i|
	man = gets.strip.to_i
	if man ==-1
		rank[i] = 1
	else
		pairs << [man, i+1]
	end
end

while rank.include? 0
	pairs.each do |v|
		u,l = v
		next if rank[l-1]!=0

		surank = rank[u-1]
		if surank!=0
			rank[l-1] = surank+1
		end
	end
end

puts rank.max

num = 0
answer = 0
employees = []

while line = STDIN.gets
  count = 0
  num += 1
  if (/exit/ =~ line)
    break;
  elsif (num == 1)
    line = line.chomp.to_i
    employee_count = line
  else
    employees.push([nil, line = line.chomp.to_i])
  end
end

employees.each do |employee|
  count = 0
  employee_tmp = employee
  while true
    count += 1
    if employee_tmp[1] == -1
      break
    else
      employee_tmp = employees[employee_tmp[1]-1]
    end
  end
  if count > answer
    answer = count
  end
end
STDOUT.puts answer

n = gets.chomp.to_i
h = Hash.new

1.upto(n).each do |i|
	v = gets.chomp.to_i
	h[v] ||= []
	h[v] << i
end

# p h
visited = Hash.new
-1.upto(n) do |i|
	next if h[i].nil? || !visited[i].nil?
	visited[i] = 0
	q = Queue.new
	q.push(i)
	while(!q.empty?)
		f = q.pop
		h[f].each do |x|
			if visited[x].nil?
				visited[x] = visited[f] + 1
				if !h[x].nil?
					q.push(x)
				end
			end
		end
	end
end

# print visited
print visited.values.max

def solve(x)
        if $p[x]<0 then
                return 0
        end
        if $dp[x]>=0 then
                return $dp[x]
        end
        return $dp[x]=solve($p[x])+1
end
n=gets.to_i
$p=[]
n.times{|i|
        $p.push(gets.to_i-1)
}
$dp=Array.new(n,-1)
ans=0
n.times{|i|
        ans=[ans,solve(i)].max
}
p ans+1

class List
  attr_accessor :element, :next_elem

  def initialize(element, next_elem)
    @element = element
    @next_elem = next_elem
  end
end

class Graph
  attr_accessor :vertices

  def initialize(vertices)
    @vertices = vertices
  end

  def add_edge(index1, index2)
    if vertices[index1].nil? then
      vertices[index1] = List.new(index2, nil)
    else
      vert = List.new(index2, vertices[index1])
      vertices[index1] = List.new(index2, vertices[index1])
    end
  end

  def print_edges
    vertices.each_with_index do |vertex, index|
      while !vertex.nil? do
        # puts "edge #{index} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end
end

def depth(graph, index)
  return 1 if graph.vertices[index].nil?
  max_depth = depth(graph, graph.vertices[index].element)
  next_vertex = graph.vertices[index].next_elem
  while !next_vertex.nil? do
    current_max_depth = depth(graph, next_vertex.element)
    max_depth = [max_depth, current_max_depth].max
    next_vertex = next_vertex.next_elem
  end
  return max_depth + 1
end

employees = Graph.new([])
root_managers = []
n = gets.strip.to_i
n.times do |i|
  manager = gets.strip.to_i
  if manager == -1 then
    root_managers.push(i)
  else
    employees.add_edge(manager - 1, i)
  end
end
employees.print_edges
# puts "root managerts: #{root_managers.join(" ")}"
max_depth = 1
root_managers.each do |i|
  if !employees.vertices[i].nil?
    max_depth = [depth(employees, i), max_depth].max
  end
end
puts max_depth

a=gets.chomp.to_i
ar=[]
a.times do
ar << gets.chomp.to_i
end
max=0
0.upto(a-1) do |i|
temp=1
k=ar[i]
loop do
break if k==-1
k=ar[k-1]
temp+=1
end
if temp >max
max=temp
end
end
puts "#{max}"

n=gets.to_i
a=(0..n).map{[]}
b=[]

n.times{|i|
	e=i+1
	e2=gets.to_i
	a[e2]<<e if e2!=-1
	b<<e if e2==-1
}
ans=1
while true
	b2=[]
	while !b.empty?
		no=b.shift
		a[no].each{|no2|
			b2<<no2
		}
	end
	break if b2.empty?
	b2.each{|e|
		b<<e
	}
	ans=ans+1
end
puts ans

# coding: utf-8

# if __FILE__ == $0
# end

# 5
# -1 : 1번 사원의 상사는 없음
# 1  : 2번 사원의 상사는 1번임
# 2  : 3번 사원의 상사는 2번임
# 1  : 4번 사원의 상사는 1번임
# -1 : 5번 사원의 상사는 없음
# transitive를 허용하지 않음(2의 상사는 3인데, 3의 상사는 1이면 2-1은 같이 있을 수 없다)

n = gets.to_i
ee = []
LOCATED = 2001
n.times {
    ee << gets.to_i - 1 # -1 -> -2
}
groups = 0
i = 0
# p ee
while ee.count(LOCATED) < n
    forming = []
    forming << i

    loop do
        i += 1
        break if i >= n

        if ee[i] == LOCATED
            next
        else
            sup_resides_in_forming = false
            j = i
            while j < ee.length
                if ee[j] == LOCATED || ee[j] < 0
                    # safely append it
                    break
                elsif forming.include?(ee[j])
                    sup_resides_in_forming = true
                    break
                else
                    j = ee[j]
                end
            end

            unless sup_resides_in_forming
                forming << i
            end
        end
    end

    # p forming
    unless forming.empty?
        # if reaches end, group them and clear
        forming.each { |idx|
            ee[idx] = LOCATED
        }
        groups += 1
        forming.clear
    end

    # p ee
    ni = ee.index { |x| x != LOCATED }
    if ni == nil
        # p "--- #{ni}"
        break
    else
        i = ni
    end
end

puts groups

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
ee = []
n.times {
    ee << gets.to_i
}

ee.sort!
prev = nil
bcounter = 0
ee.each { |i|
    if prev != i
        bcounter += 1
        prev = i
    end
}

puts bcounter

# coding: utf-8

# if __FILE__ == $0
# end

# 5
# -1 : 1번 사원의 상사는 없음
# 1  : 2번 사원의 상사는 1번임
# 2  : 3번 사원의 상사는 2번임
# 1  : 4번 사원의 상사는 1번임
# -1 : 5번 사원의 상사는 없음
# transitive를 허용하지 않음(2의 상사는 3인데, 3의 상사는 1이면 2-1은 같이 있을 수 없다)

n = gets.to_i
ee = []
LOCATED = 2001
n.times {
    ee << gets.to_i - 1 # -1 -> -2
}
groups = 0
i = 0
# p ee
while ee.count(LOCATED) < n
    forming = []
    forming << i

    loop do
        i += 1
        break if i >= n

        if ee[i] == LOCATED
            next
        else
            sup_resides_in_forming = false
            j = i
            while j < ee.length && !sup_resides_in_forming
                if ee[j] == LOCATED
                    # safely append it
                    break
                elsif ee[j] < 0
                    # check him/herself is a superior from someone
                    for idx in forming
                        sup = ee[idx]
                        if sup == j
                            sup_resides_in_forming = true
                            break
                        end
                    end

                    break
                elsif forming.include?(ee[j])
                    sup_resides_in_forming = true
                    break
                else
                    j = ee[j]
                end
            end

            unless sup_resides_in_forming
                forming << i
            end
        end
    end

    # p forming
    unless forming.empty?
        # if reaches end, group them and clear
        forming.each { |idx|
            ee[idx] = LOCATED
        }
        groups += 1
        forming.clear
    end

    # p ee
    ni = ee.index { |x| x != LOCATED }
    if ni == nil
        # p "--- #{ni}"
        break
    else
        i = ni
    end
end

puts groups

n = gets.to_i
h = Hash.new(0)
n.times do
  i = gets.to_i
  h[i] += 1 if i != -1
end
p h.values.max + 1

n = gets.to_i

puts 1 + (1..n).count { gets.to_i == -1 }

# 115A

class Node
  attr_accessor :parent
  attr_reader :children

  def initialize()
    @children = []
  end

  def len
    @children.size > 0 ? @children.map(&:len).max + 1 : 1
  end
end

n = gets.to_i
nodes = Array.new(n)
n.times { |i|
  p = gets.to_i - 1
  node = nodes[i] || Node.new
  if p >= 0
    parent = nodes[p] || Node.new
    node.parent = parent
    parent.children << node
    nodes[p] = parent
  end
  nodes[i] = node
  if i >= 90
    puts p
  end
}

puts nodes.select { |node| node.parent.nil? }.map(&:len).max

n = gets.chomp.to_i
h = Hash.new

1.upto(n).each do |i|
	v = gets.chomp.to_i
	h[v] ||= []
	h[v] << i
end

# p h
visited = Hash.new
if !h[-1].nil?
	visited[-1] = 1
end

1.upto(n) do |i|
	next if h[i].nil? || !visited[i].nil?
	visited[i] = 1
	q = Queue.new
	q.push(i)
	while(!q.empty?)
		f = q.pop
		h[f].each do |x|
			if visited[x].nil?
				visited[x] = visited[f] + 1
				if !h[x].nil?
					q.push(x)
				end
			end
		end
	end
end

print visited.values.max

n = gets.chomp.to_i
h = Hash.new

1.upto(n).each do |i|
	v = gets.chomp.to_i
	h[v] ||= []
	h[v] << i
end

# p h
ac = 0
if !h[-1].nil?
	ac += 1
end

visited = Hash.new

1.upto(n) do |i|
	next if h[i].nil? || !visited[i].nil?
	visited[i] = 1
	q = Queue.new
	q.push(i)
	while(!q.empty?)
		f = q.pop
		next if h[f].nil?

		h[f].each do |x|
			if visited[x].nil?
				visited[x] = visited[f] + 1
				ac = [ac, visited[x]].max
				q.push(x)
			end
		end
	end
end

print ac

class List
  attr_accessor :element, :next_elem

  def initialize(element, next_elem)
    @element = element
    @next_elem = next_elem
  end
end

class Graph
  attr_accessor :vertices

  def initialize(vertices)
    @vertices = vertices
  end

  def add_edge(index1, index2)
    if vertices[index1].nil? then
      vertices[index1] = List.new(index2, nil)
    else
      vert = List.new(index2, vertices[index1])
      vertices[index1] = List.new(index2, vertices[index1])
    end
  end

  def print_edges
    vertices.each_with_index do |vertex, index|
      while !vertex.nil? do
        # puts "edge #{index} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end
end

def depth(graph, index)
  return 1 if graph.vertices[index].nil?
  max_depth = depth(graph, graph.vertices[index].element)
  next_vertex = graph.vertices[index].next_elem
  while !next_vertex.nil? do
    current_max_depth = depth(graph, next_vertex.element)
    max_depth = [max_depth, current_max_depth].max
    next_vertex = next_vertex.next_elem
  end
  return max_depth + 1
end

employees = Graph.new([])
root_managers = []
n = gets.strip.to_i
n.times do |i|
  manager = gets.strip.to_i
  if manager == -1 then
    root_managers.push(i)
  else
    employees.add_edge(manager - 1, i)
  end
end
employees.print_edges
# puts "root managerts: #{root_managers.join(" ")}"
max_depth = 0
root_managers.each do |i|
  current_depth = 0
  if !employees.vertices[i].nil?
    max_depth = [depth(employees, i), max_depth].max
  end
end
puts max_depth


Let $$$f(i)$$$ denote the minimum positive integer $$$x$$$ such that $$$x$$$ is not a divisor of $$$i$$$.Compute $$$\sum_{i=1}^n f(i)$$$ modulo $$$10^9+7$$$. In other words, compute $$$f(1)+f(2)+\dots+f(n)$$$ modulo $$$10^9+7$$$.

The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 10^4$$$), the number of test cases. Then $$$t$$$ cases follow. The only line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq 10^{16}$$$).

For each test case, output a single integer $$$ans$$$, where $$$ans=\sum_{i=1}^n f(i)$$$ modulo $$$10^9+7$$$.

NoteIn the fourth test case $$$n=4$$$, so $$$ans=f(1)+f(2)+f(3)+f(4)$$$.  $$$1$$$ is a divisor of $$$1$$$ but $$$2$$$ isn't, so $$$2$$$ is the minimum positive integer that isn't a divisor of $$$1$$$. Thus, $$$f(1)=2$$$.  $$$1$$$ and $$$2$$$ are divisors of $$$2$$$ but $$$3$$$ isn't, so $$$3$$$ is the minimum positive integer that isn't a divisor of $$$2$$$. Thus, $$$f(2)=3$$$.  $$$1$$$ is a divisor of $$$3$$$ but $$$2$$$ isn't, so $$$2$$$ is the minimum positive integer that isn't a divisor of $$$3$$$. Thus, $$$f(3)=2$$$.  $$$1$$$ and $$$2$$$ are divisors of $$$4$$$ but $$$3$$$ isn't, so $$$3$$$ is the minimum positive integer that isn't a divisor of $$$4$$$. Thus, $$$f(4)=3$$$. Therefore, $$$ans=f(1)+f(2)+f(3)+f(4)=2+3+2+3=10$$$.

t = gets.to_i
(1..t).each do
  n = gets.to_i
  s = 0
  p = 1
  i = 2
  while n > 0
    d = i / p.gcd(i)
    s += i * (n - n / d)
    n /= d
    p *= d
    i += 1
  end
  puts s % (10 ** 9 + 7)
end


You and your friend are participating in a TV show "Run For Your Prize".At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.What is the minimum number of seconds it will take to pick up all the prizes?

The first line contains one integer n (1 ≤ n ≤ 105) — the number of prizes. The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 106 - 1) — the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.

Print one integer — the minimum number of seconds it will take to collect all prizes.

NoteIn the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5.

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

for i in 1..num do
    if prizes[i - 1] < 500001
        prizes[i - 1] = (500000 - prizes[i - 1]).abs
    else
        prizes[i - 1] = (500001 - prizes[i - 1]).abs
    end
end

prizes = prizes.sort{ |x, y| y <=> x }

puts 499999 - prizes[num - 1]

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

for i in 1..num do
    if prizes[i - 1] < 500001
        prizes[i - 1] = (500000 - prizes[i - 1]).abs
    else
        prizes[i - 1] = (500001 - prizes[i - 1]).abs
    end
end

prizes.sort{ |x, y| x <=> y }

puts 499999 - prizes[num - 1]

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

for i in 1..num do
    if prizes[i - 1] <= 500000
        prizes[i - 1] = (500000 - prizes[i - 1]).abs
    else
        prizes[i - 1] = (500001 - prizes[i - 1]).abs
    end
end

prizes.sort{ |x, y| x <=> y }

puts 499999 - prizes[num - 1]

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

for i in 1..num do
    prizes[i - 1] -= 500000
    prizes[i - 1] = 500000 - prizes[i - 1].abs
end

prizes.sort{ |x, y| x <=> y }

puts prizes[num - 1] - 1

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

for i in 1..num do
    if prizes[i - 1] < 500001
        prizes[i - 1] = (500000 - prizes[i - 1]).abs
    else
        prizes[i - 1] = (500001 - prizes[i - 1]).abs
        puts prizes[i - 1]
    end
end

prizes.sort{ |x, y| x <=> y }

puts 499999 - prizes[num - 1]

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

for i in 1..num do
    prizes[i - 1] -= 500000.5
    prizes[i - 1] = 500000.5 - prizes[i - 1].abs
end

prizes.sort{ |x, y| x <=> y }

puts (prizes[num - 1] - 1).to_i


A piece of paper contains an array of n integers a1, a2, ..., an. Your task is to find a number that occurs the maximum number of times in this array.However, before looking for such number, you are allowed to perform not more than k following operations — choose an arbitrary element from the array and add 1 to it. In other words, you are allowed to increase some array element by 1 no more than k times (you are allowed to increase the same element of the array multiple times).Your task is to find the maximum number of occurrences of some number in the array after performing no more than k allowed operations. If there are several such numbers, your task is to find the minimum one.

The first line contains two integers n and k (1 ≤ n ≤ 105; 0 ≤ k ≤ 109) — the number of elements in the array and the number of operations you are allowed to perform, correspondingly. The third line contains a sequence of n integers a1, a2, ..., an (|ai| ≤ 109) — the initial array. The numbers in the lines are separated by single spaces.

In a single line print two numbers — the maximum number of occurrences of some number in the array after at most k allowed operations are performed, and the minimum number that reaches the given maximum. Separate the printed numbers by whitespaces.

NoteIn the first sample your task is to increase the second element of the array once and increase the fifth element of the array twice. Thus, we get sequence 6, 4, 4, 0, 4, where number 4 occurs 3 times.In the second sample you don't need to perform a single operation or increase each element by one. If we do nothing, we get array 5, 5, 5, if we increase each by one, we get 6, 6, 6. In both cases the maximum number of occurrences equals 3. So we should do nothing, as number 5 is less than number 6.In the third sample we should increase the second array element once and the fifth element once. Thus, we get sequence 3, 2, 2, 2, 2, where number 2 occurs 4 times.

#!/usr/bin/ruby

n, k = STDIN.readline.split.map {|s| s.to_i }
arr = STDIN.readline.split.map {|s| s.to_i }.sort
sums = [0]
sum = 0
arr.each {|x| sums.push(sum += x) }
best_count, best_value = 1, arr[0]
pos = 0
(1..n-1).each do |i|
	while true
		count = i-pos+1
		need = count*arr[i] - sums[i+1] + sums[pos]
		if need <= k
			if count > best_count
				best_count = count
				best_value = arr[i]
			end
			break
		end
		pos += 1
	end
end
puts '%d %d' % [best_count, best_value]

#!/usr/bin/ruby

n, k = STDIN.readline.split.map {|s| s.to_i }
arr = STDIN.readline.split.map {|s| s.to_i }.sort
sums = [0]
sum = 0
arr.each {|x| sums.push(sum += x) }
best_count, best_value = -1, -1
n.times do |i|
	low, high = 0, i
	while low != high
		pos = (low+high)/2
		width = i-pos+1
		need = width*arr[i] - sums[i+1] + sums[pos]
		if need > k
			low = pos+1
		else
			high = pos
		end
	end
	count = i-low+1
	if count > best_count
		best_count = count
		best_value = arr[i]
	end
end
puts '%d %d' % [best_count, best_value]