Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).Help Daniel to process all queries.

The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries. The second line contains string s, consisting of n lowercase English letters and period signs. The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.

Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.

NoteNote to the first sample test (replaced periods are enclosed in square brackets).The original string is ".b..bz....". after the first query f(hb..bz....) = 4    ("hb[..]bz...."  →  "hb.bz[..].."  →  "hb.bz[..]."  →  "hb.bz[..]"  →  "hb.bz.") after the second query f(hbс.bz....) = 3    ("hbс.bz[..].."  →  "hbс.bz[..]."  →  "hbс.bz[..]"  →  "hbс.bz.") after the third query f(hbс.bz..f.) = 1    ("hbс.bz[..]f."  →  "hbс.bz.f.")Note to the second sample test.The original string is ".cc.". after the first query: f(..c.) = 1    ("[..]c."  →  ".c.") after the second query: f(....) = 3    ("[..].."  →  "[..]."  →  "[..]"  →  ".") after the third query: f(.a..) = 1    (".a[..]"  →  ".a.") after the fourth query: f(aa..) = 1    ("aa[..]"  →  "aa.")

n,q = gets.chomp.split.map{|x| x.to_i}

str = gets.chomp
prev = str[0]
total = 0
(1..n-1).each do |i|
	curr = str[i]
	if prev == curr and prev == '.'
		total+=1
	end
	prev = curr
end

q.times do
	i,c = gets.chomp.split
	i = (i.to_i)-1

	if c == '.'
		if str[i] != '.'
				if i > 0 and i < n-1

				total+=1 if str[i-1] == '.'
				total+=1 if str[i+1] == '.'
				elsif i==0 and i+1<n  and str[i+1] == '.'
				total+=1
				elsif i==n-1 and i-1>=0 and str[i-1] == '.'
				total+=1
				end
		end
	else
		if str[i] == '.'
			if i > 0 and i < n-1
				total-=1 if str[i-1] == '.'
				total-=1 if str[i+1] == '.'
			elsif i==0 and i+1<n  and str[i+1] == '.'
				total-=1
			elsif i==n-1 and i-1>=0 and str[i-1] == '.'
				total-=1
			end
		end

	end
	str[i] = c
	puts total
end

#!/usr/bin/ruby

def solution(n, m, s, narr, carr)
  count = 0
  prev_char = nil
  s.each_char do |char|
    count+=1 if char == '.' && prev_char == '.'
    prev_char = char
  end
  m.times do |t|
    i = narr[t]
    char = carr[t]
    if (char == '.') ^ (s[i] == '.')
      if char == '.'
        count+=1 if i > 0 && s[i-1] == '.'
        count+=1 if i+1 < n && s[i+1] == '.'
      else
        count-=1 if i > 0 && s[i-1] == '.'
        count-=1 if i+1 < n && s[i+1] == '.'
      end
      s[i] = char
    end
    puts count
  end
end

n, m = gets.split(' ').map{|s|s.to_i}
s = gets
narr = []
carr = []
m.times{
  i, c = gets.split(' ')
  narr.push i.to_i - 1
  carr.push c
}
solution n, m, s, narr, carr

# solution 10, 3, '.b..bz....', [0, 2, 8], %w(h c f)
# solution 4, 4, '.cc.', [1, 2, 1, 0], %w(. . a a)
# solution 4,3
# solution 3,2
# solution 3,1
# solution 3,3
# solution 2,1
# solution 2,2
#
# #
# # solution 4, [75, 150, 75, 50]
# # solution 3, [100, 150, 250]

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

s=?a+gets.chomp+?a
groups=s.scan(/\.+/).size
dots=s.count ?.
b=s.bytes.map{|c|c<90}

res=[]
queries=$<.read.split
m.times{|i|
    x=queries[2*i].to_i
    c=queries[2*i+1]
    if b[x] and c!=?.
        dots-=1
        if !b[x-1] and !b[x+1]
            groups-=1
        elsif b[x-1] and b[x+1]
            groups+=1
        end
        b[x]=false
    elsif !b[x] and c==?.
        dots+=1
        if !b[x-1] and !b[x+1]
            groups+=1
        elsif b[x-1] and b[x+1]
            groups-=1
        end
        b[x]=true
    end
    res<<dots-groups
}
puts res

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

# s=?a+gets.chomp+?a
s=?a
s<<gets.chomp
s<<?a

#groups=s.scan(/\.+/).size
#dots=s.count ?.
dots=groups=0
b=[]
for i in 1..n+1
    if s[i]==?.
        dots+=1
        b[i]=true
    else
        groups+=1 if s[i-1]==?.
    end
end

res=[]
queries=$<.read.split
m.times{|i|
    x=queries[2*i].to_i
    c=queries[2*i+1]
    if b[x] and c!=?.
        dots-=1
        if !b[x-1] and !b[x+1]
            groups-=1
        elsif b[x-1] and b[x+1]
            groups+=1
        end
        b[x]=false
    elsif !b[x] and c==?.
        dots+=1
        if !b[x-1] and !b[x+1]
            groups+=1
        elsif b[x-1] and b[x+1]
            groups-=1
        end
        b[x]=true
    end
    res<<dots-groups
}
puts res

#!/usr/bin/ruby

n, m = gets.split
N = n.to_i
M = m.to_i

str = gets.chomp

dot_amount = str.count(".")

seg_amount = 0
i = 0
while i < N do
  if str[i] == "."
    j = i + 1
    while j < N && str[j] == "." do
      j = j + 1
    end
    seg_amount += 1
    i = j + 1
  else
    i += 1
  end
end
#puts dot_amount, seg_amount

for k in 0...M do
  pos, chr = gets.chomp.split
  pos = pos.to_i - 1
  left_dot = pos != 0 && str[pos-1] == "."
  right_dot = pos != N - 1 && str[pos+1] == "."
  #puts "left #{left_dot}, right #{right_dot}, str #{str}, pos #{pos}, str.. #{str[pos+1]}"

  if chr == "." and str[pos] != "."
    if left_dot and right_dot
      seg_amount -= 1
    elsif (not left_dot) and (not right_dot)
      seg_amount += 1
    end
    dot_amount += 1
  elsif chr != "." and str[pos] == "."
    if left_dot and right_dot
      seg_amount += 1
    elsif (not left_dot) and (not right_dot)
      seg_amount -= 1
    end
    dot_amount -= 1
  end
  #puts "pos #{pos} str #{str} chr #{chr}"
  str[pos] = chr

  puts dot_amount - seg_amount
end

#!/usr/bin/ruby

n, m = gets.split
N = n.to_i
M = m.to_i

str = gets.chomp

dot_amount = str.count(".")

seg_amount = 0
i = 0
while i < N do
  j = i
  while j < N && str[j] == "." do
    j = j + 1
  end
  if j != i
    seg_amount += 1
  end

  i = j + 1
end
#puts dot_amount, seg_amount

for k in 0...M do
  pos, chr = gets.chomp.split
  pos = pos.to_i - 1
  left_dot = pos != 0 && str[pos-1] == "."
  right_dot = pos != N - 1 && str[pos+1] == "."
  #puts "left #{left_dot}, right #{right_dot}, str #{str}, pos #{pos}, str.. #{str[pos+1]}"

  if chr == "." and str[pos] != "."
    if left_dot and right_dot
      seg_amount -= 1
    elsif (not left_dot) and (not right_dot)
      seg_amount += 1
    end
    dot_amount += 1
  elsif chr != "." and str[pos] == "."
    if left_dot and right_dot
      seg_amount += 1
    elsif (not left_dot) and (not right_dot)
      seg_amount -= 1
    end
    dot_amount -= 1
  end
  #puts "pos #{pos} str #{str} chr #{chr}"
  str[pos] = chr

  puts dot_amount - seg_amount
end

input = gets.chomp.split
n = Integer(input[0])
m = Integer(input[1])
s = []
s = gets.chomp.split("")
query = []
for i in 0...m
    input = gets.chomp.split
    query[i] = []
    query[i][0] = Integer(input[0])
    query[i][1] = input[1]
end
dot_amount = 0
for i in 0...n
    if s[i] == "."
        dot_amount += 1
    end
end
record = {}
i = 0
while i < n do
    if s[i] == "."
        j = i + 1
        while j < n && s[j] == "." do
            j += 1
        end
        record[i] = [i, j - 1]
        i = j + 1
    else
        i += 1
    end
end
seg_amount = record.size
for i in 0...m
    index = query[i][0] - 1
    content = query[i][1]
    left = index != 0 && s[index - 1] == "."
    right = index != n - 1 && s[index + 1] == "."
    if s[index]!= "."
        if content != "."
            puts dot_amount - seg_amount
        else
            dot_amount += 1
            if left && right
                seg_amount -= 1
                puts dot_amount - seg_amount
            elsif left && !right
                puts dot_amount - seg_amount
            elsif !left && right
                puts dot_amount - seg_amount
            else
                seg_amount += 1
                puts dot_amount - seg_amount
            end
        end
    else
        if content == "."
            puts dot_amount - seg_amount
        else
            dot_amount -= 1
            if left && right
                seg_amount += 1
                puts dot_amount - seg_amount
            elsif left && !right
                puts dot_amount - seg_amount
            elsif !left && right
                puts dot_amount - seg_amount
            else
                seg_amount -= 1
                puts dot_amount - seg_amount
            end
        end
    end
    s[index] = content
end

n,q = gets.chomp.split.map{|x| x.to_i}

str = gets.chomp
prev = str[0]
total = 0
(1..n-1).each do |i|
	curr = str[i]
	if prev == curr and prev == '.'
		total+=1
	end
	prev = curr
end

q.times do
	i,c = gets.chomp.split
	i = (i.to_i)-1

	if c == '.'
		if str[i] != '.'
				if i > 0 and i < n-1

				total+=1 if str[i-1] == '.'
				total+=1 if str[i+1] == '.'
				elsif i==0 and i+1<n  and str[i+1] == '.'
				total+=1
				elsif i==n-1 and str[i-1] == '.'
				total+=1
				end
		end
	else
		if str[i] == '.'
			if i > 0 and i < n-1
				total-=1 if str[i-1] == '.'
				total-=1 if str[i+1] == '.'
			elsif i==0 and i+1<n  and str[i+1] == '.'
				total-=1
			elsif i==n-1 and str[i-1] == '.'
				total-=1
			end
		end

	end
	str[i] = c
	puts total
end

n,m=gets.split.map &:to_i
s=gets

groups=s.scan(/\.+/).size
dots=n-groups

m.times{
    x,c=gets.split
    x=x.to_i-1
    if s[x]==?. and c!=?.
        dots-=1
        if n>1 and (x==0 and s[x+1]!=?.) or (x==n-1 and s[x-1]!=?.)
            groups-=1
        elsif n>2 and (0<x and x<n-1 and s[x-1]==?. and s[x+1]==?.)
            groups+=1
        end
    elsif s[x]!=?. and c==?.
        dots+=1
        if n>1 and (x==0 and s[x+1]!=?.) or (x==n-1 and s[x-1]!=?.)
            groups+=1
        elsif n>2 and (0<x and x<n-1 and s[x-1]==?. and s[x+1]==?.)
            groups-=1
        end
    end
    s[x]=c
    puts dots-groups
}

n,m=gets.split.map &:to_i
s=gets

