This problem is same as the next one, but has smaller constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 50$$$) — the number of electric poles. Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \le x_i, y_i \le 10^4$$$) — the coordinates of the poles. It is guaranteed that all of these $$$n$$$ points are distinct.

Print a single integer — the number of pairs of wires that are intersecting.

NoteIn the first example:  In the second example:  Note that the three poles $$$(0, 0)$$$, $$$(0, 2)$$$ and $$$(0, 4)$$$ are connected by a single wire.In the third example:

# coding: utf-8
n = readline.to_i
poles = (0...n).map { |_| readline.split.map(&:to_i) }

def c2(n)
  n * (n-1) / 2
end

lines = {}
lines.default = 0
parallels = {}
parallels.default = 0
for i in 0...n do
  x1, y1 = poles[i]
  for j in i+1...n do
    x2, y2 = poles[j]
    a = y1 - y2
    b = x2 - x1
    if a < 0 or (a == 0 and b < 0)
      a = -a
      b = -b
    end
    d = a.gcd b
    a /= d
    b /= d
    c = a*x1 + b*y1
    line = [a, b, c]
    STDERR.print "(#{x1},#{y1})—(#{x2},#{y2}): #{a}x+#{b}y+#{c}=0\n"
    lines[line] += 1
    parallels[[a, b]] += 1 if lines[line] == 1
  end
end

r = c2(lines.length)
parallels.values.each { |x| r -= c2(x) }
p r

n = readline.to_i
poles = (0...n).map { |_| readline.split.map(&:to_i) }

def line_x(x1, y1, x2, y2)
  if y1 == y2
    [nil, nil]
  else
    slope = Rational(x1-x2, y1-y2)
    [slope, x1 - slope * y1]
  end
end

def c2(n)
  n * (n-1) / 2
end

lines = {}
lines.default = 0
parallels = {}
parallels.default = 0
for i in 0...n do
  x1, y1 = poles[i]
  for j in i+1...n do
    x2, y2 = poles[j]
    sx, lx = line_x(x1, y1, x2, y2)
    sy, ly = line_x(y1, x1, y2, x2)
    line = [sx, lx, ly]
    lines[line] += 1
    parallels[[sx,sy]] += 1 if lines[line] == 1
  end
end

r = c2(lines.length)
parallels.values.each { |x| r -= c2(x) }
p r

n = readline.to_i
poles = (0...n).map { |_| readline.split.map(&:to_i) }

def c2(n)
  n * (n-1) / 2
end

lines = {}
lines.default = 0
parallels = {}
parallels.default = 0
for i in 0...n do
  x1, y1 = poles[i]
  for j in i+1...n do
    x2, y2 = poles[j]
    a = y1 - y2
    b = x2 - x1
    d = a.gcd b
    a /= d
    b /= d
    c = a*x1 + b*y1
    line = [a, b, c]
    lines[line] += 1
    parallels[[a, b]] += 1 if lines[line] == 1
  end
end

r = c2(lines.length)
parallels.values.each { |x| r -= c2(x) }
p r

n = readline.to_i
poles = (0...n).map { |_| readline.split.map(&:to_i) }

def line_x(x1, y1, x2, y2)
  if y1 == y2
    [nil, nil]
  else
    slope = Rational((x1-x2)/(y1-y2))
    [slope, x1 - slope * y1]
  end
end

def c2(n)
  n * (n-1) / 2
end

lines = {}
lines.default = 0
parallels = {}
parallels.default = 0
for i in 0...n do
  x1, y1 = poles[i]
  for j in i+1...n do
    x2, y2 = poles[j]
    sx, lx = line_x(x1, y1, x2, y2)
    sy, ly = line_x(y1, x1, y2, x2)
    line = [sx, sy, lx, ly]
    lines[line] += 1
    parallels[[sx, sy]] += 1 if lines[line] == 1
  end
end

r = c2(lines.length)
parallels.values.each { |x| r -= c2(x) }
p r


Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are $$$n$$$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $$$a_1, a_2, \dots, a_n$$$. Leon has learned three abilities which will help him to dry and water the soil.  Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$1, 2, \dots, i$$$ by $$$1$$$.  Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$i, i + 1, \dots, n$$$ by $$$1$$$.  Increase the level of moisture of all trees by $$$1$$$. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $$$0$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$)  — the number of test cases. The description of $$$t$$$ test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the initial levels of trees moisture.  It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.

For each test case output a single integer — the minimum number of actions. It can be shown that the answer exists.

NoteIn the first test case it's enough to apply the operation of adding $$$1$$$ to the whole array $$$2$$$ times. In the second test case you can apply the operation of decreasing $$$4$$$ times on the prefix of length $$$3$$$ and get an array $$$6, 0, 3$$$. After that apply the operation of decreasing $$$6$$$ times on the prefix of length $$$1$$$ and $$$3$$$ times on the suffix of length $$$1$$$. In total, the number of actions will be $$$4 + 6 + 3 = 13$$$. It can be shown that it's impossible to perform less actions to get the required array, so the answer is $$$13$$$.

gets.to_i.times do
    n = gets.to_i
    a = gets.chomp.split.map(&:to_i)
    ans = 0
    cur = a[0]
    down = 0
    (1..n-1).each do |i|
        ans += [cur - (a[i] - down), (a[i] - down) - cur].max
        down += [(a[i] - down) - cur, 0].max
        cur = a[i] - down
    end
    puts ans + (cur > 0 ? cur : -cur)

end

gets.to_i.times do
    n = gets.to_i
    a = gets.chomp.split.map(&:to_i)
    ans = 0
    cur = a[0]
    down = 0
    for i in 1..n-1
        ans += [cur - (a[i] - down), (a[i] - down) - cur].max
        down += [(a[i] - down) - cur, 0].max
        cur = a[i] - down
    end
    puts ans + (cur > 0 ? cur : -cur)

end

gets.to_i.times do
    n = gets.to_i
    a = gets.chomp.split.map(&:to_i)
    ans = 0
    cur = a[0]
    down = 0
    for i in 1..n-1
        if(cur >= a[i] - down)
            ans += cur - (a[i] - down)
            cur = a[i] - down
        else
            ans += (a[i] - down) - cur
            down += (a[i] - down) - cur
        end
    end
    ans += cur > 0 ? cur : -cur

    puts ans
end


Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $$$0$$$ or $$$1$$$. For example, $$$1\,010\,111$$$ is a binary decimal, while $$$10\,201$$$ and $$$787\,788$$$ are not.Given a number $$$n$$$, you are asked to represent $$$n$$$ as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$), denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$), denoting the number to be represented.

For each test case, output the smallest number of binary decimals required to represent $$$n$$$ as a sum.

NoteIn the first test case, $$$121$$$ can be represented as $$$121 = 110 + 11$$$ or $$$121 = 111 + 10$$$.In the second test case, $$$5$$$ can be represented as $$$5 = 1 + 1 + 1 + 1 + 1$$$.In the third test case, $$$1\,000\,000\,000$$$ is a binary decimal itself, thus the answer is $$$1$$$.

$n = gets.chomp.to_i
$n.times do
  s = gets.chomp.to_i
  ans = 0
  while s > 0
    ans = [ans, s % 10].max
    s = s / 10
  end
  puts ans
end

gets.to_i.times do |i|
  puts gets.chomp.chars.max
end


A rectangle with its opposite corners in $$$(0, 0)$$$ and $$$(w, h)$$$ and sides parallel to the axes is drawn on a plane.You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.Your task is to choose three points in such a way that:   exactly two of them belong to the same side of a rectangle;  the area of a triangle formed by them is maximum possible. Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$w$$$ and $$$h$$$ ($$$3 \le w, h \le 10^6$$$) — the coordinates of the corner of a rectangle. The next two lines contain the description of the points on two horizontal sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$x_1 < x_2 < \dots < x_k$$$ ($$$0 < x_i < w$$$) — the $$$x$$$ coordinates of the points in the ascending order. The $$$y$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$h$$$. The next two lines contain the description of the points on two vertical sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$y_1 < y_2 < \dots < y_k$$$ ($$$0 < y_i < h$$$) — the $$$y$$$ coordinates of the points in the ascending order. The $$$x$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$w$$$. The total number of points on all sides in all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the doubled maximum area of a triangle formed by such three points that exactly two of them belong to the same side.

area = ->(x1, y1, x2, y2, x3, y3) {
  (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)).abs
}

gets.to_i.times do
  w, h = gets.split.map(&:to_i)
  as = gets.split.drop(1).map { |x| [x.to_i, 0] }
  bs = gets.split.drop(1).map { |x| [x.to_i, h] }
  cs = gets.split.drop(1).map { |x| [0, x.to_i] }
  ds = gets.split.drop(1).map { |x| [w, x.to_i] }
  all = as + bs + cs + ds
  p([as, bs, cs, ds].map do |s|
    x1, y1 = s[0]
    x2, y2 = s[-1]
    all.map { |x3, y3| area[x1, y1, x2, y2, x3, y3] }.max
  end.max)
end

input = STDIN.read.split("\n")

(0..input.shift.to_i - 1).to_a.reverse.each do |i|
  wh = input.shift.split(' ').map(&:to_i)
  h1a = input.shift.split(' ').map(&:to_i)
  h2a = input.shift.split(' ').map(&:to_i)
  w1a = input.shift.split(' ').map(&:to_i)
  w2a = input.shift.split(' ').map(&:to_i)

  h1 = h1a[h1a[0]] - h1a[1]
  h2 = h2a[h2a[0]] - h2a[1]
  maxh = [h1, h2].max

  w1 = w1a[w1a[0]] - w1a[1]
  w2 = w2a[w2a[0]] - w2a[1]
  maxw = [w1, w2].max

  puts [maxw * wh[0], maxh * wh[1]].max
end


Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.

The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house.

Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.