groups=s.scan(/\.+/).size
dots=s.count ?.

m.times{
    x,c=gets.split
    x=x.to_i-1
    if s[x]==?. and c!=?.
        dots-=1
        if n>1 and (x==0 and s[x+1]!=?.) or (x==n-1 and s[x-1]!=?.)
            groups-=1
        elsif n>2 and (0<x and x<n-1 and s[x-1]==?. and s[x+1]==?.)
            groups+=1
        end
    elsif s[x]!=?. and c==?.
        dots+=1
        if n>1 and (x==0 and s[x+1]!=?.) or (x==n-1 and s[x-1]!=?.)
            groups+=1
        elsif n>2 and (0<x and x<n-1 and s[x-1]==?. and s[x+1]==?.)
            groups-=1
        end
    end
    s[x]=c
    puts dots-groups
}


Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.

The single line contains four integers x, y, a, b (1 ≤ a ≤ x ≤ 100, 1 ≤ b ≤ y ≤ 100). The numbers on the line are separated by a space.

In the first line print integer n — the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers ci, di — the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (ci, di) in the strictly increasing order. Let us remind you that the pair of numbers (p1, q1) is less than the pair of numbers (p2, q2), if p1 < p2, or p1 = p2 and also q1 < q2.

x,y,a,b = gets.split.map{|i| i.to_i}

n = 0
ish = []
while a <= x do
    v = b
    while v <= y do
        if a > v then
            n += 1
            ish << a.to_s + " " + v.to_s
        end
        v += 1
    end
    a += 1
end

puts n
n.times do |i|
    puts ish[i]
end

ans=Array.new
x,y,a,b=gets.split.map(&:to_i)
for i in a.to_i..x.to_i do
k=[y.to_i,i].min
	for j in b.to_i..k
		ans<< [i,j] if i!=j
	end
end
ans.size!=0?(puts ans.size;ans.each{|el|puts el.join(" ")}):(puts 0)

x, y, a, b = gets.split.map(&:to_i)
res = Array.new
for i in [a, b+1].max..x
  for j in b..y
    break if j >= i
    res << [i, j]
  end
end
puts res.count
for i in res
  puts "#{i[0]} #{i[1]}"
end

x, y, a, b = gets.split(' ').collect!{ |i| i.to_i}
n = 0
a.upto(x) do |i|
	b.upto(y) do |j|
		if i>j
			n += 1
		end
	end
end

puts n

a.upto(x) do |i|
	b.upto(y) do |j|
		if i>j
                        puts "#{i} #{j}"
		end
	end
end

x,y,a,b=gets.chomp.split().map(&:to_i)
if a<=b
	a=b+1
end
count=0
i=a
while i<=x
	if i<=y
		min=i-1
	else
		min=y
	end
	count+=min-b+1
	i+=1
end
puts count
while a<=x
	if a<=y
		min=a-1
	else
		min=y
	end
	i=b
	while i<=min
		puts a.to_s+' '+i.to_s
		i+=1
	end
	a+=1

end

x,y,a,b = gets.split.map(&:to_i)
s = %w()
(a..x).each { |i| (b..y).each { |j| s.push [i, j] if i > j } }
puts s.size
s.each { |f| puts f*' ' }

#CF Round 149. Div II Prob. A - Heads or Tails
arr = gets.chomp.split(/ /)
a, res = [], []
arr.each {|i| a << i.to_i}
(a[2]..a[0]).each { |i|
    (a[3]..[a[1], i - 1].min).each { |j|
        res << (i.to_s + " " + j.to_s)
    }
}
puts res.size
res.each {|i| puts i}

#CF Round 149. Div II Prob. A - Heads or Tails
a = gets.chomp.split(/ /).map(&:to_i)
res = []
(a[2]..a[0]).each { |i|
    (a[3]..[a[1], i - 1].min).each { |j|
        res << (i.to_s + " " + j.to_s)
    }
}
puts res.size
res.each {|i| puts i}

x,y,a,b = gets.split.map(&:to_i)
ans = []
if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a).upto(x) do |i|
        (b).upto([(i-1),y].min) do |j|
            ans << "#{i} #{j}"
        end
    end
end
puts ans.length
ans.each { |i| puts i }

x, y, a, b = gets.split.collect{|i| i.to_i}
cnt = 0
for i in a..x
    for j in b...(i<y+1 ? i : y+1)
        cnt += 1
    end
end
puts cnt
for i in a..x
    for j in b...(i<y+1 ? i : y+1)
        print i, " ", j, "\n"
    end
end

x, y, a, b = gets.split.map { |x| x.to_i }
s = a > b ? a : b + 1
t = y + 1
ps = []
for i in s..x
  for j in b...[i, t].min
    ps << [i, j]
  end
end
puts ps.size
ps.each { |p| puts p * ' ' }

x, y, a, b = gets.split.map(&:to_i)
outcomes = []
a.upto(x) do |i|
    b.upto(y) do |j|
        outcomes << [i, j] if i > j
    end
end
puts outcomes.size
outcomes.sort.each do |outcome|
    puts outcome.join(" ")
end

ans=Array.new
x,y,a,b=gets.split.map(&:to_i)
for i in a.to_i..x.to_i do
	for j in [b.to_i,a.to_i].max..[y.to_i,i].min
		ans<< [i,j] if i!=j
	end
end
ans.size!=0?(ans.each{|el|puts el.join(" ")}):(puts 0)

ans=Array.new
x,y,a,b=gets.split.map(&:to_i)
for i in a.to_i..x.to_i do
	for j in [b.to_i,a.to_i].max..[y.to_i,i].min
		ans<< [i,j] if i!=j
	end
end
ans.size!=0?(puts ans.size;ans.each{|el|puts el.join(" ")}):(puts 0)

x, y, a, b = gets.split(' ').collect!{ |i| i.to_i}
n = 0
x.downto(a) do |i|
	y.downto(b) do |j|
		if i>j
			n += 1
		end
	end
end

puts n

x.downto(a) do |i|
	y.downto(b) do |j|
		if i>j
                        puts "#{i} #{j}"
		end
	end
end

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

if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a+1).upto(x) do |i|
        (b).upto(i-1) do |j|
            print i,' ',j; puts
        end
    end
end

x,y,a,b = gets.split.map(&:to_i)
ans = []
if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a+1).upto(x) do |i|
        (b).upto([(i-1),b].min) do |j|
            ans << "#{i} #{j}"
        end
    end
end
puts ans.length
ans.each { |i| puts i }

x,y,a,b = gets.split.map(&:to_i)
ans = []
if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a+1).upto(x) do |i|
        (b).upto(i-1) do |j|
            ans << "#{i} #{j}"
        end
    end
end
puts ans.length
ans.each { |i| puts i }

x,y,a,b = gets.split.map(&:to_i)
ans = []
if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a+1).upto(x) do |i|
        (b).upto(i-1) do |j|
            ans << "#{i} #{j}"
        end
    end
end

ans.each { |i| puts i }

x,y,a,b = gets.split.map(&:to_i)
ans = []
if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a+1).upto(x) do |i|
        (b).upto([(i-1),y].min) do |j|
            ans << "#{i} #{j}"
        end
    end
end
puts ans.length
ans.each { |i| puts i }

x, y, a, b = gets.split.collect{|i| i.to_i}
cnt = 0
for i in b..y
    for j in i+1..x
        cnt += 1
    end
end
puts cnt
for i in b..y
    for j in i+1..x
        print j, " ", i, "\n"
    end
end


An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?

The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train.  The second line contains n integers pi (1 ≤ pi ≤ n, pi ≠ pj if i ≠ j) — the sequence of the numbers of the cars in the train.

Print a single integer — the minimum number of actions needed to sort the railway cars.

NoteIn the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.

#Good luk for the Contest 606, Problem: c
n = gets.strip.to_i
ar = gets.strip.split.map(&:to_i)

pos = Array.new(n, 0)
0.upto(n-1).each do |i|
	pos[ar[i]-1]  = i
end

res = 1
tmp = 1
1.upto(n-1).each do |i|
	if pos[i] > pos[i-1]
		tmp += 1
	else
		res = tmp if tmp >res
		tmp = 1
	end
end
res = tmp if tmp > res
puts n-res

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

hs = Hash.new()
(0...n).each do |i|
  hs[ps[i]] = i
end

ans = n - 1
cnt = 1
for i in 2..n
  if hs[i - 1] < hs[i]
    cnt += 1
  else
    cnt = 1
  end
  ans = [ans, n - cnt].min
end

puts ans

n = gets.to_i
ps = gets.chomp.split.map(&:to_i)
d = Array.new(n, 0)
ps.each {|p| d[p - 1] = p == 1 ?  1 : d[p - 2] + 1 }
puts (n - d.max)

#Good luk for the Contest 606, Problem: c
n = gets.strip.to_i
ar = gets.strip.split.map(&:to_i)

pos = Array.new(n, 0)
0.upto(n-1).each do |i|
	pos[ar[i]-1]  = i
end

res = 1
tmp = 1
1.upto(n-1).each do |i|
	if pos[i] > pos[i-1]
		tmp += 1
	else
		res = tmp if tmp >res
		tmp = 1
	end
end
puts n-res

#Good luk for the Contest 606, Problem: c
n = gets.strip.to_i
ar = gets.strip.split.map(&:to_i)

pos = Array.new(n, 0)
0.upto(n-1).each do |i|
	pos[ar[i]-1]  = i
end

res = 0
tmp = 1
1.upto(n-1).each do |i|
	if pos[i] > pos[i-1]
		tmp += 1
	else
		res = tmp if tmp >res
		tmp = 1
	end
end
puts n-res


Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows.  The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \le k \le 10^9$$$) which location must be found.

For each test case, output in a separate line two integers $$$r$$$ and $$$c$$$ ($$$r, c \ge 1$$$) separated by spaces — the indices of the row and the column containing the cell filled by the number $$$k$$$, respectively.

MOD = 10 ** 9 + 7
def gs; gets.chomp; end
def gi; gets.to_i; end
def gli; gets.split.map(&:to_i); end
def cyesno(x); puts x ? :Yes : :No; end
def uyesno(x); puts x ? :YES : :NO; end
def array_to_hash_by_count(c); Hash.new(0).tap { |x| c.each { |z| x[z] += 1 } }; end

gets.to_i.times do
  x = gi
  n = (x ** 0.5).to_i
  if x == n * n
    puts "#{n} 1"
  else
    n += 1
    diff = n * n - x
    if diff == n - 1
      puts "#{n} #{n}"
    elsif diff > n - 1
      puts "#{n - (diff - n + 1)} #{n}"
    else
      puts "#{n} #{n - (n - diff) + 1}"
    end
  end
end