n, m = gets.split(' ').map(&:to_i)
ar = gets.split(' ').map(&:to_i)
puts ar.each_cons(2).select{|x,y| x>y}.count * n + ar[-1] - 1

#!/usr/bin/ruby
n=gets.to_i
p ([0]+gets.split.map{|e|e.to_i-1}).each_cons(2).map{|a,b|b-a<0 ? b+n-a : b-a}.reduce(:+)

line1 = gets.chomp.split(" ")
n = line1[0].to_i
m = line1[1].to_i
task = gets.chomp.split(" ").map {|x| x.to_i}
pos = 1
ans = 0
for t in task
  if t > pos
    ans += t-pos
  elsif t < pos
    ans += t+n-pos
  end
  pos = t
end
puts ans

def get_i
  return gets.split(' ').map(&:to_i)
end
n,m=get_i
a=get_i.unshift(1)
ans=0
for i in 1..m do
  ans+=(a[i]-a[i-1]+n)%n
end
puts ans

n, m = gets.split.map { |i| i.to_i }
a = gets.split.map { |i| i.to_i }

s = a[0] - 1
for i in 1..(a.count - 1) do
  y = a[i] - a[i - 1]
  if y < 0 then y = n + y end
  s += y
end

puts s

#!/usr/bin/ruby1.9

n, m = STDIN.readline.split.collect {|s| s.to_i }
tasks = STDIN.readline.split.collect {|s| s.to_i }

total = 0
pos = 1
tasks.each do |next_pos|
	if next_pos >= pos
		total += next_pos - pos
	else
		total += (n - pos) + 1 + (next_pos - 1)
	end
	pos = next_pos
end
puts total

hn, dn = gets.split.map(&:to_i)
deals = gets.split.map(&:to_i)
time = 0
curh = 1
deals.each {|d|
	time += (d-curh)%hn
	curh = d
}
puts time

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

input = string_to_int(gets.chomp)
dest = string_to_int(gets.chomp)

walk = dest[0] - 1

for i in 0...dest.length - 1
	if dest[i] <= dest[i+1]
		walk += dest[i+1] - dest[i]
	else
		walk += input[0] + dest[i+1] - dest[i]
	end
end

puts walk

r = -> { gets.split.map(&:to_i )}
n,m = r[]
v = r[]
v.unshift(1)
s = 0
(1..m).each do |x|
    if v[x - 1] < v[x]
        s += v[x] - v[x - 1]
    elsif v[x - 1] > v[x]
        s += n - v[x - 1] + v[x]
    end
end
p s

n,m=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i)
y,ans,x=1,0,0
a.each do |i|
	ans+=1 if i<y
	y=i
	x=i
end
puts ans*n+x-1

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

prev = 1
s = 0
a.each do |el|
  if el < prev
    s += (el - prev + n)
  else
    s += el - prev
  end
  prev = el
end
puts s

n, m = gets.split.map &:to_i
arr = gets.split.map &:to_i
moves = 0
prev = 1
arr.each do |item|
  if item >= prev
    moves += item - prev
    prev = item
  else
    moves += n - prev + item
    prev = item
  end
end
puts moves

n,m = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
res = arr[0]-1
for i in 1...m
  if arr[i] < arr[i-1]
    res += n - (arr[i] - arr[i-1]).abs
  else
    res += arr[i] - arr[i-1];
  end
end

puts res

n, m = gets.chomp.split(/ /).map(&:to_i)
tasks = gets.chomp.split(/ /).map(&:to_i)
ans = 0
prev_task = 0
(0...m).each do |task|
    current_task = tasks[task]
    if prev_task == 0
        ans += current_task
    else
        if current_task != prev_task
            if current_task < prev_task
                ans += (n - prev_task) + current_task
            else
                ans += current_task - prev_task
            end
        end
    end
    prev_task = current_task
end
puts ans - 1

n,m=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i-1}

ans=x[0]
(m-1).times{|i|
	if x[i+1]>=x[i] then
		ans=ans+x[i+1]-x[i]
	else
		ans=ans+x[i+1]+n-x[i]
	end
}
puts ans

s = gets.split.map { |e| e.to_i  }
s2 = gets.split.map { |e| e.to_i  }
n = s[0]
m = s[1]
x = m[0]
c = 0
for i in s2
	if i < x
		c +=1
	end
	x = i
end
puts (c * n) + s2[m-1] - 1

n,m = gets.split(" ").map { |x| x.to_i }
a = gets.split(" ").map { |x| x.to_i }
res = 0
xprev = 1
a.each do |x|
  if xprev > x then
    res += n
  end
  res += x - xprev
  xprev = x
end
puts res

input = gets.chomp
num = input.split
n = Integer(num[0])
m = Integer(num[1])
input2 = gets.chomp
nums = input2.split
a = Array.new
for i in 0...m
    a[i] = Integer(nums[i])
end

b = Array.new
b[0] = a[0]
for i in 0...m-1
    if a[i+1] != a[i]
        b.push(a[i+1])
    end
end
time = 0
l = b.length
for i in 0...l-1
    if b[i+1] < b[i]
        time += 1
    end
end

puts time * n - 1 + b[l-1]

nm = gets.chomp
nm = nm.split
houses = nm[0].to_i
tasks = nm[1].to_i
each_task = gets.chomp
each_task = each_task.split

hours = 0
position = 1
for i in (0..each_task.size-1)
	if position < each_task[i].to_i
		hours += (each_task[i].to_i - position)
		position = each_task[i].to_i
	elsif position > each_task[i].to_i
		hours += (houses - position) + each_task[i].to_i
		position = each_task[i].to_i
	end
end

print hours

n,m = gets.split(" ").map(&:to_i)
tasks = gets.split(" ").map(&:to_i)
cost = 0
current = 1
tasks.each do |a|
	if a > current
		cost += a - current

		current = a
	elsif a < current
		cost += (n - current) + a
		current = a
	end
end
puts cost

n, m = gets.split.map &:to_i
a = gets.split.map &:to_i
s = 0
p = 1

for i in (0..m-1)
  a[i] < p ? s += n - p + a[i] : s += a[i] - p
  p = a[i]
end
puts s

#!/usr/bin/env ruby

n,m = gets.split.map(&:to_i)
x = gets.split.map(&:to_i)
now = 1
ans = 0
x.each do |p|
  if now <= p
    ans += p - now
  else
    ans += p + n - now
  end
  now = p
end
puts ans

n, m = gets.strip.split.map(&:to_i)
a = gets.strip.split.map(&:to_i)
now = 1
dis = 0
a.each do |x|
  if x < now
    dis += (n - (now - x))
  else
    dis += x - now
  end
  now = x
end
puts dis

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

curr = 1
puts(
  gets.split(' ').map(&:to_i).inject(0) do |result, x|
    c = curr
    curr = x
    result + (x >= c ? x - c : n - c + x)
  end
)

n, m = gets.chomp.split.map { |x| x.to_i }
h = [1].concat(gets.chomp.split.map { |x| x.to_i })
count = 0
for i in 1..m
  if h[i] > h[i - 1]
    count += h[i] - h[i - 1]
  elsif h[i] < h[i - 1]
    count += n - h[i - 1] + h[i]
  end
end
puts count

r = gets.split(" ")[0].to_i
s = gets.split(" ").map { |i| i.to_i }

b = 1
res = 0
s.each do |i|
	if b < i
		res += (i-b)
	elsif b > i
		res += (r-b+i)
	end
	b = i
end

puts res

def read_line
	line = gets.chomp.split(' ')
	line.map { |elem| elem.to_i }
end

def distance(a, b, n)
	return b - a if a <= b
	n - a + 1 + b - 1
end

n, m = read_line
a = read_line
current = 1
res = 0
a.each do |after|
	res += distance(current, after, n)
	current = after
end

puts res

# f = File.new('test1.txt', 'r')
f = STDIN
while s = f.gets
  n, m = s.split.map(&:to_i)
  arr = f.gets.split.map(&:to_i)
  ans, start = 0, 1
  arr.each do |e|
    if e >= start
      ans += e - start
    else
      ans += n - start + e
    end
    start = e
  end
  puts ans
end
f.close

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

input = string_to_int(gets.chomp)
dest = string_to_int(gets.chomp)

walk = dest[0] - 1

for i in 0...dest.length - 1
	if dest[i] < dest[i+1]
		walk += dest[i+1] - dest[i]
	else
		walk += input[0] + dest[i+1] - dest[i]
	end
end

puts walk

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

input = string_to_int(gets.chomp)
dest = string_to_int(gets.chomp)

house_no = 0
houses = Array.new(input[0]){|house_no| house_no+1}
walk = 0

j = 0
for i in 0...dest.length
	while houses[j] != dest[i]
		if j > dest.length - 1
			j = 0
			walk += 1
		else
			j += 1
			walk += 1
		end
	end
end

puts walk

def read_line
	line = gets.chomp.split(' ')
	line.map { |elem| elem.to_i }
end

def distance(a, b, n)
	return b - a if a <= b
	n - a + 1 + b - 1
end

n, m = read_line
a = read_line.uniq
current = 1
res = 0
a.each do |after|
	res += distance(current, after, n)
	current = after
end

puts res


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$:  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$.  $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain.

For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$.

gets.to_i.times do
  n = gets.to_i
  array = [*1..n]
  p n
  n.times do |i|
    puts array * " "
    if i + 1 < n
      array[i], array[i + 1] = array[i + 1], array[i]
    end
  end
end


In this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully.A string is a bHTML table, if it satisfies the grammar: TABLE ::=
ROWS
ROWS ::= ROW | ROW ROWSROW ::=
CELLS
CELLS ::= CELL | CELL CELLSCELL ::= 	 | TABLE	Blanks in the grammar are only for purposes of illustration, in the given data there will be no spaces. The bHTML table is very similar to a simple regular HTML table in which meet only the following tags : "table", "tr", "td", all the tags are paired and the table contains at least one row and at least one cell in each row. Have a look at the sample tests as examples of tables.As can be seen, the tables may be nested. You are given a table (which may contain other(s)). You need to write a program that analyzes all the tables and finds the number of cells in each of them. The tables are not required to be rectangular.

For convenience, input data can be separated into non-empty lines in an arbitrary manner. The input data consist of no more than 10 lines. Combine (concatenate) all the input lines into one, to get a text representation s of the specified table. String s corresponds to the given grammar (the root element of grammar is TABLE), its length does not exceed 5000. Only lower case letters are used to write tags. There are no spaces in the given string s.

Print the sizes of all the tables in the non-decreasing order.

TABLE_PAT = '<table>'
ROW_PAT = '<tr>'
CELL_PAT = '<td>'

class Solution
  def initialize()
    @s = ""
    while line=gets do
      @s = @s + line.chomp!
    end
    @count_stack = []
    @count_array = []
  end

  def cell()
    @s = @s[CELL_PAT.length..-1]
    if /^#{TABLE_PAT}/ =~ @s
      table
    end
    @count_stack[-1] += 1
    @s = @s[CELL_PAT.length+1..-1]
  end

  def row()
    @s = @s[ROW_PAT.length..-1]
    while /^#{CELL_PAT}/ =~ @s do
      cell
    end
    @s = @s[ROW_PAT.length+1..-1]
  end

  def table()
    @s = @s[TABLE_PAT.length..-1]
    @count_stack.push(0)
    while /^#{ROW_PAT}/ =~ @s do
      row
    end
    @count_array.push(@count_stack.pop)
    @s = @s[TABLE_PAT.length+1..-1]
  end

  def solve()
    while /^#{TABLE_PAT}/ =~ @s do
      table
    end
    puts @count_array.sort!.join(' ')
  end
end

solution = Solution.new
solution.solve

a = [0]
b = []
(readlines.map(&:chomp) * '').scan(/<(ta|\/ta|td)/) do |_,|
	case _
	when 'ta' then a << 0
	when '/ta' then b << a.pop
	when 'td' then a[-1] += 1
	end
end
puts b.sort * ' '

s = ''
x = ''
s += x.chomp while x = gets

def read_next(s)
  return [nil, nil] if !s || s.empty?
  pos = s.index('>')
  [s[0..pos], s[pos+1..-1]]
end

stack = []
ans = []

while true
  head, s = read_next(s)
  break unless head
  case head
    when "
" then stack.push(0)
    when "
" then ans << stack.pop
    when "	" then stack[-1] += 1
  end
end

puts ans.sort.join(' ')

a = [0]
b = []
(readlines * '').scan(/<(ta|\/ta|td)/) do |_,|
	case _
	when 'ta' then a << 0
	when '/ta' then b << a.pop
	when 'td' then a[-1] += 1
	end
end
puts b.sort * ' '

a = [0]
b = []
(readlines * ' ').scan(/<(table|\/table|td)>/) do |_,|
	case _
	when 'table' then a << 0
	when '/table' then b << a.pop
	when 'td' then a[-1] += 1
	end
end
puts b.sort * ' '


We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.

The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$  — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  xs.pop while xs.last == 0
  sum = 0
  ok = true
  xs.each.with_index do |x, i|
    sum += x
    if sum < 0 || (sum == 0 && i != xs.size - 1)
      ok = false
    end
  end
  ok = false if sum != 0
  puts ok ? "YES" : "NO"
end


Ashishgup and FastestFinger play a game. They start with a number $$$n$$$ and play in turns. In each turn, a player can make any one of the following moves:  Divide $$$n$$$ by any of its odd divisors greater than $$$1$$$.  Subtract $$$1$$$ from $$$n$$$ if $$$n$$$ is greater than $$$1$$$. Divisors of a number include the number itself.The player who is unable to make a move loses the game.Ashishgup moves first. Determine the winner of the game if both of them play optimally.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$)  — the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer  — $$$n$$$ ($$$1 \leq n \leq 10^9$$$).

For each test case, print "Ashishgup" if he wins, and "FastestFinger" otherwise (without quotes).

FastestFinger
Ashishgup
Ashishgup
FastestFinger
Ashishgup
FastestFinger
Ashishgup

NoteIn the first test case, $$$n = 1$$$, Ashishgup cannot make a move. He loses.In the second test case, $$$n = 2$$$, Ashishgup subtracts $$$1$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the third test case, $$$n = 3$$$, Ashishgup divides by $$$3$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the last test case, $$$n = 12$$$, Ashishgup divides it by $$$3$$$. Now $$$n = 4$$$, FastestFinger is forced to subtract $$$1$$$, and Ashishgup gets $$$3$$$, so he wins by dividing it by $$$3$$$.

def solve
  n = gets.strip.to_i
  if n == 1
    puts "FastestFinger"
    return nil
  end
  if n == 2 || n.odd?
    puts "Ashishgup"
    return nil
  end

  sq = Math.sqrt(n).to_i
  (2..sq).each { |i|
    if (n % i).zero?
      if (i.odd? && (n / i) > 2) || ((n / i).odd? && (n / (n / i)) > 2)
        puts "Ashishgup"
        return nil
      end
    end
  }
  puts "FastestFinger"
end

gets.strip.to_i.times { solve }

n = gets.chomp.to_i

a = 'Ashishgup'
b = 'FastestFinger'

def is_prime?(num)
  return if num <= 1
  (2..Math.sqrt(num)).none? { |i| (num % i).zero? }
end

(1..n).each do
  x = gets.chomp.to_i
  if x == 1
    puts b
  elsif x == 2
    puts a
  elsif x % 2 == 1
    puts a
  elsif x % 4 != 0
    if is_prime?(x/2)
      puts b
    else
      puts a
    end
  elsif x.to_s(2).count('1') == 1
    puts b
  else
    puts a
  end
end

def solve
  n = gets.strip.to_i
  if n == 1
    puts "FastestFinger"
    return nil
  end
  if n == 2 || n.odd?
    puts "Ashishgup"
    return nil
  end

  sq = Math.sqrt(n).to_i
  (2..sq).each { |i|
    if (n % i).zero?
      if (i.odd? || (n / i).odd?)
        if n / (n / i) > 3 || n / i > 3
          puts "Ashishgup"
          return nil
        end
      end
    end
  }
  puts "FastestFinger"
end

gets.strip.to_i.times { solve }

n = gets.chomp.to_i

a = 'Ashishgup'
b = 'FastestFinger'

(1..n).each do
  x = gets.chomp.to_i
  if x == 1
    puts b
  elsif x == 2
    puts a
  elsif x % 2 == 1
    puts a
  elsif x % 4 != 0
    puts b
  elsif x.to_s(2).count('1') == 1
    puts b
  else
    puts a
  end
end


We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7.The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.

The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106.

Print the minimum number of steps modulo 109 + 7.

NoteThe first example: "ab"  →  "bba".The second example: "aab"  →  "abba"  →  "bbaba"  →  "bbbbaa".

res, q, m=0, 1, 10**9+7
gets.chomp.chars{|c| c==?a ? q=q*2%m : res=(res+q-1+m)%m}
p res

s=gets.chomp
MOD=1000000007
ans=0
m=1
for i in 0...s.length
	if s[i]=='a'
		m=(m*2)%MOD
	else
		ans=(ans+m-1)%MOD
	end
end
puts ans

s=gets.chomp
m=10**9+7
a=s.split(?b).map(&:size)
a.pop if s[-1]!=?b
n=a.size
for i in 1...n
    a[i]+=a[i-1]
end
res=0
a.each{|e| res+=2**e-1; res%=m; }
p res


Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation.This day, Mocha got a sequence $$$a$$$ of length $$$n$$$. In each operation, she can select an arbitrary interval $$$[l, r]$$$ and for all values $$$i$$$ ($$$0\leq i \leq r-l$$$), replace $$$a_{l+i}$$$ with $$$a_{l+i} \,\&\, a_{r-i}$$$ at the same time, where $$$\&$$$ denotes the bitwise AND operation. This operation can be performed any number of times.For example, if $$$n=5$$$, the array is $$$[a_1,a_2,a_3,a_4,a_5]$$$, and Mocha selects the interval $$$[2,5]$$$, then the new array is $$$[a_1,a_2\,\&\, a_5, a_3\,\&\, a_4, a_4\,\&\, a_3, a_5\,\&\, a_2]$$$.Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?

Each test contains multiple test cases.  The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).

For each test case, print one integer — the minimal value of the maximum value in the sequence.

NoteIn the first test case, Mocha can choose the interval $$$[1,2]$$$, then the sequence becomes $$$[ 0, 0]$$$, where the first element is $$$1\,\&\,2$$$, and the second element is $$$2\,\&\,1$$$.In the second test case, Mocha can choose the interval $$$[1,3]$$$, then the sequence becomes $$$[ 1,1,1]$$$, where the first element is $$$1\,\&\,3$$$, the second element is $$$1\,\&\,1$$$, and the third element is $$$3\,\&\,1$$$.

END { load __FILE__ unless $stdin.eof? }

t = gets.to_i
t.times do

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

x = a.inject(:&)
p x

end

gets.to_i.times do
  n=gets.to_i
  puts gets.split.map(&:to_i).inject(:&)
end