AquaMoon has two binary sequences $$$a$$$ and $$$b$$$, which contain only $$$0$$$ and $$$1$$$. AquaMoon can perform the following two operations any number of times ($$$a_1$$$ is the first element of $$$a$$$, $$$a_2$$$ is the second element of $$$a$$$, and so on): Operation 1: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\operatorname{min}(a_1,a_2)$$$, and remove the first element of $$$a$$$. Operation 2: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\operatorname{max}(a_1,a_2)$$$, and remove the first element of $$$a$$$.Note that after a removal of the first element of $$$a$$$, the former $$$a_2$$$ becomes the first element of $$$a$$$, the former $$$a_3$$$ becomes the second element of $$$a$$$ and so on, and the length of $$$a$$$ reduces by one.Determine if AquaMoon can make $$$a$$$ equal to $$$b$$$ by using these operations.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2\,000$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 50$$$, $$$m \leq n$$$) — the lengths of $$$a$$$ and $$$b$$$ respectively. The second line of each test case contains a string $$$a$$$ of length $$$n$$$, consisting only $$$0$$$ and $$$1$$$. The third line of each test case contains a string $$$b$$$ of length $$$m$$$, consisting only $$$0$$$ and $$$1$$$.

For each test case, output "YES" if AquaMoon can change $$$a$$$ to $$$b$$$ by using these options; otherwise, output "NO". You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).

NoteIn the first test case, you can use Operation 2 four times to make $$$a$$$ equals to $$$b$$$.In the second test case, you can use Operation 1 four times to make $$$a$$$ equals to $$$b$$$.In the third test case, it can be proved that no matter how we use the operations, it is impossible to make $$$a$$$ equal to $$$b$$$.In the fourth test case, it can be proved that no matter how we use the operations, it is impossible to make $$$a$$$ equal to $$$b$$$.In the fifth test case, you can use Operation 2 three times to make $$$a$$$ become $$$10101$$$, so the first element of $$$a$$$ equals to the first element of $$$b$$$, but it can be proved that no matter how to operate, the second to the fifth elements of $$$a$$$ can't be the same as $$$b$$$.

t = gets.to_i
t.times do
  gets
  a = gets.chomp!
  b = gets.chomp!
  if b.size == 1 && a.include?(b[0]) || a[(-b.size + 1)..-1] == b[1..-1] && a[0..(-b.size)].include?(b[0])
    puts 'YES'
  else
    puts 'NO'
  end
end

t = gets.to_i
t.times do
  gets
  a = gets.chomp!
  b = gets.chomp!
  if a[(-b.size + 1)..-1] == b[1..-1] && a[0..(-b.size)].include?(b[0])
    puts 'YES'
  else
    puts 'NO'
  end
end


Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams!Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the m friends found n different kinds of milk on the menu, that's why they ordered n bottles — one bottle of each kind. We know that the volume of milk in each bottle equals w.When the bottles were brought in, they decided to pour all the milk evenly among the m cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem — and what is actually the way to do it?Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible!Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup.

The only input data file contains three integers n, w and m (1 ≤ n ≤ 50, 100 ≤ w ≤ 1000, 2 ≤ m ≤ 50), where n stands for the number of ordered bottles, w stands for the volume of each of them and m stands for the number of friends in the company.

Print on the first line "YES" if it is possible to pour the milk so that the milk from each bottle was in no more than two different cups. If there's no solution, print "NO". If there is a solution, then print m more lines, where the i-th of them describes the content of the i-th student's cup. The line should consist of one or more pairs that would look like "b v". Each such pair means that v (v > 0) units of milk were poured into the i-th cup from bottle b (1 ≤ b ≤ n). All numbers b on each line should be different. If there are several variants to solve the problem, print any of them. Print the real numbers with no less than 6 digits after the decimal point.

n, w, m = gets.split.map(&:to_i)
current = 0
pos = 0
ret = Array.new(m){Array.new}

n.times do |i|
  if current + m > n
    ret[pos] << [i, n - current]
    pos += 1
    current = m - (n - current)
    if current > n
      puts 'NO'
      exit
    else
      ret[pos] << [i, current]
    end
  else
    ret[pos] << [i, m]
    current += m
  end
  if current == n
    pos += 1
    current = 0
  end
end

puts 'YES'
ret.each do |array|
  s = array.map do |e|
    e[0] += 1
    e[1] = e[1].to_f * w / m
    "%d %.6f" % e
  end.join(" ")
  puts s
end

# 4 100 8

n, w, m = gets.split.map(&:to_i)
current = 0
pos = 0
ret = Array.new(m){Array.new}

n.times do |i|
  if current + m > n
    ret[pos] << [i, n - current]
    pos += 1
    current = m - (n - current)
    if current > n
      puts 'NO'
      exit
    else
      ret[pos] << [i, current]
      if current == n
        pos += 1
        current = 0
      end
    end
  else
    ret[pos] << [i, m]
    current += m
  end
end

puts 'YES'
ret.each do |array|
  s = array.map do |e|
    e[0] += 1
    e[1] = e[1].to_f * w / m
    "%d %.6f" % e
  end.join(" ")
  puts s
end

# 4 100 8

n, w, m = gets.split.map(&:to_i)
min = 10e-6
a = (n * w).to_f / m
r = a
ret = Array.new(m){Array.new}
cur = 0
n.times do |i|
  if r - w > min
    ret[cur] << [i, w]
    r = r - w
  else
    ret[cur] << [i, r]
    cur += 1
    if w - r > a + min
      puts 'NO'
      exit
    elsif w - r > min
      ret[cur] << [i, w - r]
      r = a - (w - r)
    end
  end
end

puts 'YES'
ret.each do |array|
  s = array.map do |e|
    e[0] += 1
    "%d %.6f" % e
  end.join(" ")
  puts s
end


Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value x, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than y points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.Vova has already wrote k tests and got marks a1, ..., ak. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.

The first line contains 5 space-separated integers: n, k, p, x and y (1 ≤ n ≤ 999, n is odd, 0 ≤ k < n, 1 ≤ p ≤ 1000, n ≤ x ≤ n·p, 1 ≤ y ≤ p). Here n is the number of tests that Vova is planned to write, k is the number of tests he has already written, p is the maximum possible mark for a test, x is the maximum total number of points so that the classmates don't yet disturb Vova, y is the minimum median point so that mom still lets him play computer games. The second line contains k space-separated integers: a1, ..., ak (1 ≤ ai ≤ p) — the marks that Vova got for the tests he has already written.

If Vova cannot achieve the desired result, print "-1". Otherwise, print n - k space-separated integers — the marks that Vova should get for the remaining tests. If there are multiple possible solutions, print any of them.

NoteThe median of sequence a1, ..., an where n is odd (in this problem n is always odd) is the element staying on (n + 1) / 2 position in the sorted list of ai.In the first sample the sum of marks equals 3 + 5 + 4 + 4 + 1 = 17, what doesn't exceed 18, that means that Vova won't be disturbed by his classmates. And the median point of the sequence {1, 3, 4, 4, 5} equals to 4, that isn't less than 4, so his mom lets him play computer games.Please note that you do not have to maximize the sum of marks or the median mark. Any of the answers: "4 2", "2 4", "5 1", "1 5", "4 1", "1 4" for the first test is correct.In the second sample Vova got three '5' marks, so even if he gets two '1' marks, the sum of marks will be 17, that is more than the required value of 16. So, the answer to this test is "-1".

n,k,p,x,y=gets.chomp.split(' ').map(&:to_i)
ak=gets.chomp.split(' ').map(&:to_i)
one=0
two=0
sum=0
for i in ak do
	sum+=i
	if i<y
		one+=1
	else
		two+=1
	end
end

won=n/2-one
if won>(n-k)
	won=n-k
end
m=n-k-won
sum=x-sum
if won+y*m>sum ||won<0
	puts "-1"
else
	won.times do
		print "1 "
	end
	m.times do
		print y.to_s+' '
	end
end
puts

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|i| i < y}
g = kk.count{|i| i >= y}
add_g = [0, (n + 1) / 2 - g].max
if l > n / 2 || kk.inject(:+).to_i + add_g * y + (n - k - add_g) > x
  puts -1
else
  ans = []
  add_g.times{ans << y}
  (n - k - add_g).times{ans << 1}
  puts ans.join(" ")
end

n,k,p,x,y=gets.chomp.split(' ').map(&:to_i)
ak=gets.chomp.split(' ').map(&:to_i).sort
ch=0
sum=0
for i in ak do
	sum+=i
end
ak.each_with_index { |i,j|
	if i>=y
		ch=j
		break
	end
}
left=n/2-ch
right=n-k-left

#puts "left = "+left.to_s
#puts "right = "+right.to_s
#puts "p = "+p.to_s
#puts "y = "+y.to_s
#puts "x = "+x.to_s
#puts "sum = "+sum.to_s
#puts "sum+left+right*y = "+ (sum+left+right*y).to_s

if(left<0)
	puts "-1"
elsif(p<y && right>0)
	puts "-1"
elsif(right<0)
	right=0;
	left=n-k-right;
elsif sum+left+right*y<=x
	left.times do
		print "1 "
	end
	right.times do
		print y.to_s+' '
	end
	puts
else
	puts "-1"
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|x| x < y}
g = k - l

if l > n / 2 || (n / 2 - l) * 1 + [(n - n / 2 - g), 0].max * y + kk.inject(:+).to_i > x
  puts -1
else
  ans = []
  (n - k).times do
    if kk[(kk.size - 1) / 2].to_i >= y
      kk << 1
      ans << 1
    else
      kk << y
      ans << y
    end
    kk.sort!
  end
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|x| x < y}
g = k - l
if l > n / 2 || (n / 2 - l) * 1 + (n - n / 2 - g) * y + kk.inject(:+).to_i > x
  puts -1
else
  ans = []
  (n - k).times do
    if kk[(kk.size - 1) / 2].to_i >= y
      kk << 1
      ans << 1
    else
      kk << y
      ans << y
    end
    kk.sort!
  end
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|x| x < y}
g = k - l
if l > n / 2 || g > n / 2 || (n / 2 - l) * 1 + (n / 2 - g) * y + kk.inject(:+).to_i > x
  puts -1
else
  ans = []
  (n - k).times do
    if kk[(kk.size - 1) / 2].to_i >= y
      kk << 1
      ans << 1
    else
      kk << 4
      ans << 4
    end
    kk.sort!
  end
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|i| i < y}
g = kk.count{|i| i >= y}
add_g = [0, (n + 1) / 2 - g].max
if l > n / 2 || kk.inject(:+).to_i + add_g * y + (n - k - add_g) > x
  puts -1
else
  ans = []
  (n - k).times do
    if kk[kk.size / 2] < y
      kk << y
      ans << y
    elsif kk.size < n
      kk << 1
      ans << 1
    end
  end
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|x| x < y}
g = k - l
if l > n / 2 || g > n / 2 || (n / 2 - l) * 1 + (n - n / 2 - g) * y + kk.inject(:+).to_i > x
  puts -1
else
  ans = []
  (n - k).times do
    if kk[(kk.size - 1) / 2].to_i >= y
      kk << 1
      ans << 1
    else
      kk << y
      ans << y
    end
    kk.sort!
  end
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
ans = []
if k > 0
  kk = gets.split.map(&:to_i)
else
  kk = [y]
  ans << y
end
l = kk.count{|x| x < y}
g = kk.count{|x| x > y}
p_n = x - kk.inject(:+)
if l > n / 2 || g > n / 2 || (n / 2 - l) * 1 + (n / 2 - g) * y > p_n
  puts -1
else
  (n / 2 - l).times{ans << 1}
  (n / 2 - g).times{ans << y}
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|x| x < y}
g = kk.count{|x| x > y}
p_n = x - kk.inject(:+)
if l > n / 2 || g > n / 2 || (n / 2 - l) * 1 + (n / 2 - g) * y > p_n
  puts -1