This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers $$$a_1, a_2, \dots, a_n$$$.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers $$$f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$$$, where $$$a_1 \dots a_p$$$ and $$$b_1 \dots b_q$$$ are digits of two integers written in the decimal notation without leading zeros.In other words, the function $$$f(x, y)$$$ alternately shuffles the digits of the numbers $$$x$$$ and $$$y$$$ by writing them from the lowest digits to the older ones, starting with the number $$$y$$$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$$$$f(1111, 2222) = 12121212$$$$$$ $$$$$$f(7777, 888) = 7787878$$$$$$ $$$$$$f(33, 44444) = 4443434$$$$$$ $$$$$$f(555, 6) = 5556$$$$$$ $$$$$$f(111, 2222) = 2121212$$$$$$Formally,  if $$$p \ge q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$;  if $$$p < q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$. Mishanya gives you an array consisting of $$$n$$$ integers $$$a_i$$$, your task is to help students to calculate $$$\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$$$ modulo $$$998\,244\,353$$$.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of elements in the array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array.

Print the answer modulo $$$998\,244\,353$$$.

MOD = 998244353
n = gets.to_i
a = gets.split.map(&:to_i)
cnt = [0]*10
a.each do |v|
  cnt[Math.log10(v).to_i] += 1
end
ans = 0
a.each do |v|
  d = Math.log10(v).to_i
  l,r,m = v,0,1
  10.times do |i|
    r += m*(l%10)
    l /= 10
    m *= 100
    if i < d
      ans += l * m * cnt[i] * 2 % MOD
      ans += (r + r*10) * cnt[i] % MOD
    else
      ans += (r + r*10) * cnt[i] % MOD
    end
    ans %= MOD
  end
end
p ans

MOD = 998244353
n = gets.to_i
a = gets.split.map(&:to_i)
cnt = [0]*10
a.each do |v|
  cnt[Math.log(v,10).to_i] += 1
end
ans = 0
a.each do |v|
  d = Math.log(v,10).to_i
  val = v
  10.times do |i|
    val = (val/10**(i*2)) * 10**(i*2+1) + val % 10**(i*2)
    if i < d
      l = val/10**(i**2+2)
      r = val % 10**(i**2+2)
      ans += l * 10**(i**2+2) * cnt[i] * 2 % MOD
      ans += r * cnt[i] % MOD
      ans += r/10 * cnt[i] % MOD
    else
      ans += val/10 * cnt[i] % MOD
      ans += val * cnt[i] % MOD
    end
    ans %= MOD
    #p [v,i,val,ans]
  end
end
#p cnt
p ans

MOD = 998244353
n = gets.to_i
a = gets.split.map(&:to_i)
cnt = [0]*10 # key: log10(a)
a.each do |v|
  cnt[Math.log(v,10).to_i] += 1
end
ans = 0
a.each do |v|
  d = Math.log(v,10).to_i
  val = v
  10.times do |i|
    val = (val/10**(i*2)) * 10**(i*2+1) + val % 10**(i*2) % MOD
    if i < d
      l = val/10**(i**2+2)
      r = val % 10**(i**2+2)
      ans += l * 10**(i**2+2) * cnt[i] * 2 % MOD
      ans += r * cnt[i] % MOD
      ans += r/10 * cnt[i] % MOD
    else
      ans += val/10 * cnt[i] % MOD
      ans += val * cnt[i] % MOD
    end
    ans %= MOD
    #p [v,i,val,ans]
  end
end
#p cnt
p ans

def modpow(x,n)
  ret = 1
  while n > 0
    ret = ret*x % MOD if n&1 == 1
    x = x*x % MOD
    n >>= 1
  end
  return ret
end

def modinv(x)
  return modpow(x,MOD-2)
end
MOD = 998244353
n = gets.to_i
a = gets.split.map(&:to_i)
cnt = [0]*10
a.each do |v|
  cnt[Math.log(v,10).to_i] += 1
end
ans = 0
a.each do |v|
  d = Math.log(v,10).to_i
  l,r,m = v,0,1
  10.times do |i|
    r += m*(l%10)
    l /= 10
    m *= 100
    if i < d
      ans += l * m * cnt[i] * 2 % MOD
      ans += (r + r*10) * cnt[i] % MOD
    else
      ans += (r + r*10) * cnt[i] % MOD
    end
    ans %= MOD
  end
end
p ans


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times:  if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  ...  remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.

The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.

Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).

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

a = s.split("").sort

hash = Hash.new { |hash, key| hash[key] = 0 }

k.times do |i|
  hash[a[i]] += 1
end

result = ""

s.each_char do |char|
  if hash[char].nil? || hash[char] <= 0
    result << char
  elsif hash[char] && hash[char] > 0
    hash[char] -= 1
  end
end

puts result

n, k = gets.split(" ").map{|n| n.to_i }
s = gets.chomp

require 'pp'
strs = "abcdefghijklmnopqrstuvwxyz".split("")
maps = {}
s.length.times{|i|
  maps[s[i]] ||= 0
  maps[s[i]] += 1
}

counts = maps.to_a.sort{|a, b|a[0]<=>b[0]}
erase_counts = {}
while 0 < k
  counts.each{|char, count|
    erase = [count, k].min
    k -= erase
    erase_counts[char] = erase
    break if k == 0
  }
end

s.length.times{|i|
  char = s[i]
  if not erase_counts[char].nil? and 0 < erase_counts[char]
    erase_counts[char] -= 1
  else
    print char
  end
}
puts ""

n, k = gets.split.map(&:to_i)
s = gets.chomp
pos = (1..26).map { [] }
s.chars.each_with_index { |c, i| pos[c.ord - 'a'.ord] << i }

flag = [true] * n
pos.each do |a|
	a.each do |pos|
		if k > 0
			flag[pos] = false
			k -= 1
		end
	end
end
puts (0...n).select { flag[_1] }.map { s[_1] }.join

def solution
  _, k = read_ints
  s = read_string.chars

  ixs = (0..25).map{ |i| [] }

  (0...s.size).each do |i|
    c = s[i]
    x = c.ord - 97
    ixs[x] << i
  end

  to_remove = ixs.flatten

  k.times do
    i = to_remove.shift
    s[i] = '*'
  end

  # puts s.gsub('*', '')
  s.each do |c|
    print c if c > '*'
  end
  puts

end

def solution_16s
  # perf problem was not the hash; it was the string ops
  # Apparently s[i] = 'c' is expensive.
  # Using s.chars instead is much better
  _, k = read_ints
  s = read_string

  ixs = Hash.new { |h, i| h[i] = [] }

  (0...s.size).each do |i|
    c = s[i]
    ixs[c] << i
  end

  l = 'a'

  k.times do
    l = l.succ while ixs[l].size < 1
    ix = ixs[l].shift
    s[ix] = ' '
  end

  # puts s.gsub(' ', '')
end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

N, K = gets.split.map(&:to_i)
str = gets.chomp
hash = Hash.new(0)
str.split('').sort[0, K].each do |c|
    hash[c] += 1
end
ans = ''
str.chars do |c|
    if hash[c] > 0
        hash[c] -= 1
    else
        ans << c
    end
end
puts ans

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

chars = str.split('').sort
hsh = {}
k.times do |i|
  hsh[chars[i]] = (hsh[chars[i]] || 0) + 1
end

ans_str = ""
str.each_char do |c|
  if hsh[c].nil? || hsh[c] <= 0
    ans_str << c
  else
    hsh[c] -= 1 if hsh[c] && hsh[c] > 0
  end
end
puts ans_str

def solution
  _, k = read_ints
  s = read_string.chars

  ixs = (0..25).map{ |i| [] }

  (0...s.size).each do |i|
    c = s[i]
    x = c.ord - 97
    ixs[x] << i
  end

  to_remove = ixs.flatten

  k.times do
    i = to_remove.shift
    s[i] = '*'
  end

  # puts s.gsub('*', '')
  s.each do |c|
    print c, false if c > '*'
  end
  puts

end

def solution_16s
  _, k = read_ints
  s = read_string

  ixs = Hash.new { |h, i| h[i] = [] }

  (0...s.size).each do |i|
    c = s[i]
    ixs[c] << i
  end

  l = 'a'

  k.times do
    l = l.succ while ixs[l].size < 1
    ix = ixs[l].shift
    s[ix] = ' '
  end

  # puts s.gsub(' ', '')
end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

def solution
  _, k = read_ints
  s = read_string.chars

  ixs = (0..25).map{ |i| [] }

  (0...s.size).each do |i|
    c = s[i]
    x = c.ord - 97
    ixs[x] << i
  end

  to_remove = ixs.flatten

  k.times do
    i = to_remove.shift
    s[i] = '*'
  end

  s.each do |c|
    print c, false if c > '*'
  end
  puts

end

def solution_16s
  _, k = read_ints
  s = read_string

  ixs = Hash.new { |h, i| h[i] = [] }

  (0...s.size).each do |i|
    c = s[i]
    ixs[c] << i
  end

  l = 'a'

  k.times do
    l = l.succ while ixs[l].size < 1
    ix = ixs[l].shift
    s[ix] = ' '
  end

  # puts s.gsub(' ', '')
end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']


Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.

The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font:

Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes).

sym = ['A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y']

input = gets.chomp
if input != input.reverse
    puts "NO"
else
    input.each_char do |char|
        next if sym.include? char

        puts "NO"
        exit
    end
    puts "YES"
end

def solve(s)
	return ((/^[AHIMOTUVWXY]*$/.match s) and (s == s.reverse))
end

def main()
	return "YES" if solve(gets.chomp)
	return "NO"
end

puts main

s = gets.chomp
if s.match(/[^AHIOMTUVWXY]/).nil? and s == s.reverse
  puts 'YES'
else
  puts 'NO'
end

s = gets.chomp
if (s.size == 1 or s[0..s.size / 2 - 1] == s[(s.size / 2.0).ceil..-1].reverse) and s.scan(/[AHIMOTUVWXY]/i).size == s.size
	puts "YES"
else
	puts "NO"
end

s = gets.chomp
letters = ["A", "H", "I", "M", "O", "T", "U", "V", "W", "X", "Y"]
s.split("").each do |ch|
    unless letters.include?(ch)
        puts "NO"
        exit
    end
end
if s.reverse != s
    puts "NO"
    exit
end
puts "YES"

s = gets.chomp
letters = ["A", "H", "I", "M", "O", "T", "U", "V", "W", "X", "Y"]
unless (s.split("").uniq-letters).empty?
    puts "NO"
    exit
end
if s.reverse != s
    puts "NO"
    exit
end
puts "YES"

MIRROR = "AHIMOTUVWXY"
s = gets.chomp
len = s.length
0.upto(len>>1) do |i|
	if s[i] != s[len-1-i] || !MIRROR.include?(s[i]) || !MIRROR.include?(s[len-1-i])
		puts "NO"
		exit 0
	end
end
puts "YES"

#!/usr/bin/ruby
s=gets.chomp
puts s.tr('A-Z','A@@@@@@HI@@@M@O@@@@TUVWXY@').reverse==s ? :YES : :NO

s = gets.chomp
if s[0..s.size / 2 - 1] == s[(s.size / 2.0).ceil..-1].reverse and s.scan(/[AHIMOTUVWXY]/i).size == s.size
	puts "YES"
else
	puts "NO"
end

gets.chomp.each_char do |i|
	if !"AHIMOTUVWY".include?(i)
		puts "NO"
		exit 0
	end
end
puts "YES"

#!/usr/bin/ruby
s=gets.chomp
puts s.tr('A-Z','A@@@@@@HI@@M@O@@@@TUVWXY@').reverse==s ? :YES : :NO

s = gets.chomp
if s.match(/[^AHIOTUVWXY]/).nil? and s == s.reverse
  puts 'YES'
else
  puts 'NO'
end


The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.

The first line of input will contain an integer n (1 ≤ n ≤ 105), the number of events. The next line will contain n space-separated integers. If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.

Print a single integer, the number of crimes which will go untreated.

NoteLets consider the second example:  Firstly one person is hired.  Then crime appears, the last hired person will investigate this crime.  One more person is hired.  One more crime appears, the last hired person will investigate this crime.  Crime appears. There is no free policeman at the time, so this crime will go untreated.  One more person is hired.  One more person is hired.  One more person is hired. The answer is one, as one crime (on step 5) will go untreated.

n = gets.to_i
plc, crm = 0, 0
gets.split(' ',n).map(&:to_i).each do |x|
  plc += x
  if plc < 0
    crm += 1
    plc = 0
  end
end
puts crm

#!/usr/bin/ruby
gets
r=0
n=0
gets.split.each{|e|
	n+=e.to_i
	if n<0
		r+=-n
		n=0
	end
}
p r

police = 0
ans = 0
gets.chomp
gets.chomp.split(" ").each { |p|
  if p.to_i > -1
    police += p.to_i
  elsif police > 0
    police -= 1
  else
    ans += 1
  end
}

puts ans

gets
s=0
a=0
for x in gets.chomp.split.map(&:to_i)
	s += x;
	a += -s if s < 0
	s -= s if s < 0
end

puts a

n = gets.to_i
events = gets.chomp.split(" ").map{ |e| e.to_i }
s = 0
p = 0
events.each{ |event|
	if event < 0
		if p > 0
			p -= 1
		else
			s += 1
		end
	else
		p += event
	end
}
puts(s)

# -*- encoding: utf-8 -*-
n = gets.chomp.to_i
events = gets.chomp.split(" ").map{ |e| e.to_i }

ans = 0
p = 0

events.each { |event|
  if event == -1
    if p > 0
      p -= 1
    else
      ans += 1
    end
  else
    p += event
  end
}

puts ans

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

x = 0
y = 0

for i in a
  if i == -1
    if x > 0
      x -= 1
    else
      y += 1
    end
  else
    x += i
  end
end

print y

n = gets.to_i
arr = gets.split.map(&:to_i)
soliders = 0
crimes = 0

arr.each do |x|
	soliders += x
	(crimes += 1; soliders = 0) if soliders < 0
end

puts crimes

n,v=gets.to_i,gets.split.map(&:to_i)
s,c=0,0
v.each {|x| (s+=x) == -1 ? (c,s=c+1,0) : s}
p c

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

counters = 0; xounterz = 0
for i in 0..n-1
  counters+=p[i]
  if counters<0
      xounterz+=1
      counters = 0
  end
end
puts xounterz

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

k = 0
f.inject(0) do |cops_count, x|
    #puts "cop_count=#{cops_count}, x=#{x}, k=#{k}"
    if x == -1
        if cops_count == 0
            k+=1
        else
            cops_count -= 1
        end
    else
        cops_count += x
    end
    cops_count
end

puts k

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

i= 0
available_police = 0
crime =0
n.times do
  if list[i] > 0
    available_police+=list[i]

  elsif list[i]<0 and available_police>0
    available_police+=list[i]
  else
    crime +=1
  end
  i+=1

end
puts crime

n = gets.to_i
arr = gets.split.map &:to_i
cops = 0
crimes = 0
arr.each do |x|
  if x == -1 && cops == 0
    crimes += 1
  elsif x == -1 && cops != 0
    cops -= 1
  else
    cops += x
  end
end
puts crimes

n = gets.to_i
a = gets.split.map(&:to_i)
cur = 0
ans = 0
for x in a
  if x>0
    cur += x
  else
    if cur == 0
      ans += 1
    else
      cur -= 1
    end
  end
end
print ans

n = gets.to_i
s = 0
ans = 0
gets.split.map(&:to_i).each do |e|
  if e < 0
    if s > 0
      s += e
    else
      ans += 1
    end
  else
    s += e
  end
end
puts ans

gets
f=a=0
gets.split.map{|i| i.to_i}.each{|s|
	if s<0
		if f<=0
			a+=1
		else
			f-=1
		end
	else
		f+=s
	end
}
p a

gets
x=gets.split.map{|e| e.to_i}
sum=0
ans=0
x.each{|e|
	if e<0 then
		sum+=e
		ans+=1 if sum<0
	else
		sum=([sum,0].max)+e
	end
}
puts ans

t = gets.chomp.to_i
arr = gets.chomp.split.map(&:to_i)

co = 0
t = 0
arr.each do |el|
  # p [t+el]
  if t + el < 0
    co += 1
    t = 0
  else
    t += el
  end
end
puts co

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

police = 0
criminal = 0
out = 0
k = gets.to_i
gets.chomp.split.map do |e|
  e = e.to_i
  police += e if e > 0
  out += 1 if e == -1 and police == 0
  police -= 1 if  e == -1 and police > 0

end

puts out

n = gets.chomp.to_i

ans,pol = 0,0

gets.chomp.split(" ").each { |e|
  if e.to_i == -1
    if pol>0
      pol -= 1
    else
      ans += 1
    end
  else
    pol += e.to_i
  end
}
puts ans

crimes = gets.chomp.to_i
n = gets.chomp
events = n.split

count = 0
untreated = 0
for i in (0..crimes-1)
	if count == 0 && events[i].to_i == -1
		untreated += 1
	elsif events[i].to_i >= 1
		count += events[i].to_i
	elsif count > 0 && events[i].to_i == -1
		count -= 1
	end
end

puts untreated

n = gets.chomp
events = gets.chomp.split(' ').map(&:to_i)
ans = f = 0
events.reverse.each do |e|
  next if f == 0 && e != -1
  f = 1
  if e == -1
    ans = ans + e
  else
    ans = ans + (ans < 0 ? e : 0)
    ans = 0 if ans > 0
  end
end
puts ans.abs

gets
now = 0
ans = 0
gets.split.map(&:to_i).each { |c|
  if c == -1
    if now >= 1
      now -= 1
    else
      ans += 1
    end
  else
    now += c
  end
}

puts ans

cops = 0
result = 0

gets
gets.split(' ').map(&:to_i).each do |x|
  cops += x
  if cops < 0
    result += 1
    cops = 0
  end
end

puts result

eventNumber = gets.chomp.to_i
input = gets.chomp.split(' ').map {|item| item.to_i}

police = 0
ans = 0
(0...eventNumber).each do |event|
    police += input[event] if input[event] >= 1

    if input[event] == -1 && police <= 0
        ans += 1
    elsif input[event] == -1
        police -= 1
    end
end

puts ans

police = 0
ans = 0
gets.chomp
gets.chomp.split(" ").each { |p|
  if p.to_i == 1
    police += 1
  elsif police > 0
    police -= 1
  else
    ans += 1
  end
}

puts ans

n = gets.to_i
events = gets.chomp.split(" ").map{ |e| e.to_i }
s = 0
p = 0
events.each{ |event|
	if event == -1
		if p >= 0
			p -= 1
		else
			s += 1
		end
	else
		p+=1
	end
}
puts(s)

n = gets.to_i
events = gets.chomp.split(" ").map{ |e| e.to_i }
s = 0
p = 0
events.each{ |event|
	if event == -1
		if p > 0
			p -= 1
		else
			s += 1
		end
	else
		p+=1
	end
}
puts(s)

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

x = 0
y = 0

for i in a
  if i == -1
    if x > 0
      x -= 1
    else
      y += 1
    end
  else
    x += 1
  end
end

print y

n,v=gets.to_i,gets.split.map(&:to_i)
s=0
p v.map {|x| s+=x}.min.abs

gets
f=a=0
gets.split.each{|s|
	if s[1]
		if f<0
			a+=1
		else
			f-=1
		end
	else
		f+=1
	end
}
p a

n = gets.chomp
events = gets.chomp.split(' ').map(&:to_i)
ans = f = 0
events.reverse.each { |e| f == 0 && e == 1 ? next : (f, ans = 1, ans + e) }
puts ans.abs


Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.It is known that the chicken needs t minutes to be cooked on the stove, if it is turned on, and 2t minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.

The single line contains three integers k, d and t (1 ≤ k, d, t ≤ 1018).