else
  ans = []
  (n / 2 - l).times{ans << 1}
  (n / 2 - g).times{ans << y}
  puts ans.join(" ")
end


A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe xi. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg.The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.

The first line of input contains three space-separated integers, a, b and c (1 ≤ b < a < c ≤ 109), denoting the positions of Oleg, the first security guard and the second security guard, respectively. The next line of input contains a single integer n (1 ≤ n ≤ 105), denoting the number of banknotes. The next line of input contains n space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 109), denoting that the i-th banknote is located in the xi-th safe. Note that xi are not guaranteed to be distinct.

Output a single integer: the maximum number of banknotes Oleg can take.

NoteIn the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes.For the second sample, Oleg can't take any banknotes without bumping into any of the security guards.

a, b, c = gets.chomp.split(" ").map(&:to_i)
n = gets.chomp.to_i
xx = gets.chomp.split(" ").map(&:to_i)

ret = 0

xx.each do |x|
  if x > b && x < c then
    ret += 1
  end
end
puts ret


ВКонтакте открыла второй штаб в Санкт-Петербурге! Вы не преминули возможностью сменить обстановку и решили переехать из офиса в Доме Зингера в офис на Красном мосту.Для комфортной работы вам потребуются два монитора с одинаковой высотой, чтобы изображение на них выглядело единым целым. На складе офиса на Красном мосту есть $$$n$$$ мониторов, $$$i$$$-й из них имеет ширину $$$w_i$$$ и высоту $$$h_i$$$. Любой монитор можно повернуть на 90 градусов, и тогда он будет иметь ширину $$$h_i$$$ и высоту $$$w_i$$$.Назовём неупорядоченную пару из двух различных мониторов подходящей, если можно их повернуть так, чтобы они имели одинаковую высоту. Любой из мониторов в паре можно как повернуть относительно исходной ориентации, так и не поворачивать.Подсчитайте подходящие пары мониторов.

В первой строке задано одно целое число $$$n$$$ — число мониторов на складе. В каждой из следующих $$$n$$$ строк заданы два целых числа $$$w_i$$$ и $$$h_i$$$ ($$$1 \le w_i, h_i \le 10^9$$$) — ширина и высота $$$i$$$-го монитора. Обратите внимание, что мониторы могут быть квадратными ($$$w_i = h_i$$$), а размеры разных мониторов могут совпадать. В этой версии задачи $$$2 \le n \le 10^3$$$.

Выведите число подходящих пар мониторов.

ПримечаниеВ первом примере подходящими являются пары мониторов с номерами $$$(1, 2)$$$, $$$(1, 4)$$$, $$$(1, 5)$$$, $$$(3, 4)$$$, $$$(4, 5)$$$.Во втором примере все пары мониторов — подходящие.

count = gets.chomp.to_i
monitors = []
result = 0

count.times do
  monitors << gets.chomp.split(' ').map(&:to_i)
end

monitors.each_with_index do |monitor1, index1|
  monitors.each_with_index do |monitor2, index2|
    next if index1 == index2

    result += 1 if monitor1.intersection(monitor2) != []
  end
end

puts result / 2


The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring.String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r.Help the bear cope with the given problem.

The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters.

Print a single number — the answer to the problem.

s=gets.chomp
l=s.size
p=0
r=0
while (q=s.index('bear',p))
  r+=(l-q-3)*(q-p+1)
  p=q+1
end
p r

s, r, x = gets.chomp, 0, -1

(s.length - 3).times do |i|
    x = i if s[i..i+3] == 'bear'
    r += x + 1
end

p r

#f = File.open('test1.txt', 'r')
f = STDIN
s = f.gets.chomp
res = 0
length = s.length
length.times do |i|
  j = s.index 'bear', i
  next unless j
  j += 3
  res += length - j
end
puts res

str = gets.chomp

def eq_bear?(str)
	str[(0..3)] == "bear"
end

sum = 0
last = -1
(0...str.length).each do |i|
	if eq_bear? str[(i..(i + 3))]
		sum += (i - last) * (str.length - (i + 3))
		last = i
	end
end

puts sum

str = gets.chomp
last = -1
ans = 0
(3...str.size).step(1) { |i|
  last = i-3 if str[i-3..i] == 'bear'
  ans += last + 1
}
puts ans

s, r = gets.chomp, 0
n = s.length
x = 1

s.each_char.with_index do |c, i|
    if (i < n-3) && s[i] + s[i+1] + s[i+2] + s[i+3] == 'bear'

        r += (i+x) * (n - i - 3)
        x = 0 if x == 1
    end
end

p r


There is a pyramid which consists of $$$n$$$ floors. The floors are numbered from top to bottom in increasing order. In the pyramid, the $$$i$$$-th floor consists of $$$i$$$ rooms.Denote the $$$j$$$-th room on the $$$i$$$-th floor as $$$(i,j)$$$. For all positive integers $$$i$$$ and $$$j$$$ such that $$$1 \le j \le i < n$$$, there are $$$2$$$ one-way staircases which lead from $$$(i,j)$$$ to $$$(i+1,j)$$$ and from $$$(i,j)$$$ to $$$(i+1,j+1)$$$ respectively.In each room you can either put a torch or leave it empty. Define the brightness of a room $$$(i, j)$$$ to be the number of rooms with a torch from which you can reach the room $$$(i, j)$$$ through a non-negative number of staircases.For example, when $$$n=5$$$ and torches are placed in the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,2)$$$, $$$(4,1)$$$, $$$(4,3)$$$, and $$$(5,3)$$$, the pyramid can be illustrated as follows:  In the above picture, rooms with torches are colored in yellow, and empty rooms are white. The blue numbers in the bottom-right corner indicate the brightness of the rooms.The room $$$(4,2)$$$ (the room with a star) has brightness $$$3$$$. In the picture below, the rooms from where you can reach $$$(4,2)$$$ have red border. The brightness is $$$3$$$ since there are three torches among these rooms.  The pyramid is called nice if and only if for all floors, all rooms in the floor have the same brightness.Define the brilliance of a nice pyramid to be the sum of brightness over the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,1)$$$, ..., $$$(n,1)$$$.Find an arrangement of torches in the pyramid, such that the resulting pyramid is nice and its brilliance is maximized.We can show that an answer always exists. If there are multiple answers, output any one of them.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains a single positive integer $$$n$$$ ($$$1 \le n \le 500$$$) — the number of floors in the pyramid. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$500$$$.

For each test case, output $$$n$$$ lines, the arrangement of torches in the pyramid. The $$$i$$$-th line should contain $$$i$$$ integers, each separated with a space. The $$$j$$$-th integer on the $$$i$$$-th line should be $$$1$$$ if room $$$(i,j)$$$ has a torch, and $$$0$$$ otherwise. We can show that an answer always exists. If there are multiple answers, output any one of them.

NoteIn the third test case, torches are placed in $$$(1,1)$$$, $$$(2,1)$$$, $$$(2,2)$$$, $$$(3,1)$$$, and $$$(3,3)$$$.  The pyramid is nice as rooms on each floor have the same brightness. For example, all rooms on the third floor have brightness $$$3$$$.The brilliance of the pyramid is $$$1+2+3 = 6$$$. It can be shown that no arrangements with $$$n=3$$$ will have a greater brilliance.

def main
  t = inp.to_i
  t.times do
    n = inp.to_i
    1.upto(n) do |i|
      1.upto(i) do |j|
        if j == 1 || j == i
          print 1
        else
          print 0
        end
        print " " if j != i
      end
      puts ""
    end
  end

end

# lib
def inp
  gets.chomp
end

def inarr
  gets.chomp.split
end

def mapint(lst)
  lst.map(&:to_i)
end

main


Vasya has got three integers $$$n$$$, $$$m$$$ and $$$k$$$. He'd like to find three integer points $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$, such that $$$0 \le x_1, x_2, x_3 \le n$$$, $$$0 \le y_1, y_2, y_3 \le m$$$ and the area of the triangle formed by these points is equal to $$$\frac{nm}{k}$$$.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.

If there are no such points, print "NO". Otherwise print "YES" in the first line. The next three lines should contain integers $$$x_i, y_i$$$ — coordinates of the points, one point per line. If there are multiple solutions, print any of them. You can print each letter in any case (upper or lower).

NoteIn the first example area of the triangle should be equal to $$$\frac{nm}{k} = 4$$$. The triangle mentioned in the output is pictured below:   In the second example there is no triangle with area $$$\frac{nm}{k} = \frac{16}{7}$$$.

n,m,k = gets.split.map(&:to_i)
if (n*m*2)%k == 0
  area = (n*m*2)/k
  puts "YES"
  x = n.gcd(area)
  y = area/x
  if y > m
    y /= 2
    x *= 2
  end
  puts "0 0"
  puts "#{x} 0"
  puts "0 #{y}"
else
  puts "NO"
end

n,m,k = gets.split.map(&:to_i)
if (n*m*2)%k == 0
  area = (n*m*2)/k
  puts "YES"
  g = n.gcd(area)
  puts "0 0"
  puts "#{g} 0"
  puts "0 #{area/g}"
else
  puts "NO"
end


You are given a string $$$a$$$, consisting of $$$n$$$ characters, $$$n$$$ is even. For each $$$i$$$ from $$$1$$$ to $$$n$$$ $$$a_i$$$ is one of 'A', 'B' or 'C'.A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You want to find a string $$$b$$$ that consists of $$$n$$$ characters such that:   $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$. In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.Your task is to determine if such a string $$$b$$$ exists.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$a$$$. $$$a$$$ consists only of uppercase letters 'A', 'B' and 'C'. Let $$$n$$$ be the length of $$$a$$$. It is guaranteed that $$$n$$$ is even and $$$2 \le n \le 50$$$.

For each testcase print "YES" if there exists such a string $$$b$$$ that:    $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$.  Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first testcase one of the possible strings $$$b$$$ is "(())()".In the second testcase one of the possible strings $$$b$$$ is "()()".

def good(s)
  cur = 0
  s.each_char do |c|
    cur += c == '(' ? 1 : -1
    return false if cur < 0
  end
  cur == 0
end
gets.to_i.times do
  s = gets.chomp
  ok = false
  (0...8).each do |msk|
    cur = s.dup
    (0...s.size).each do |i|
      if msk >> (s[i].ord - 'A'.ord) & 1 != 0
        cur[i] = '('
      else
        cur[i] = ')'
      end
    end
    ok |= good cur
  end
  puts ok ? "YES" : "NO"
end

class String
  def rbs?
    b = 0
    self.each_char { |c|
      b += 1 if c == '('
      b -= 1 if c == ')'
      return false if b < 0
    }
    b == 0
  end
end

gets.to_i.times do
  s = gets.strip

  solution_found = false
  8.times do |m|
    a = '()'[(m >> 0) & 1]
    b = '()'[(m >> 1) & 1]
    c = '()'[(m >> 2) & 1]
    t = s.gsub('A', a).gsub('B', b).gsub('C', c)
    solution_found = true if t.rbs?
  end

  puts(solution_found ? "YES" : "NO")
end

def solve
  a = string
  n = a.size
  (1 << 3).times do |bits|
    paren = 0
    xa = 1 - bits[0] * 2
    xb = 1 - bits[1] * 2
    xc = 1 - bits[2] * 2
    valid = true
    a.each_char do |c|
      case c
      when ?A
        paren += xa
      when ?B
        paren += xb
      when ?C
        paren += xc
      end
      if paren < 0
        valid = false
        break
      end
    end
    valid &&= (paren == 0)
    if valid
      puts "YES"
      return
    end
  end
  puts "NO"
end

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

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

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main

def good(s)
  cur = 0
  s.each_char do |c|
    cur += c == '(' ? 1 : -1
    return false if cur < 0
  end
  cur == 0
end
gets.to_i.times do
  s = gets.chomp
  ok = false
  (0..7).each do |msk|
    cur = s
    (0...s.size).each do |i|
      if (msk >> (s[i].ord - 'A'.ord)) & 1 != 0
        cur[i] = '('
      else
        cur[i] = ')'
      end
      ok |= good cur
    end
  end
  puts ok ? "YES" : "NO"
end

def good(s)
  cur = 0
  s.each_char do |c|
    cur += c == '(' ? 1 : -1
    return false if cur < 0
  end
  cur == 0
end
gets.to_i.times do
  s = gets.chomp
  ok = false
  (0..7).each do |msk|
    cur = s
    (0...s.size).each do |i|
      if msk >> (s[i].ord - 'A'.ord) & 1 != 0
        cur[i] = '('
      else
        cur[i] = ')'
      end
      ok |= good cur
    end
  end
  puts ok ? "YES" : "NO"
end

def good(s)
  cur = 0
  s.each_char do |c|
    cur += c == '(' ? 1 : -1
    return false if cur < 0
  end
  cur == 0
end
gets.to_i.times do
  s = gets.chomp
  ok = false
  (1..7).each do |msk|
    cur = s
    (0...s.size).each do |i|
      if msk >> (s[i].ord - 'A'.ord) & 1 != 0
        cur[i] = '('
      else
        cur[i] = ')'
      end
      ok |= good cur
    end
  end
  puts ok ? "YES" : "NO"
end


Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has n records in total.In order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category:   "noob" — if more than 50% of players have better results;  "random" — if his result is not worse than the result that 50% of players have, but more than 20% of players have better results;  "average" — if his result is not worse than the result that 80% of players have, but more than 10% of players have better results;  "hardcore" — if his result is not worse than the result that 90% of players have, but more than 1% of players have better results;  "pro" — if his result is not worse than the result that 99% of players have.  When the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that 50% of players have, and the second one is not worse than the result that 100% of players have.Vasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.

The first line contains the only integer number n (1 ≤ n ≤ 1000) — a number of records with the players' results. Each of the next n lines contains a player's name and the amount of points, obtained by the player for the round, separated with a space. The name contains not less than 1 and no more than 10 characters. The name consists of lowercase Latin letters only. It is guaranteed that any two different players have different names. The amount of points, obtained by the player for the round, is a non-negative integer number and does not exceed 1000.

Print on the first line the number m — the number of players, who participated in one round at least. Each one of the next m lines should contain a player name and a category he belongs to, separated with space. Category can be one of the following: "noob", "random", "average", "hardcore" or "pro" (without quotes). The name of each player should be printed only once. Player names with respective categories can be printed in an arbitrary order.

5
vasya 100
vasya 200
artem 100
kolya 200
igor 250

4
artem noob
igor pro
kolya random
vasya random

NoteIn the first example the best result, obtained by artem is not worse than the result that 25% of players have (his own result), so he belongs to category "noob". vasya and kolya have best results not worse than the results that 75% players have (both of them and artem), so they belong to category "random". igor has best result not worse than the result that 100% of players have (all other players and himself), so he belongs to category "pro".In the second example both players have the same amount of points, so they have results not worse than 100% players have, so they belong to category "pro".

def classify(percent)
  return "noob" if percent > 50.0
  return "random" if percent > 20.0
  return "average" if percent > 10.0
  return "hardcore" if percent > 1.0
  return "pro"
end

n = gets.chomp.to_i
h = Hash.new()
for i in 0..n-1
  nm, pt = gets.chomp.split(/ /)
  pt = pt.to_i
  if h.key?(nm)
    if h[nm] < pt
      h[nm] = pt
    end
  else
    h[nm] = pt
  end
end

a = h.to_a
n = a.length
a.sort!{|a1, a2|
  a2[1] <=> a1[1]
}
ret = []
wkper = 0
prev = 0
for i in 0..n-1
  if prev > a[i][1]
    wkper = (i / n.to_f) * 100
  end
  ret << [a[i][0], classify(wkper)]
  prev = a[i][1]
end
ret.sort!{|r1, r2|
  r1[0] <=> r2[0]
}
puts n
ret.each{|rr|
  puts rr.join(" ")
}

result = Hash.new
result.default = 0
n = gets.to_i
n.times do
  a,b = gets.split
  b = b.to_i
  result[a] = [result[a],b].max
end

array = result.sort
m=array.length
puts m
m.times{|i|
  cnt=0
  tmp=array[i][1]
  m.times{|j|
    cnt+=1 if tmp<array[j][1]
  }
  print array[i][0]
  per=100.0-cnt*100.0/m
  if per>=99.0
    puts " pro"
  elsif per>=90.0
    puts " hardcore"
  elsif per>=80.0
    puts " average"
  elsif per>=50.0
    puts " random"
  else
    puts " noob"
  end
}

result = Hash.new
result.default = 0
n = gets.to_i
n.times do
  a,b = gets.split
  b = b.to_i
  result[a] = [result[a],b].max
end
array = result.sort
m=array.length
puts m
m.times do |i|
  cnt=0
  tmp=array[i][1]
  m.times{|j|
    cnt+=1 if tmp<array[j][1]
  }
  print array[i][0]
  per=100.0-cnt*100.0/m
  if per>=99.0
    puts " pro"
  elsif per>=90.0
    puts " hardcore"
  elsif per>=80.0
    puts " average"
  elsif per>=50.0
    puts " random"
  else
    puts " noob"
  end
end

n = STDIN.gets.to_i
scores = {}
(0...n).each do |it|
	name, score = STDIN.gets.split ' '
	score = score.to_i
	if scores.has_key? name
		scores[name] = [scores[name], score].max
	else
		scores[name] = score
	end
end

p scores.size
scores.keys.each do |i|
	score = scores[i]
	not_worse = 0
	better = 0
        scores.values.each do |j|
        	if j <= score
        		not_worse += 1
		else
			better += 1
		end
        end
        category = ""
        if better > 0.5 * scores.size
        	category = "noob"
	elsif better > 0.2 * scores.size
		category = "random"
	elsif better > 0.1 * scores.size
		category = "average"
	elsif better > 0.01 * scores.size
		category = "hardcore"
	else
		category = "pro"
	end
	puts "#{i} #{category}"
end

result = Hash.new
result.default = 0
n = gets.to_i
n.times do
  a,b = gets.split
  b = b.to_i
  result[a] = [result[a],b].max
end

array = result.sort
m=array.length
m.times{|i|
  cnt=0
  tmp=array[i][1]
  m.times{|j|
    cnt+=1 if tmp<array[j][1]
  }
  print array[i][0]
  per=100.0-cnt*100.0/m
  if per>99.0
    puts " pro"
  elsif per>90.0
    puts " hardcore"
  elsif per>80.0
    puts " average"
  elsif per>50.0
    puts " random"
  else
    puts " noob"
  end
}


Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.You have to find the minimum number of digits in which these two numbers can differ.

The first line contains integer k (1 ≤ k ≤ 109). The second line contains integer n (1 ≤ n < 10100000). There are no leading zeros in n. It's guaranteed that this situation is possible.

Print the minimum number of digits in which the initial number and n can differ.

NoteIn the first example, the initial number could be 12.In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.

k=gets.to_i
n=gets.chomp.chars.sort.map &:to_i
x=n.inject :+
res=0
while x<k
    x+=9-n[res]
    res+=1
end
puts res

k = gets.to_i
n = gets.chomp.chars.map(&:to_i).sort
s = n.map(&:to_i).reduce(0, :+)
d = 0
n.each{|x|
  break if s>=k
  d += 1
  s += 9 - x
}
p d

k = gets.to_i
n = gets.chomp.split('').map(&:to_i).sort
sum = n.inject(:+)
ans = 0
idx = 0
while sum < k
    sum += 9 - n[idx]
    idx += 1
    ans += 1
end
puts ans

k=gets.to_i
n=gets.chars.sort.map &:to_i
x=n.inject :+
res=0
while x<k
    x+=9-n[res]
    res+=1
end
puts res

k=gets.to_i
n=gets
x=n.chars.map(&:to_i).inject(:+)
puts (x<k ? 1 : 0)


Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.

The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 и s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.

If Vasya can write the given anonymous letter, print YES, otherwise print NO

Instead of dogging Your footsteps it disappears but you dont notice anything
where is your dog

Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging your footsteps it disappears but you dont notice anything
Your dog is upstears

str=gets
str2=gets