Print a single number, the total time of cooking in minutes. The relative or absolute error must not exceed 10 - 9. Namely, let's assume that your answer is x and the answer of the jury is y. The checker program will consider your answer correct if .

NoteIn the first example, the chicken will be cooked for 3 minutes on the turned on stove, after this it will be cooked for . Then the chicken will be cooked for one minute on a turned off stove, it will be cooked for . Thus, after four minutes the chicken will be cooked for . Before the fifth minute Julia will turn on the stove and after 2.5 minutes the chicken will be ready .In the second example, when the stove is turned off, Julia will immediately turn it on, so the stove will always be turned on and the chicken will be cooked in 20 minutes.

k, d, t = gets().split().map{|x| 2*(x.to_i)}
r = (d - k%d) % d
n = k/d
n += 1 if r != 0

ans = 0
if t <= k
	ans += t
else
	cycle = k + r/2
	ans += t/cycle * n * d
	t %= cycle
	if t <= k
		ans += t
	else
		ans += k + 2*(t-k)
	end
end

puts "%.10f" % [ans/2.0]

K,D,T=gets.split.map(&:to_f)
S=(K/D).ceil*D
def f(t)
  (t/S).floor*(K+(S-K)*0.5)+[t%S,K].min+[0,t%S-K].max*0.5
end
l=T
r=2*T
100.times{
  m=(l+r)/2.0
  if f(m)>T
    r=m
  else
    l=m
  end
}
p l

K,D,T=gets.split.map(&:to_f)
S=(K/D).ceil*D
# def f(t)
#   (t/S).floor*(K+(S-K)*0.5)+[t%S,K].min+[0,t%S-K].max*0.5
# end
# l=T
# r=2*T
# 100.times{
#   m=(l+r)/2.0
#   if f(m)>T
#     r=m
#   else
#     l=m
#   end
# }
# p l

ans = 0

a = (S + K) * 0.5
ans += (T/a).floor * S
T -= (T/a).floor * a

ans += [T, K].min
T -= [T, K].min

if T > 0
  ans += 2 * T
end

p ans

k,d,t = gets.split.map(&:to_i)
if k > d
  d = (k/d.to_f).ceil * d
end

per = k + (d-k)/2.to_f
n = (t/per).to_i
ans = n * d
if (t-per*n) <= k
  ans += t - per*n
elsif
  ans += k + (t-k-per*n)*2
end
puts ans

k,d,t = gets.split.map(&:to_i)
if k > d
  d = (k/d.to_f).ceil * d
end

trial = k + (d-k)/2.to_f
n = (t/trial).to_i
a = n * d
if (t-trial*n) <= k
  ans = n * d + t-trial*n
elsif
  ans = n * d + k + (t-trial*n-k)/2.to_f
end
sprintf("%.0f", ans.to_f)

k,d,t = gets.split.map(&:to_i)
if k > d
  d = (k/d.to_f).ceil * d
end

trial = k + (d-k)/2.to_f
n = (t/trial).to_i
a = n * d
if (t-trial*n) <= k
  ans = n * d + t-trial*n
elsif
  ans = n * d + k + (t-trial*n-k)/2.to_f
end
printf("%.0f", ans)

k,d,t = gets.split.map(&:to_i)
if k > d
  d = (k/d.to_f).ceil * d
end

trial = k + (d-k)/2.to_f
n = (t/trial).to_i
a = n * d
if (t-trial*n) <= k
  ans = n * d + t-trial*n
elsif
  ans = n * d + k + (t-trial*n-k)/2.to_f
end
puts ans

k,d,t = gets.split.map(&:to_i)
if k > d
  d = (k/d.to_f).ceil * d
end

per = k + (d-k)/2.to_f
n = (t/per).to_i
ans = n * d
p ans
p n*per
if (t-per*n) <= k
  ans += t - per*n
elsif
  ans += k + (t-k-per*n)*2
end
puts sprintf("%.9f", ans)

k,d,t = gets.split.map(&:to_i)
if k > d
  d = (k/d.to_f).ceil * d
end

per = k + (d-k)/2.to_f
n = (t/per).to_i
ans = n * d
p ans
p n*per
if (t-per*n) <= k
  ans += t - per*n
elsif
  ans += k + (t-k-per*n)*2
end
puts ans


There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.

Print the minimum number of operations required to change balance in each bank to zero.

NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer:   transfer 1 from the first bank to the second bank;  transfer 3 from the second bank to the third;  transfer 6 from the third bank to the fourth.

n = readline.to_i
arr = readline.split(' ').collect(&:to_i)
mp = Hash.new(0)
best = 0
sum = 0
arr.each do |num|
  sum += num
  mp[sum] += 1
  best = [best, mp[sum]].max
end
puts n - best

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

acc = 0
hash = Hash.new(0)
f.each do |x|
	acc += x
	hash[acc] += 1
end

ans = 0
hash.each do |key, val|
	ans = [ans, val].max
end

puts n - ans

n = readline.to_i
arr = readline.split(' ').collect(&:to_i)
mp = Hash.new
mp[0] = true
sum = 0
ct = 0
found = false
arr.each do |num|
  sum += num
  if found
    if sum == 0
      ct += 1
    end
  else
    if mp.has_key?(sum)
      found = true
      sum = 0
      ct += 1
    else
      mp[sum] = true
    end
  end
end
if found && sum != 0
  ct += 1
end
puts n - ct

n = readline.to_i
arr = readline.split(' ').collect(&:to_i)
mp = Hash.new
mp[0] = true
sum = 0
ct = 0
found = false
arr.each do |num|
  sum += num
  if found
    if sum == 0
      ct += 1
    end
  else
    if mp.has_key?(sum)
      found = true
      ct += 1
    else
      mp[sum] = true
    end
  end
end
puts n - ct

n = readline.to_i
arr = readline.split(' ').collect(&:to_i)
mp = Hash.new
mp[0] = true
sum = 0
ct = 0
found = false
arr.each do |num|
  sum += num
  if found
    if sum == 0
      ct += 1
    end
  else
    if mp.has_key?(sum)
      found = true
      ct += 1
    end
  end
end
puts n - ct


$$$n$$$ people gathered to hold a jury meeting of the upcoming competition, the $$$i$$$-th member of the jury came up with $$$a_i$$$ tasks, which they want to share with each other.First, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$ (an array of size $$$n$$$ where each integer from $$$1$$$ to $$$n$$$ occurs exactly once).Then the discussion goes as follows:  If a jury member $$$p_1$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped.  If a jury member $$$p_2$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped.  ...  If a jury member $$$p_n$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped.  If there are still members with tasks left, then the process repeats from the start. Otherwise, the discussion ends. A permutation $$$p$$$ is nice if none of the jury members tell two or more of their own tasks in a row. Count the number of nice permutations. The answer may be really large, so print it modulo $$$998\,244\,353$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — number of jury members. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the number of problems that the $$$i$$$-th member of the jury came up with. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the number of nice permutations, taken modulo $$$998\,244\,353$$$.

NoteExplanation of the first test case from the example:There are two possible permutations, $$$p = [1, 2]$$$ and $$$p = [2, 1]$$$. For $$$p = [1, 2]$$$, the process is the following:  the first jury member tells a task;  the second jury member tells a task;  the first jury member doesn't have any tasks left to tell, so they are skipped;  the second jury member tells a task. So, the second jury member has told two tasks in a row (in succession), so the permutation is not nice.For $$$p = [2, 1]$$$, the process is the following:  the second jury member tells a task;  the first jury member tells a task;  the second jury member tells a task. So, this permutation is nice.

@m = 998_244_353

def fact(m, n)
  (m..n).inject(1) { |f, i| f * i % @m }
end

gets.to_i.times do

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

if a[-1] - a[-2] > 1
  puts 0
  next
elsif a[-1] - a[-2] == 0
  puts fact(1, n)
  next
end

h = a.tally
hk = h.keys.sort!

b1 = h.delete(hk.pop)  # == 1
b2 = h.delete(hk.pop)

c = fact(1, b2) * b2 * fact(b2 + 2, n) % @m
puts c

end


There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.

Only one line containing two positive integers a and b (1 ≤ a, b ≤ 109).

Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output  - 1 as the answer.

NoteYou can see following graphs for sample 1 and sample 3.

class Solver
	def main
		x, y = gets.split.map { |s| s.to_i }
		if x < y then
			puts -1
		else
			tmp = (x - y) / (2 * y)
			puts (x + y).to_f / (2 * tmp + 2)
		end
	end
end

Solver.new.main


Nauuo is a girl who loves drawing circles.One day she has drawn a circle and wanted to draw a tree on it.The tree is a connected undirected graph consisting of $$$n$$$ nodes and $$$n-1$$$ edges. The nodes are numbered from $$$1$$$ to $$$n$$$.Nauuo wants to draw a tree on the circle, the nodes of the tree should be in $$$n$$$ distinct points on the circle, and the edges should be straight without crossing each other."Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.Nauuo wants to draw the tree using a permutation of $$$n$$$ elements. A permutation of $$$n$$$ elements is a sequence of integers $$$p_1,p_2,\ldots,p_n$$$ in which every integer from $$$1$$$ to $$$n$$$ appears exactly once.After a permutation is chosen Nauuo draws the $$$i$$$-th node in the $$$p_i$$$-th point on the circle, then draws the edges connecting the nodes.The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo $$$998244353$$$, can you help her?It is obvious that whether a permutation is valid or not does not depend on which $$$n$$$ points on the circle are chosen.

The first line contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is an edge between $$$u$$$ and $$$v$$$. It is guaranteed that the given edges form a tree.

The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo $$$998244353$$$.

NoteExample 1All valid permutations and their spanning trees are as follows.Here is an example of invalid permutation: the edges $$$(1,3)$$$ and $$$(2,4)$$$ are crossed.Example 2Every permutation leads to a valid tree, so the answer is $$$4! = 24$$$.

def fact(n)
  @facts ||= [1]
  (@facts.size).upto(n){|i| @facts << @facts[-1]*i % MOD}
  return @facts[n]
end

MOD = 998244353
n = gets.to_i
visited = [false]*(n+1)
childs = Array.new(n+1){[]}
(n-1).times do
  a,b = gets.split.map(&:to_i)
  childs[a] << b
  childs[b] << a
end
visited[1] = true
que = childs[1].dup
ans = fact(childs[1].length)

while v = que.shift
  visited[v] = true
  cnt = 0
  childs[v].each do |u|
    if !visited[u]
      que << u
      cnt += 1
    end
  end
  ans = (ans*fact(cnt+1)) % MOD
  #p [v,ans]
end
p ans*n % MOD


Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = $$$2$$$, b = $$$3$$$ changes the value of a to $$$5$$$ (the value of b does not change).In a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations "a += b" or "b += a". Leo wants to test handling large integers, so he wants to make the value of either a or b strictly greater than a given value $$$n$$$. What is the smallest number of operations he has to perform?

The first line contains a single integer $$$T$$$ ($$$1 \leq T \leq 100$$$) — the number of test cases. Each of the following $$$T$$$ lines describes a single test case, and contains three integers $$$a, b, n$$$ ($$$1 \leq a, b \leq n \leq 10^9$$$) — initial values of a and b, and the value one of the variables has to exceed, respectively.

For each test case print a single integer — the smallest number of operations needed. Separate answers with line breaks.

NoteIn the first case we cannot make a variable exceed $$$3$$$ in one operation. One way of achieving this in two operations is to perform "b += a" twice.

t = gets.to_i
t.times do
	a, b, n = gets.split.map(&:to_i)
	b, a = a, b if a < b
	# a >= b

	c = 0
	until n < a
		b += a
		a, b = b, a if a < b
		c += 1
	end

	p c
end


Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of $$$2$$$ rows and $$$n$$$ columns. Monocarp controls a character, which starts in cell $$$(1, 1)$$$ — at the intersection of the $$$1$$$-st row and the $$$1$$$-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ in one step if $$$|x_1 - x_2| \le 1$$$ and $$$|y_1 - y_2| \le 1$$$. Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell $$$(2, n)$$$ — at the intersection of row $$$2$$$ and column $$$n$$$.Help Monocarp determine if it is possible to complete the level.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of columns. The next two lines describe the level. The $$$i$$$-th of these lines describes the $$$i$$$-th line of the level — the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell. Additional constraint on the input: cells $$$(1, 1)$$$ and $$$(2, n)$$$ are safe.

For each test case, output YES if it is possible to complete the level, and NO otherwise.

NoteConsider the example from the statement.In the first test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (2, 3)$$$.In the second test case, one of the possible paths is $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 3) \rightarrow (2, 4)$$$.In the fourth test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (1, 3) \rightarrow (2, 4) \rightarrow (1, 5) \rightarrow (2, 6)$$$.

# 4
# 3
# 000
# 000
# 4
# 0011
# 1100
# 4
# 0111
# 1110
# 6
# 010101
# 101010

n = gets.to_i

def result
  n = gets.to_i
  arr = 2.times.map { gets.split('').map(&:to_i) }
  if n.times.all? do |i|
    arr[0][i] == 0 || arr[1][i] == 0
  end
    'YES'
  else
    'NO'
  end
end

n.times do
  puts result
end

def dfs(grid, x, y)
  if y == 1 && x == grid.first.length
    return true
  elsif grid[y].nil? || grid[y][x].nil? || grid[y][x] == "1"
    return false
  else
    grid[y][x] = "1"
    return dfs(grid, x, (y + 1) % 2) ||
      dfs(grid, x + 1, y) ||
      dfs(grid, x + 1, (y + 1) % 2)
  end
end

STDIN.read
  .split("\n")
  .drop(1)
  .each_slice(3) do |arr|
    puts(dfs([arr[1].split(""), arr[2].split("")], 0, 0) ? "YES" : "NO")
  end

t= gets.chomp.to_i
t.times do
    n=gets.chomp.to_i
    s1=gets.chomp.chars
    s2=gets.chomp.chars
    n.times do |i|
      if s1[i].to_i+s2[i].to_i==2
        puts "NO"
        break
    elsif i == n-1
        puts "YES"
    end
    end
end

    t = gets.to_i
    t.times{|w|
    n = gets.to_i
    board = [gets.chomp.to_s,gets.chomp.to_s]
    path = [0,0]
    find = false
    visited = []
    while path.size != 0
    node = path.shift
    if node[0] == n-1 && node[1] == 1
    find = true
    break
    end
    if (!visited.include?(node))
    visited<<node
    dir = [[node[0]+1,node[1]],[node[0],node[1]+1],[node[0]+1,node[1]+1],[node[0]+1,node[1]-1]].filter{|x,y| x<n && y>=0 && y < 2}
    dir.map{|w|
    if (board[w[1]][w[0]] == "0")
    path<<w
    end
    }
    end
    end
    puts find ? "YES" : "NO"
    }

gets.to_i.times do
  n=gets.to_i
  s=gets.chomp.chars.map(&:to_i)
  t=gets.chomp.chars.map(&:to_i)
  f=true
  n.times do |i|
    if s[i]+t[i]==2
      f=false
      break
    end
  end

  if f
    puts "YES"
  else
    puts "NO"
  end
end


Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 104) — number of pebbles of each type.

The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.

NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.Optimal sequence of actions in the second sample case:   In the first day Anastasia collects 8 pebbles of the third type.  In the second day she collects 8 pebbles of the fourth type.  In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.  In the fourth day she collects 7 pebbles of the fifth type.  In the fifth day she collects 1 pebble of the second type.

n, m = gets.chomp.split().map { |e| e.to_i }
pebble = gets.chomp.split().map { |e| e.to_i }
K = m - 1
answer = 0
for i in pebble
    answer += (i + K) / m
end
puts ((answer+1)/2)

number=gets.chomp.split.map{ |s| s.to_i}
w=gets.chomp.split.map{|s| s.to_i}
n=number[0]
k=number[1]
sum=0
count=0
w.each { |x| sum+=x/k}
w.each { |x| count+=1 if x%k!=0 }
if sum%2==1
	count+=1
end
result=sum/2+count/2
if count%2==1
	result+=1
end
puts result

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
ans = 0
a.each{|x| ans += (x + k - 1) / k}
p (ans + 1) / 2


Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?There are $$$n$$$ students living in a building, and for each of them the favorite drink $$$a_i$$$ is known. So you know $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ ($$$1 \le a_i \le k$$$) is the type of the favorite drink of the $$$i$$$-th student. The drink types are numbered from $$$1$$$ to $$$k$$$.There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $$$k$$$ types of drink sets, the $$$j$$$-th type contains two portions of the drink $$$j$$$. The available number of sets of each of the $$$k$$$ types is infinite.You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $$$\lceil \frac{n}{2} \rceil$$$, where $$$\lceil x \rceil$$$ is $$$x$$$ rounded up.After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $$$n$$$ is odd then one portion will remain unused and the students' teacher will drink it.What is the maximum number of students that can get their favorite drink if $$$\lceil \frac{n}{2} \rceil$$$ sets will be chosen optimally and students will distribute portions between themselves optimally?

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 1\,000$$$) — the number of students in the building and the number of different drinks. The next $$$n$$$ lines contain student's favorite drinks. The $$$i$$$-th line contains a single integer from $$$1$$$ to $$$k$$$ — the type of the favorite drink of the $$$i$$$-th student.

Print exactly one integer — the maximum number of students that can get a favorite drink.

NoteIn the first example, students could choose three sets with drinks $$$1$$$, $$$1$$$ and $$$2$$$ (so they will have two sets with two drinks of the type $$$1$$$ each and one set with two drinks of the type $$$2$$$, so portions will be $$$1, 1, 1, 1, 2, 2$$$). This way all students except the second one will get their favorite drinks.Another possible answer is sets with drinks $$$1$$$, $$$2$$$ and $$$3$$$. In this case the portions will be $$$1, 1, 2, 2, 3, 3$$$. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with $$$a_i = 1$$$ (i.e. the first, the third or the fourth).

n,k = gets.split.map(&:to_i)
b = Hash.new(0)
n.times do
    a = gets.to_i
    b[a] += 1
end
c = b.values.map{|i|i%2}.count(1)
ans = n-c/2
puts ans

a = gets.chomp.split.collect{|var| var.to_i}
n = a[0]
k = a[1]
array_k = Array.new(k,0)
for var in (0...n) do
    value = gets.chomp.to_i
    array_k[value - 1] += 1
end
students = 0
count = 0
for var in (0...k) do
    if(array_k[var] % 2 == 0)
        students += array_k[var]
    else
        students += (array_k[var] - 1)
        count += 1
    end
end
puts (students + (count.to_f/2).ceil)


Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.The outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made exactly n movements on its way from the headquarters to the stall. A movement can move the car from point (x, y) to one of these four points: to point (x - 1, y) which we will mark by letter "L", to point (x + 1, y) — "R", to point (x, y - 1) — "D", to point (x, y + 1) — "U".The GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: "UL", "UR", "DL", "DR" or "ULDR". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string "UL" means that the car moved either "U", or "L".You've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point (0, 0), your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of the car's movements from the headquarters to the stall. Each of the following n lines describes the car's possible movements. It is guaranteed that each possible movement is one of the following strings: "UL", "UR", "DL", "DR" or "ULDR".  All movements are given in chronological order.  Please do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin and cout stream or the %I64d specifier.

Print a single integer — the number of different possible locations of the gang's headquarters.

NoteThe figure below shows the nine possible positions of the gang headquarters from the first sample:   For example, the following movements can get the car from point (1, 0) to point (0, 0):