symbols=str2.scan(/(\w)/)
r=true
symbols.each{|i|
	if str=~/#{i}/
		str=str.sub(/#{i}/,"")
#		print "Found ",i,"\nstr=",str,"\n"
	else
#		print "Not found ",i,"\nstr=",str,"\n"
		r=false
		break
	end
}
if r then print "YES"
else print "NO"
end

a=[*gets.chars]
puts gets.scan(/\S/).all?{|b|(c=a.index b)&&a.delete_at(c)}?:YES:"NO"

#=================================
require 'prime'
include Math

if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

txt=gets.strip.gsub(/[^a-zA-Z]/,'')
msg=gets.strip.gsub(/[^a-zA-Z]/,'')

ans=true
msg.each_char{|c|
	(ans=false and break) if !(txt.count(c)>=msg.count(c))
}

puts ans ? :YES : :NO

def main()
	s1=gets.chomp.to_s
	s2=gets.chomp.to_s
	charavail=[]
	for i in 0...(s1.length)
		if s1[i].chr!=" "
		charavail << s1[i].chr
		end
	end
	f=true
	for i in 0...(s2.length)
		if s2[i].chr!=" "
			if charavail.include?(s2[i].chr)
				ind=charavail.index(s2[i].chr)
				charavail.delete_at(ind)
			else
				f=false
				break;
			end
		end
	end
	if f
		puts "YES"
	else
		puts "NO"
	end
end
main()

s1 = gets.chomp!.gsub(" ","")
s2 = gets.chomp!.gsub(" ","")

s2.each_char { |c|
  index = s1.index(c)
  if index == nil
    puts "NO"
    exit
  else
    s1[index..index] = ""
  end
}

puts "YES"

s1, s2 = gets.chomp, gets.chomp

s1 = s1.scan(/./).reject{ |x| x =~ /\s+/ }
s2 = s2.scan(/./).reject{ |x| x =~ /\s+/ }

res = true
s2.each do |char|
  i = s1.index(char)
  if i
    s1.delete_at(i)
  else
    res = false
    break
  end
end

puts res ? "YES" : "NO"

require 'set'

YES, NO = "YES", "NO"

def get_table(test)
  result = Hash.new(0)
  test.gsub(/\s+/, '').each_char { |char| result[char] += 1 }
  result
end

header, text = get_table(gets), get_table(gets)

ok = true

text.each_key do |letter|
  if text[letter] > header[letter]
    ok = false
    break
  end
end

puts ok ? YES : NO

h, l = STDIN.read.split("\n")

l.each_char do |c|
  next if c == ' '
  i = h.index c
  (print :NO; exit) if i.nil?
  h[i] = ''
end

print :YES

str=gets
str2=gets
#str="Instead of dogging Your footsteps it disappears but you dont notice anything"
#str2="where is your dog"

symbols=str2.scan(/(\w)/)
r=true
symbols.each{|i|
	if str=~/#{i}/
		str=str.sub(/#{i}/,"")
	else
		r=false
		break
	end
}
if r then p "YES"
else print "NO"
end

#=================================
require 'prime'
include Math

if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

txt=gets.strip
msg=gets.strip

ans=true
msg.each_char{|c|
	(ans=false and break) if !(msg.count(c)>=txt.count(c))
}

puts ans ? :YES : :NO

s1 = gets.chomp!.gsub(" ","")
s2 = gets.chomp!.gsub(" ","")

s2.each_char { |c|
  if s1.index(c) == nil
    puts "NO"
    exit
  end
}

puts "YES"


Petya organized a strange birthday party. He invited $$$n$$$ friends and assigned an integer $$$k_i$$$ to the $$$i$$$-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are $$$m$$$ unique presents available, the $$$j$$$-th present costs $$$c_j$$$ dollars ($$$1 \le c_1 \le c_2 \le \ldots \le c_m$$$). It's not allowed to buy a single present more than once.For the $$$i$$$-th friend Petya can either buy them a present $$$j \le k_i$$$, which costs $$$c_j$$$ dollars, or just give them $$$c_{k_i}$$$ dollars directly.Help Petya determine the minimum total cost of hosting his party.

The first input line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 3 \cdot 10^5$$$) — the number of friends, and the number of unique presents available. The following line contains $$$n$$$ integers $$$k_1, k_2, \ldots, k_n$$$ ($$$1 \leq k_i \leq m$$$), assigned by Petya to his friends.  The next line contains $$$m$$$ integers $$$c_1, c_2, \ldots, c_m$$$ ($$$1 \le c_1 \le c_2 \le \ldots \le c_m \le 10^9$$$) — the prices of the presents. It is guaranteed that sum of values $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of values $$$m$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case output a single integer — the minimum cost of the party.

NoteIn the first example, there are two test cases. In the first one, Petya has $$$5$$$ friends and $$$4$$$ available presents. Petya can spend only $$$30$$$ dollars if he gives  $$$5$$$ dollars to the first friend.  A present that costs $$$12$$$ dollars to the second friend.  A present that costs $$$5$$$ dollars to the third friend.  A present that costs $$$3$$$ dollars to the fourth friend.  $$$5$$$ dollars to the fifth friend. In the second one, Petya has $$$5$$$ and $$$5$$$ available presents. Petya can spend only $$$190$$$ dollars if he gives  A present that costs $$$10$$$ dollars to the first friend.  A present that costs $$$40$$$ dollars to the second friend.  $$$90$$$ dollars to the third friend.  $$$40$$$ dollars to the fourth friend.  $$$10$$$ dollars to the fifth friend.

t= gets.chomp.to_i
while t > 0
 n, m   = gets.chomp.split(' ')
 n = n.to_i
 m = m.to_i
 k = gets.chomp.split(' ').map(&:to_i)
 c = gets.chomp.split(' ').map(&:to_i)
 k = k.sort.reverse()
 last_used_gift = 0
 cost = 0
 k.each do |ks|
  if(c[ks-1] > c[last_used_gift] && last_used_gift < m)
  	cost = cost + c[last_used_gift]
  	last_used_gift = last_used_gift + 1
  else
  	cost = cost + c[ks-1]
  end
 end
 puts cost
 t = t - 1
end

t = gets.to_i
ans = []
t.times do
  n,m = gets.chomp.split(" ").map(&:to_i)
  k = gets.chomp.split(" ").map(&:to_i).sort!.reverse!
  c = gets.chomp.split(" ").map(&:to_i)
  sum = 0
  index = 0
  n.times do |i|
    if c[k[i]-1] > c[index]
      sum += c[index]
      index += 1
    else
      sum += c[k[i]-1]
    end
  end
  ans << sum
end
puts ans


This is a simplified version of the problem B2. Perhaps you should read the problem B2 before you start solving B1.Paul and Mary have a favorite string $$$s$$$ which consists of lowercase letters of the Latin alphabet. They want to paint it using pieces of chalk of two colors: red and green. Let's call a coloring of a string wonderful if the following conditions are met:  each letter of the string is either painted in exactly one color (red or green) or isn't painted;  each two letters which are painted in the same color are different;  the number of letters painted in red is equal to the number of letters painted in green;  the number of painted letters of this coloring is maximum among all colorings of the string which meet the first three conditions. E. g. consider a string $$$s$$$ equal to "kzaaa". One of the wonderful colorings of the string is shown in the figure.    The example of a wonderful coloring of the string "kzaaa". Paul and Mary want to learn by themselves how to find a wonderful coloring of the string. But they are very young, so they need a hint. Help them find $$$k$$$ — the number of red (or green, these numbers are equal) letters in a wonderful coloring.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one non-empty string $$$s$$$ which consists of lowercase letters of the Latin alphabet. The number of characters in the string doesn't exceed $$$50$$$.

For each test case, output a separate line containing one non-negative integer $$$k$$$ — the number of letters which will be painted in red in a wonderful coloring.

NoteThe first test case contains the string from the statement. One of the wonderful colorings is shown in the figure. There's no wonderful coloring containing $$$3$$$ or more red letters because the total number of painted symbols will exceed the string's length.The string from the second test case can be painted as follows. Let's paint the first occurrence of each of the letters "c", "o", "e" in red and the second ones in green. Let's paint the letters "d", "f" in red and "r", "s" in green. So every letter will be painted in red or green, hence the answer better than $$$5$$$ doesn't exist.The third test case contains the string of distinct letters, so you can paint any set of characters in red, as long as the size of this set doesn't exceed half of the size of the string and is the maximum possible.The fourth test case contains a single letter which cannot be painted in red because there will be no letter able to be painted in green.The fifth test case contains a string of identical letters, so there's no way to paint more than one letter in red.

def calculate(chuoi)
  hash_ky_tu = Hash.new { |hash, key| hash[key] = 0 }
  (0...chuoi.length).each do |index|
    hash_ky_tu[chuoi[index]] += 1
  end

  lap_lai_3_lan = 0
  lap_lai_2_lan = 0
  lap_lai_1_lan = 0

  hash_ky_tu.values.each do |so_lan_lap_lai|
    case so_lan_lap_lai
    when 3
      lap_lai_3_lan += 1
    when 1
      lap_lai_1_lan += 1
    else
      lap_lai_2_lan += 1
    end
  end
  lap_lai_3_lan + lap_lai_2_lan + lap_lai_1_lan / 2
end

t = gets.to_i
t.times do
  chuoi = gets.chomp
  puts calculate(chuoi)
end


A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:  ai ≥ ai - 1 for all even i,  ai ≤ ai - 1 for all odd i > 1. For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.Can you make the array z-sorted?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array a. The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.

If it's possible to make the array a z-sorted print n space separated integers ai — the elements after z-sort. Otherwise print the only word "Impossible".

n = gets.to_i
a = gets.split(" ").map(&:to_i).sort
i = 0
j = n-1

b = []
while true do
  b << a[i]
  i += 1
  break if i > j
  b << a[j]
  j -= 1
  break if i > j
end

valid = true
n.times do |i|
  if (i+1).even?
    valid = false if b[i] < b[i-1]
  elsif (i+1).odd? && i > 0
    valid = false if b[i] > b[i-1]
  end
end

puts valid ? b.join(" ") : "Impossible"

n = gets.to_i
a = gets.split.map(&:to_i)
for i in 0..n-1
    if (i+1)%2==0 then printf "%d ", a.max; a.delete_at a.index(a.max);
    else printf "%d ", a.min; a.delete_at a.index(a.min); end
end

n = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
res = []
for i in 0..n[0] - 1 do
  if i == 0 or (i + 1) % 2 != 0
    res[i] = arr.min
  else
    res[i] = arr.max
  end
  arr.delete_at(arr.index(res[i]) || arr.length)
end
puts res.join(' ')

#!/usr/bin/env ruby

n = gets.to_i
inp = gets.split.map(&:to_i)
for i in 0..n-1
  if (i+1) % 2 == 0 then printf "%d ", inp.max; inp.delete_at inp.index(inp.max)
  else printf "%d ", inp.min; inp.delete_at inp.index(inp.min) end
end
puts

n = readline.to_i
arr = readline.split(' ').collect(&:to_i).sort
arr[0..(n / 2)].zip(arr[(n / 2 + 1)..-1]).flatten.compact.each_with_index do |num, ind|
  print " " if ind != 0
  print num
end
puts ""

a=gets.chomp.to_i
b=gets.chomp.split(" ")
0.upto(a-1) {|i| b[i]=b[i].to_i}
b.sort!
if a%2==0
0.upto (a/2-1) do |i|
printf "#{b[i]} #{b[a/2+i]} "
end
else
0.upto (a/2) do |i|
if i!=a/2
printf "#{b[i]} #{b[a/2+1+i]} "
else
printf "#{b[i]}"
end
end
end

gets
a = gets.split.map(&:to_i)
a.sort!
b = []
a.size.times do |i|
  if i.even?
    b << a.shift
  else
    b << a.pop
  end
end
puts b.join ' '

n=gets.to_i
a=gets.split(' ')
for i in 0..a.size-1
	a[i]=a[i].to_i
end
a=a.sort
l=0
r=a.size-1
ans=""
while l<=r
	ans+=" #{a[l]}"
	ans+=" #{a[r]}" if l<r
	l+=1
	r-=1
end
puts ans.strip

gets # ignore
sorted = gets.split(" ").map(&:to_i).sort
lo, hi = 0, sorted.length - 1

ret = []
while lo < hi
  ret << sorted[lo]
  ret << sorted[hi]

  lo += 1
  hi -= 1
end
ret << sorted[hi] if lo == hi

puts ret.join(" ")

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

if arr.length <= 1
  puts arr.join(" ")
  exit
end

len = arr.length
do_swap = len % 2 != 0

sorted = arr.sort

lo = 0
hi = len/2

ret = []
(0...(len/2)).each do
  ret << sorted[lo]
  ret << sorted[hi]

  lo += 1
  hi += 1
end

if do_swap
  tmp = ret[-1]
  ret[-1] = sorted[hi]
  ret << tmp
end

puts ret.join(" ")

n = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
res = []
for i in 0..n[0] - 1 do
  if i == 0 or (i + 1) % 2 != 0
    res[i] = arr.min
  else
    res[i] = arr.max
  end
  arr.delete_at(i)
end
puts res.join(' ')

n = readline.to_i
arr = readline.split(' ').collect(&:to_i).sort
puts arr
arr[0..(n / 2)].zip(arr[(n / 2 + 1)..-1]).flatten.compact.each_with_index do |num, ind|
  print " " if ind != 0
  print num
end
puts ""

gets # ignore
arr = gets.split(" ").map(&:to_i)
if arr.length <= 1
  puts "Impossible"
  exit 0
end

len = arr.length
do_swap = len % 2 != 0

sorted = arr.sort

lo = 0
hi = len/2

ret = []
(0...(len/2)).each do
  ret << sorted[lo]
  ret << sorted[hi]

  lo += 1
  hi += 1
end

if do_swap
  tmp = ret[-1]
  ret[-1] = arr[hi]
  ret << tmp
end

puts ret.join(" ")

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

if arr.length <= 1
  puts arr.join(" ")
  exit
end

len = arr.length
do_swap = len % 2 != 0

sorted = arr.sort

lo = 0
hi = len/2

ret = []
(0...(len/2)).each do
  ret << sorted[lo]
  ret << sorted[hi]

  lo += 1
  hi += 1
end

if do_swap
  tmp = ret[-1]
  ret[-1] = arr[hi]
  ret << tmp
end

puts ret.join(" ")

gets # ignore
sorted = gets.split(" ").map(&:to_i).sort
lo, hi = 0, sorted.length - 1

ret = []
while lo < hi
  ret << sorted[lo]
  ret << sorted[hi]

  lo += 1
  hi -= 1
end
ret << sorted[hi]

puts ret.join(" ")


Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.This time mr. Boosch plans to sign 2k laws. He decided to choose exactly two non-intersecting segments of integers from 1 to n of length k and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers a, b (1 ≤ a ≤ b ≤ n - k + 1, b - a ≥ k) and sign all laws with numbers lying in the segments [a; a + k - 1] and [b; b + k - 1] (borders are included).As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.

The first line contains two integers n and k (2 ≤ n ≤ 2·105, 0 < 2k ≤ n) — the number of laws accepted by the parliament and the length of one segment in the law list, correspondingly. The next line contains n integers x1, x2, ..., xn — the absurdity of each law (1 ≤ xi ≤ 109).

Print two integers a, b — the beginning of segments that mr. Boosch should choose. That means that the president signs laws with numbers from segments [a; a + k - 1] and [b; b + k - 1]. If there are multiple solutions, print the one with the minimum number a. If there still are multiple solutions, print the one with the minimum b.

NoteIn the first sample mr. Boosch signs laws with numbers from segments [1;2] and [4;5]. The total absurdity of the signed laws equals 3 + 6 + 1 + 6 = 16.In the second sample mr. Boosch signs laws with numbers from segments [1;2] and [3;4]. The total absurdity of the signed laws equals 1 + 1 + 1 + 1 = 4.

#author :Fuad Ashraful Mehmet
#date: 17th April 2020

n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
sum=Array.new(n)
rsum=Array.new(n)
bestl=Array.new(n)
bestr=Array.new(n)
astart=Array.new(n)
bstart=Array.new(n)
n.times do |i|
  if i<k
    sum[i]=(i>0?sum[i-1]:0)+a[i]
    rsum[n-i-1]=(i>0?rsum[n-i]:0)+a[n-i-1]
  else
    sum[i]=sum[i-1]+a[i]-a[i-k]
    rsum[n-i-1]=rsum[n-i]+a[n-i-1]-a[n-i+k-1]
  end

  if i==0
    bestr[n-1]=rsum[n-1]
    bstart[n-1]=n-1
  else
    if bestr[n-i] > rsum[n-i-1]
      bestr[n-i-1] = bestr[n-i]
      bstart[n-i-1] = bstart[n-i]
    else
      bestr[n-i-1] = rsum[n-i-1]
      bstart[n-i-1] = n-i-1
    end
  end
end

max=0
besta=0
bestb=0
for i in k-1..n-k-1
  s = sum[i]+bestr[i+1]
  if max < s
    max = s
    besta=i
    bestb=bstart[i+1]
  end
end

puts "#{besta+2-k} #{bestb+1}"

n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
sum=Array.new(n)
rsum=Array.new(n)
bestl=Array.new(n)
bestr=Array.new(n)
astart=Array.new(n)
bstart=Array.new(n)
n.times do |i|
  if i<k
    sum[i]=(i>0?sum[i-1]:0)+a[i]
    rsum[n-i-1]=(i>0?rsum[n-i]:0)+a[n-i-1]
  else
    sum[i]=sum[i-1]+a[i]-a[i-k]
    rsum[n-i-1]=rsum[n-i]+a[n-i-1]-a[n-i+k-1]
  end

  if i==0
    bestr[n-1]=rsum[n-1]
    bstart[n-1]=n-1
  else
    if bestr[n-i] > rsum[n-i-1]
      bestr[n-i-1] = bestr[n-i]
      bstart[n-i-1] = bstart[n-i]
    else
      bestr[n-i-1] = rsum[n-i-1]
      bstart[n-i-1] = n-i-1
    end
  end
end

max=0
besta=0
bestb=0
for i in k-1..n-k-1
  s = sum[i]+bestr[i+1]
  if max < s
    max = s
    besta=i
    bestb=bstart[i+1]
  end
end

#p sum
#p rsum
#p bestr
#p bstart
puts "#{besta+2-k} #{bestb+1}"

def add(heap, x)
	heap.push(x)
	pos = heap.length-1
	while pos != 0
		parent_pos = (pos-1)/2
		break if (heap[parent_pos] <=> x) >= 0
		heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos]
		pos  = parent_pos
	end
end
def remove(heap, pos, heap_pos)
	x = heap.pop
	return if heap.length == 0
	heap[pos] = x
	heap_pos[-heap[pos][1]] = pos
	while true
		child_pos = 2*pos+1
		break if child_pos >= heap.length
		if child_pos+1 < heap.length and (heap[child_pos+1] <=> heap[child_pos]) == -1
			child_pos = child_pos+1
		end
		break if (heap[pos] <=> heap[child_pos]) >= 0
		heap[child_pos], heap[pos] = heap[pos], heap[child_pos]
		heap_pos[-heap[pos][1]] = pos
		heap_pos[-heap[child_pos][1]] = child_pos
	end
end

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
heap = []
(k..n-k).each {|i| add(heap, [sums[i], -i]) }
best_score = 0
heap_pos = {}
heap.each_with_index do |item, i|
	sum, key = item
	heap_pos[-key] = i
end
best_indices = nil
(0..n-2*k).each do |i|
	value, j = heap[0]
	score = sums[i] + value
	if score > best_score
		best_indices = [i+1, -j+1]
		best_score = score
	end
	remove(heap, heap_pos[i+k], heap_pos)
end
puts best_indices.join(' ')

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
left, right = 0, k
best_score = sums[left] + sums[right]
best_left, best_right = left, right
while right != n-k
	right += 1
	(right..n-k).each do |seek|
		right = seek if sums[seek] > sums[right]
	end
	left += 1
	(left..right-k).each do |seek|
		left = seek if sums[seek] > sums[left]
	end
	score = sums[left]+sums[right]
	if score > best_score
		best_score, best_left, best_right = score, left, right
	end
end
puts '%d %d' % [best_left+1, best_right+1]
puts best_score

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
a, b = 0, k
(1..n-k).each do |i|
	sum = sums[i]
	if sum > sums[a] and (i-b).abs >= k
		if (i-a).abs >= k and (sums[b] < sums[a] or (sums[b] == sums[a] and b > a))
			b = i
		else
			a = i
		end
	elsif sum > sums[b] and (i-a).abs >= k
		b = i
	end
end
puts '%d %d' % [[a, b].min + 1, [a, b].max + 1]

def add(heap, x)
	heap.push(x)
	pos = heap.length-1
	while pos != 0
		parent_pos = (pos-1)/2
		break if (heap[parent_pos] <=> x) >= 0
		heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos]
		pos  = parent_pos
	end
end
def remove(heap, pos, heap_pos)
	x = heap.pop
	return if pos == heap.length
	heap[pos] = x
	heap_pos[-heap[pos][1]] = pos
	while true
		child_pos = 2*pos+1
		break if child_pos >= heap.length
		if child_pos+1 < heap.length and (heap[child_pos] <=> heap[child_pos+1]) == -1
			child_pos = child_pos+1
		end
		break if (heap[pos] <=> heap[child_pos]) >= 0
		heap[child_pos], heap[pos] = heap[pos], heap[child_pos]
		heap_pos[-heap[pos][1]] = pos
		heap_pos[-heap[child_pos][1]] = child_pos
	end
end

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
heap = []
(k..n-k).each {|i| add(heap, [sums[i], -i]) }
best_score = 0
heap_pos = {}
heap.each_with_index do |item, i|
	sum, key = item
	heap_pos[-key] = i
end
best_a, best_b = nil, nil
(0..n-2*k).each do |a|
	sum, b = heap[0]
	score = sums[a] + sum
	if score > best_score
		best_a, best_b = a+1, -b+1
		best_score = score
	end
	remove(heap, heap_pos[a+k], heap_pos)
end
puts '%d %d' % [best_a, best_b]
#puts best_score

def add(heap, x)
	heap.push(x)
	pos = heap.length-1
	while pos != 0
		parent_pos = (pos-1)/2
		break if (heap[parent_pos] <=> x) >= 0
		heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos]
		pos  = parent_pos
	end
end
def remove(heap)
	x = heap.pop
	return if heap.length == 0
	heap[0] = x
	pos = 0
	while true
		child_pos = 2*pos+1
		break if child_pos >= x.length
		if child_pos+1 < x.length and heap[child_pos+1] > heap[child_pos]
			child_pos = child_pos+1
		end
		break if (heap[pos] <=> heap[child_pos]) >= 0
		heap[child_pos], heap[pos] = heap[pos], heap[child_pos]
	end
end

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
heap = []
(k..n-k).each {|i| add(heap, [sums[i], -i]) }
best_score = 0
best_indices = nil
(0..n-2*k).each do |i|
	score, j = heap[0]
	if score > best_score
		best_indices = [i+1, -j+1]
		best_score = score
	end
end
puts best_indices.join(' ')

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
a, b = 0, k
(k+1..n-k).each do |i|
	sum = sums[i]
	if sum > sums[a] and i-b >= k
		if sums[b] < sums[a] and i-a >= k
			b = i
		else
			a = i
		end
	elsif sum > sums[b] and i-a >= k
		b = i
	end
end
puts '%d %d' % [[a, b].min + 1, [a, b].max + 1]

def add(heap, x)
	heap.push(x)
	pos = heap.length-1
	while pos != 0
		parent_pos = (pos-1)/2
		break if (heap[parent_pos] <=> x) >= 0
		heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos]
		pos  = parent_pos
	end
end
def remove(heap, pos, heap_pos)
	x = heap.pop
	return if pos == heap.length
	heap[pos] = x
	heap_pos[-heap[pos][1]] = pos
	while true
		child_pos = 2*pos+1
		break if child_pos >= heap.length
		if child_pos+1 < heap.length and (heap[child_pos] <=> heap[child_pos+1]) == -1
			child_pos = child_pos+1
		end
		break if (heap[pos] <=> heap[child_pos]) >= 0
		heap[child_pos], heap[pos] = heap[pos], heap[child_pos]
		heap_pos[-heap[pos][1]] = pos
		heap_pos[-heap[child_pos][1]] = child_pos
	end
end

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
heap = []
(k..n-k).each {|i| add(heap, [sums[i], -i]) }
best_score = 0
heap_pos = {}
heap.each_with_index do |item, i|
	sum, key = item
	heap_pos[-key] = i