x=y=1
gets.to_i.times{
	s=gets.chomp.to_sym
	if (s==:UL)||(s==:DR)
		x+=1
	elsif (s==:UR)||(s==:DL)
		y+=1
	else
		x+=1
		y+=1
	end
}
p x*y


You are given a table $$$a$$$ of size $$$n \times m$$$. We will consider the table rows numbered from top to bottom from $$$1$$$ to $$$n$$$, and the columns numbered from left to right from $$$1$$$ to $$$m$$$. We will denote a cell that is in the $$$i$$$-th row and in the $$$j$$$-th column as $$$(i, j)$$$. In the cell $$$(i, j)$$$ there is written a number $$$(i - 1) \cdot m + j$$$, that is $$$a_{ij} = (i - 1) \cdot m + j$$$.A turtle initially stands in the cell $$$(1, 1)$$$ and it wants to come to the cell $$$(n, m)$$$. From the cell $$$(i, j)$$$ it can in one step go to one of the cells $$$(i + 1, j)$$$ or $$$(i, j + 1)$$$, if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path.  For example, with $$$n = 2$$$ and $$$m = 3$$$ the table will look as shown above. The turtle can take the following path: $$$(1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3)$$$. The cost of such way is equal to $$$a_{11} + a_{12} + a_{13} + a_{23} = 12$$$. On the other hand, the paths $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 1)$$$ and $$$(1, 1) \rightarrow (1, 3)$$$ are incorrect, because in the first path the turtle can't make a step $$$(2, 2) \rightarrow (2, 1)$$$, and in the second path it can't make a step $$$(1, 1) \rightarrow (1, 3)$$$.You are asked to tell the turtle a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$. Please note that the cells $$$(1, 1)$$$ and $$$(n, m)$$$ are a part of the way.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of test cases follows. A single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^4$$$) — the number of rows and columns of the table $$$a$$$ respectively.

For each test case output a single integer — a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$.

NoteIn the first test case the only possible path consists of a single cell $$$(1, 1)$$$.The path with the minimal cost in the second test case is shown in the statement.In the fourth and the fifth test cases there is only one path from $$$(1, 1)$$$ to $$$(n, m)$$$. Both paths visit every cell in the table.

gets.to_i.times{n, m = gets.split.map(&:to_i); p m * (m- 1  + n * n + n) / 2}

gets.to_i.times{n, m = gets.split.map(&:to_i);p (m * m + m * n * n + m * n - m) / 2}

gets.to_i.times{
    n, m = gets.split.map(&:to_i)
    p (m * m + m * n * n + m * n - m) / 2
}

gets.to_i.times do
  x, y = gets.split.map(&:to_i)
  puts((1 + y) * y / 2 + y * ((1 + x) * x / 2 - 1))
end

n = gets.chomp.to_i
for i in 1..n
    x, y = gets.split.map(&:to_i)
    ans = (1 + y) * y / 2 + y * ((1 + x) * x / 2 - 1)
    puts(ans)
end


You are given a tree (a connected undirected graph without cycles) of $$$n$$$ vertices. Each of the $$$n - 1$$$ edges of the tree is colored in either black or red.You are also given an integer $$$k$$$. Consider sequences of $$$k$$$ vertices. Let's call a sequence $$$[a_1, a_2, \ldots, a_k]$$$ good if it satisfies the following criterion:  We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from $$$a_1$$$ and ending at $$$a_k$$$.  Start at $$$a_1$$$, then go to $$$a_2$$$ using the shortest path between $$$a_1$$$ and $$$a_2$$$, then go to $$$a_3$$$ in a similar way, and so on, until you travel the shortest path between $$$a_{k-1}$$$ and $$$a_k$$$. If you walked over at least one black edge during this process, then the sequence is good.   Consider the tree on the picture. If $$$k=3$$$ then the following sequences are good: $$$[1, 4, 7]$$$, $$$[5, 5, 3]$$$ and $$$[2, 3, 7]$$$. The following sequences are not good: $$$[1, 4, 6]$$$, $$$[5, 5, 5]$$$, $$$[3, 7, 3]$$$.There are $$$n^k$$$ sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo $$$10^9+7$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$2 \le k \le 100$$$), the size of the tree and the length of the vertex sequence. Each of the next $$$n - 1$$$ lines contains three integers $$$u_i$$$, $$$v_i$$$ and $$$x_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$x_i \in \{0, 1\}$$$), where $$$u_i$$$ and $$$v_i$$$ denote the endpoints of the corresponding edge and $$$x_i$$$ is the color of this edge ($$$0$$$ denotes red edge and $$$1$$$ denotes black edge).

Print the number of good sequences modulo $$$10^9 + 7$$$.

NoteIn the first example, all sequences ($$$4^4$$$) of length $$$4$$$ except the following are good:   $$$[1, 1, 1, 1]$$$ $$$[2, 2, 2, 2]$$$ $$$[3, 3, 3, 3]$$$ $$$[4, 4, 4, 4]$$$ In the second example, all edges are red, hence there aren't any good sequences.

def main
  n, k = gets.chomp.split.map(&:to_i)

  graph = Hash.new {|hash, key| hash[key] = []}
  (n - 1).times do
    x, y, c = gets.chomp.split.map(&:to_i)
    if c == 0
      graph[x] << y
      graph[y] << x
    end
  end

  result = n ** k

  visited = {}
  for vertex in (1..n)
    if not visited[vertex]
      componentSize = 0
      stack = [vertex]
      while not stack.empty?
        componentSize += 1
        current = stack.pop
        visited[current] = true
        for neighbor in graph[current]
          if not visited[neighbor]
            stack.push(neighbor)
          end
        end
      end
      result -= componentSize ** k
    end
  end

  puts (result % (10 ** 9 + 7))
end

main


Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — the number of red, green and blue lamps in the set, respectively.

Print $$$t$$$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.

NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example.

gets.strip.to_i.times do
  a = gets.strip.split(' ').map(&:to_i)
  a.sort!
  res = if a[2] <= a[1] + a[0]
    (a[0] + a[1] + a[2]) / 2
  else
    a[0] + a[1]
  end
  if res * 2 == a.inject(:+) or  res * 2 == [a.inject(:+) - 1, 0].max
    puts "Yes"
  else
    puts "No"
  end
end

q = gets.chomp.to_i
(0..q-1).each do |i|
  a = gets.strip.split(' ').map(&:to_i)
  a.sort!
  res = if a[2] <= a[1] + a[0]
          (a[0] + a[1] + a[2]) / 2
        else
          a[0] + a[1]
        end
  if res * 2 == a.inject(:+) or  res * 2 == [a.inject(:+) - 1, 0].max
    puts "Yes"
  else
    puts "No"
  end
end

gets.strip.to_i.times {
    x, y, k = gets.strip.split(' ').map(&:to_i)
    mx = [x, y, k].max
    mn = [x, y, k].min
    if ((x + y + k) - (mx + mn) + mn) + 1 >= mx
        puts "YES"
    else
        puts "NO"
    end
}

a = gets.chomp.to_i
(0..a-1).each do |i|
  s = gets.chomp.split(' ')
  r = s[0].to_i; g = s[1].to_i; b = s[2].to_i;
  if ((r/g)>2 || (r/b)>2 || (g/b)>2 || (g/r)>2 || (b/r)>2 || (b/g)>2)
    puts 'No'
  else
    puts 'Yes'
  end
end

a = gets.chomp.to_i
(0..a-1).each do |i|
  s = gets.chomp.split(' ')
  r = s[0].to_i; g = s[1].to_i; b = s[2].to_i;
  if ((r-g).abs>2 || (r-b).abs>2 || (g-b).abs>2)
    puts 'No'
  else
    puts 'Yes'
  end
end

gets.strip.to_i.times {
    x, y, k = gets.strip.split(' ').map(&:to_i)
    if [x, y, k].max - [x, y, k].min <= 3
        puts "YES"
    else
        puts "NO"
    end
}


Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...The string $$$s$$$ he found is a binary string of length $$$n$$$ (i. e. string consists only of 0-s and 1-s).In one move he can choose two consecutive characters $$$s_i$$$ and $$$s_{i+1}$$$, and if $$$s_i$$$ is 1 and $$$s_{i + 1}$$$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing.Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $$$s$$$ as clean as possible. He thinks for two different strings $$$x$$$ and $$$y$$$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner.Now you should answer $$$t$$$ test cases: for the $$$i$$$-th test case, print the cleanest possible string that Lee can get by doing some number of moves.Small reminder: if we have two strings $$$x$$$ and $$$y$$$ of the same length then $$$x$$$ is lexicographically smaller than $$$y$$$ if there is a position $$$i$$$ such that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$,..., $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$.

The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.  Next $$$2t$$$ lines contain test cases — one per two lines. The first line of each test case contains the integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The second line contains the binary string $$$s$$$. The string $$$s$$$ is a string of length $$$n$$$ which consists only of zeroes and ones. It's guaranteed that sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.

Print $$$t$$$ answers — one per test case. The answer to the $$$i$$$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero).

NoteIn the first test case, Lee can't perform any moves.In the second test case, Lee should erase $$$s_2$$$.In the third test case, Lee can make moves, for example, in the following order: 11001101 $$$\rightarrow$$$ 1100101 $$$\rightarrow$$$ 110101 $$$\rightarrow$$$ 10101 $$$\rightarrow$$$ 1101 $$$\rightarrow$$$ 101 $$$\rightarrow$$$ 01.

require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7
t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  s = gets.chomp

  l = s.index('1')
  r = s.reverse.index('0')
  if l.nil? || r.nil?
    puts s
    next
  end

  r = n - r - 1

  if r < l
    puts s
  else
    left  = s.slice(0, l) || ''
    right = s.slice(r + 1, s.size) || ''
    # [[l, r], [left, right]]
    puts left + '0' + right
  end
end