end
best_a, best_b = nil, nil
(0..n-2*k).each do |a|
	sum, b = heap[0]
	score = sums[a] + sum
	if score > best_score
		best_a, best_b = a+1, -b+1
		best_score = score
	end
	remove(heap, heap_pos[a+k], heap_pos)
end
puts '%d %d' % [best_a, best_b]
puts best_score

def add(heap, x)
	heap.push(x)
	pos = heap.length-1
	while pos != 0
		parent_pos = (pos-1)/2
		break if (heap[parent_pos] <=> x) >= 0
		heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos]
		pos  = parent_pos
	end
end
def remove(heap, pos, heap_pos)
	x = heap.pop
	return if heap.length == 0
	heap[pos] = x
	heap_pos[-heap[pos][1]] = pos
	while true
		child_pos = 2*pos+1
		break if child_pos >= heap.length
		if child_pos+1 < heap.length and (heap[child_pos] <=> heap[child_pos+1]) == -1
			child_pos = child_pos+1
		end
		break if (heap[pos] <=> heap[child_pos]) >= 0
		heap[child_pos], heap[pos] = heap[pos], heap[child_pos]
		heap_pos[-heap[pos][1]] = pos
		heap_pos[-heap[child_pos][1]] = child_pos
	end
end

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
heap = []
(k..n-k).each {|i| add(heap, [sums[i], -i]) }
best_score = 0
heap_pos = {}
heap.each_with_index do |item, i|
	sum, key = item
	heap_pos[-key] = i
end
best_indices = nil
(0..n-2*k).each do |i|
	value, j = heap[0]
	score = sums[i] + value
	if score > best_score
		best_indices = [i+1, -j+1]
		best_score = score
	end
	remove(heap, heap_pos[i+k], heap_pos)
end
puts best_indices.join(' ')

def add(heap, x)
	heap.push(x)
	pos = heap.length-1
	while pos != 0
		parent_pos = (pos-1)/2
		break if (heap[parent_pos] <=> x) >= 0
		heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos]
		pos  = parent_pos
	end
end
def remove(heap, pos, heap_pos)
	x = heap.pop
	return if heap.length == 0
	heap[pos] = x
	heap_pos[-heap[pos][1]] = pos
	while true
		child_pos = 2*pos+1
		break if child_pos >= heap.length
		if child_pos+1 < heap.length and (heap[child_pos] <=> heap[child_pos+1]) == -1
			child_pos = child_pos+1
		end
		break if (heap[pos] <=> heap[child_pos]) >= 0
		heap[child_pos], heap[pos] = heap[pos], heap[child_pos]
		heap_pos[-heap[pos][1]] = pos
		heap_pos[-heap[child_pos][1]] = child_pos
	end
end

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
heap = []
(k..n-k).each {|i| add(heap, [sums[i], -i]) }
best_score = 0
heap_pos = {}
heap.each_with_index do |item, i|
	sum, key = item
	heap_pos[-key] = i
end
best_a, best_b = nil, nil
(0..n-2*k).each do |a|
	sum, b = heap[0]
	score = sums[a] + sum
	if score > best_score
		best_a, best_b = a+1, -b+1
		best_score = score
	end
	remove(heap, heap_pos[a+k], heap_pos)
end
puts '%d %d' % [best_a, best_b]
puts best_score

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
best = [[sum, 0]]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
	if sum <= best[-1][0]
		best.push(best[-1])
	else
		best.push([sum, i-k+1])
	end
end
left, right = 0, k
(k+1..n-k).each do |i|
	if best[i-k][0] + sums[i] > sums[left] + sums[right]
		left, right = best[i-k][1], i
	end
end
puts '%d %d' % [left+1, right+1]
puts sums[left] + sums[right]

def add(heap, x)
	heap.push(x)
	pos = heap.length-1
	while pos != 0
		parent_pos = (pos-1)/2
		break if (heap[parent_pos] <=> x) >= 0
		heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos]
		pos  = parent_pos
	end
end
def remove(heap, pos, heap_pos)
	x = heap.pop
	return if heap.length == 0
	heap[pos] = x
	heap_pos[-heap[pos][1]] = pos
	while true
		child_pos = 2*pos+1
		break if child_pos >= heap.length
		if child_pos+1 < heap.length and (heap[child_pos] <=> heap[child_pos+1]) == -1
			child_pos = child_pos+1
		end
		break if (heap[pos] <=> heap[child_pos]) >= 0
		heap[child_pos], heap[pos] = heap[pos], heap[child_pos]
		heap_pos[-heap[pos][1]] = pos
		heap_pos[-heap[child_pos][1]] = child_pos
	end
end

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
heap = []
(k..n-k).each {|i| add(heap, [sums[i], -i]) }
best_score = 0
heap_pos = {}
heap.each_with_index do |item, i|
	sum, key = item
	heap_pos[-key] = i
end
best_a, best_b = nil, nil
(0..n-2*k).each do |a|
	sum, b = heap[0]
	score = sums[a] + sum
	if score > best_score
		best_a, best_b = a+1, -b+1
		best_score = score
	end
	remove(heap, heap_pos[a+k], heap_pos)
end
puts '%d %d' % [best_a, best_b]
#puts best_score

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
best_score = -1
best_left, best_right = -1, -1
left, right = nil, k-1
while right != n-k
	left = right-k+1
	right += 1
	(right..n-k).each do |seek|
		right = seek if sums[seek] > sums[right]
	end
	(left..right-k).each do |seek|
		left = seek if sums[seek] > sums[left]
	end
	break if 2*[sums[left], sums[right]].max <= best_score
	score = sums[left]+sums[right]
	if score > best_score
		best_score, best_left, best_right = score, left, right
	end
end
puts '%d %d' % [best_left+1, best_right+1]

def add(heap, x)
	heap.push(x)
	pos = heap.length-1
	while pos != 0
		parent_pos = (pos-1)/2
		break if (heap[parent_pos] <=> x) >= 0
		heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos]
		pos  = parent_pos
	end
end
def remove(heap)
	x = heap.pop
	return if heap.length == 0
	heap[0] = x
	pos = 0
	while true
		child_pos = 2*pos+1
		break if child_pos >= heap.length
		if child_pos+1 < heap.length and (heap[child_pos+1] <=> heap[child_pos]) == -1
			child_pos = child_pos+1
		end
		break if (heap[pos] <=> heap[child_pos]) >= 0
		heap[child_pos], heap[pos] = heap[pos], heap[child_pos]
	end
end

n, k = STDIN.readline.split.map {|s| s.to_i }
values = STDIN.readline.split.map {|s| s.to_i }
sum = values[0..k-1].inject(:+)
sums = [sum]
(k..n-1).each do |i|
	sum += values[i] - values[i-k]
	sums.push(sum)
end
heap = []
(k..n-k).each {|i| add(heap, [sums[i], -i]) }
best_score = 0
best_indices = nil
(0..n-2*k).each do |i|
	value, j = heap[0]
	score = sums[i] + value
	if score > best_score
		best_indices = [i+1, -j+1]
		best_score = score
	end
	remove(heap)
end
puts best_indices.join(' ')


Two players play a game.Initially there are $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $$$n - 1$$$ turns are made. The first player makes the first move, then players alternate turns.The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.You want to know what number will be left on the board after $$$n - 1$$$ turns if both players make optimal moves.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of numbers on the board. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$).

Print one number that will be left on the board.

NoteIn the first sample, the first player erases $$$3$$$ and the second erases $$$1$$$. $$$2$$$ is left on the board.In the second sample, $$$2$$$ is left on the board regardless of the actions of the players.

# cook your code here

n = gets.to_i

arr = gets.split.map { |x| x.to_i }

arr = arr.sort!

puts arr[(n-1)/2]

n = gets.to_i
as = gets.split.map(&:to_i)
puts as.sort[(n.to_f/2).ceil-1]

n = gets.strip.to_i
a = gets.strip.split.map(&:to_i).sort
x = n / 2
x -= 1 if n.even?
puts a[x]

# -*- coding: utf-8 -*-

n = gets.to_i
ar = gets.split.map(&:to_i)
ar.sort!
if n.odd?
    puts ar[n/2]
else
    puts ar[n/2 - 1]
end

x = gets.chomp.to_i;
a = gets.strip.split(' ').map(&:to_i);

a = a.sort;
for i in 0 ... (x - 1) / 2
	a[i] = 0;
	a[a.length - i - 1] = 0;
end

a.each do |num|
	if num != 0
		puts num;
		exit;
	end

end

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

n = r[].first

arr = r[].sort

p arr[(n - 1) / 2]

n = gets.to_i
puts gets.split.map(&:to_i).sort[(n - 1) / 2]

n = gets.strip.to_i
a = gets.strip.split.map(&:to_i).sort
puts a[n / 2]

x = gets.chomp.to_i;
a = gets.strip.split(' ').map(&:to_i);

for i in 0 ... x / 2
	a[i] = 0;
	a[a.length - i - 1] = 0;
end

a.each do |num|
	if num.nonzero?
		puts num;
		exit;
	end

end

x = gets.chomp.to_i;
a = gets.strip.split(' ').map(&:to_i);

a = a.sort;
for i in 0 ... x / 2
	a[i] = 0;
	a[a.length - i - 1] = 0;
end

a.each do |num|
	if num != 0
		puts num;
		exit;
	end

end


"You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it?

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For every test case print one non-negative integer — the answer to the problem.

NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs.

T = gets.to_i

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

  ans = 0
  counter = Hash.new(0)

  a.each do |x|
    l = x.to_s(2).size
    ans += counter[l]
    counter[l] += 1
  end

  puts ans
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i)
    hash = Hash.new(0)
    a.each do |i|
        ii = i.to_s(2).size
        hash[ii] += 1
    end
    count = 0
    hash.each do |i,j|
        if j >= 2
            ans = (j * (j-1)) / 2
            count += ans
        end
    end
    puts count
end


As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.Let's consider a set of functions of the following form:  Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.

The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.

Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.

r = []
gets.to_i.times { |i|
ar = gets.split(' ').map{ |x| x.to_i }
if ar[0] != 0 then  r.push(Rational(-ar[1], ar[0])); end
}

puts r.uniq.size

#!/usr/bin/ruby
require 'set'
n = $stdin.gets.to_i
s = Set.new
n.times do |i|
  k, b = *$stdin.gets.split.map(&:to_i)
  if k != 0
    s.add -b.to_r/k
  end
end
puts s.size

#!/usr/bin/ruby
n = $stdin.gets.to_i
h = Hash.new { |h, k| h[k] = [] }
n.times do
  k, b = *$stdin.gets.split.map(&:to_i)
  if k != 0
    h[-b.to_r/k].push k
  end
end
ans = 0
h.values.each do |a|
  if a.inject(0, :+) != 0
    ans += 1
  end
end
puts ans

#!/usr/bin/ruby
n = $stdin.gets.to_i
h = Hash.new { |h, k| h[k] = [] }
n.times do
  k, b = *$stdin.gets.split.map(&:to_i)
  if k != 0
    h[b.to_r/k].push k
  end
end
ans = 0
h.values.each do |a|
  x = 0
  y = 0
  a.each do |k|
    x += k
  end
  if x != 0
    ans += 1
  end
end
puts ans