You are given two strings $$$a$$$ and $$$b$$$ consisting of lowercase English letters, both of length $$$n$$$. The characters of both strings have indices from $$$1$$$ to $$$n$$$, inclusive. You are allowed to do the following changes:   Choose any index $$$i$$$ ($$$1 \le i \le n$$$) and swap characters $$$a_i$$$ and $$$b_i$$$;  Choose any index $$$i$$$ ($$$1 \le i \le n$$$) and swap characters $$$a_i$$$ and $$$a_{n - i + 1}$$$;  Choose any index $$$i$$$ ($$$1 \le i \le n$$$) and swap characters $$$b_i$$$ and $$$b_{n - i + 1}$$$. Note that if $$$n$$$ is odd, you are formally allowed to swap $$$a_{\lceil\frac{n}{2}\rceil}$$$ with $$$a_{\lceil\frac{n}{2}\rceil}$$$ (and the same with the string $$$b$$$) but this move is useless. Also you can swap two equal characters but this operation is useless as well.You have to make these strings equal by applying any number of changes described above, in any order. But it is obvious that it may be impossible to make two strings equal by these swaps.In one preprocess move you can replace a character in $$$a$$$ with another character. In other words, in a single preprocess move you can choose any index $$$i$$$ ($$$1 \le i \le n$$$), any character $$$c$$$ and set $$$a_i := c$$$.Your task is to find the minimum number of preprocess moves to apply in such a way that after them you can make strings $$$a$$$ and $$$b$$$ equal by applying some number of changes described in the list above.Note that the number of changes you make after the preprocess moves does not matter. Also note that you cannot apply preprocess moves to the string $$$b$$$ or make any preprocess moves after the first change is made.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$a$$$ and $$$b$$$. The second line contains the string $$$a$$$ consisting of exactly $$$n$$$ lowercase English letters. The third line contains the string $$$b$$$ consisting of exactly $$$n$$$ lowercase English letters.

Print a single integer — the minimum number of preprocess moves to apply before changes, so that it is possible to make the string $$$a$$$ equal to string $$$b$$$ with a sequence of changes from the list above.

NoteIn the first example preprocess moves are as follows: $$$a_1 := $$$'b', $$$a_3 := $$$'c', $$$a_4 := $$$'a' and $$$a_5:=$$$'b'. Afterwards, $$$a = $$$"bbcabba". Then we can obtain equal strings by the following sequence of changes: $$$swap(a_2, b_2)$$$ and $$$swap(a_2, a_6)$$$. There is no way to use fewer than $$$4$$$ preprocess moves before a sequence of changes to make string equal, so the answer in this example is $$$4$$$.In the second example no preprocess moves are required. We can use the following sequence of changes to make $$$a$$$ and $$$b$$$ equal: $$$swap(b_1, b_5)$$$, $$$swap(a_2, a_4)$$$.

N = gets.to_i
A = gets.chomp
B = gets.chomp

ans = 0
((N+1)/2).times do |i|
    hash = Hash.new(0)
    hash[A[i]] += 1
    hash[B[i]] += 1
    if i != N-i-1
        hash[A[N-i-1]] += 1
        hash[B[N-i-1]] += 1
    end
    values = hash.values.sort
    if values.all?(&:even?)
        next
    elsif B[i] != B[N-i-1] && A[i] != B[i] && A[N-i-1] != B[N-i-1] && A[i] != B[N-i-1] && A[N-i-1] != B[i]
        ans += 2
    else
        ans += 1
    end
end
puts ans

n = gets.to_i
str1 = gets.chomp
str2 = gets.chomp

#require 'Set'

count = 0

(0..(n/2)-1).each do |i|
  set = [str1[i],str2[i],str1[n-i-1],str2[n-i-1]]
  len = set.uniq.length

  if len == 2
    if set.count(set[0]) != 2
      count += 1
    end
  elsif len == 3
    count += 1
    if set[0] == set[2]
      count += 1
    end
  elsif len == 4
    count += 2
  end
end

if n%2==1
  if str1[n/2]!=str2[n/2]
    count += 1
  end
end

puts count

N = gets.to_i
A = gets.chomp
B = gets.chomp

ans = 0
((N+1)/2).times do |i|
    hash = Hash.new(0)
    hash[A[i]] += 1
    hash[B[i]] += 1
    if i != N-i-1
        hash[A[N-i-1]] += 1
        hash[B[N-i-1]] += 1
    end
    values = hash.values.sort
    if values.all?(&:even?)
        next
    elsif B[i] != B[N-i-1] && A[i] != B[i] && A[N-i-1] != B[N-i-1]
        ans += 2
    else
        ans += 1
    end
    p [i, ans]
end
puts ans

N = gets.to_i
A = gets.chomp
B = gets.chomp

ans = 0
((N+1)/2).times do |i|
    hash = Hash.new(0)
    hash[A[i]] += 1
    hash[B[i]] += 1
    if i != N-i-1
        hash[A[N-i-1]] += 1
        hash[B[N-i-1]] += 1
    end
    values = hash.values.sort
    if values.all?(&:even?)
        next
    elsif values == [1, 3] || B[i] == B[N-i-1]
        ans += 1
    else
        ans += 2
    end
end
puts ans

N = gets.to_i
A = gets.chomp
B = gets.chomp

ans = 0
((N+1)/2).times do |i|
    hash = Hash.new(0)
    hash[A[i]] += 1
    hash[B[i]] += 1
    if i != N-i-1
        hash[A[N-i-1]] += 1
        hash[B[N-i-1]] += 1
    end
    values = hash.values.sort
    if values.all?(&:even?)
        next
    elsif B[i] != B[N-i-1] && A[i] != B[i] && A[N-i-1] != B[N-i-1] && A[i] != B[N-i-1] && A[N-i-1] && B[i]
        ans += 2
    else
        ans += 1
    end
end
puts ans

N = gets.to_i
A = gets.chomp
B = gets.chomp

ans = 0
((N+1)/2).times do |i|
    hash = Hash.new(0)
    hash[A[i]] += 1
    hash[B[i]] += 1
    if i != N-i-1
        hash[A[N-i-1]] += 1
        hash[B[N-i-1]] += 1
    end
    values = hash.values.sort
    if values.all?(&:even?)
        next
    elsif A[i] != A[N-i-1] && A[i] != B[i] && A[N-i-1] != B[N-i-1]
        ans += 2
    else
        ans += 1
    end
end
puts ans

N = gets.to_i
A = gets.chomp
B = gets.chomp

ans = 0
((N+1)/2).times do |i|
    hash = Hash.new(0)
    hash[A[i]] += 1
    hash[B[i]] += 1
    if i != N-i-1
        hash[A[N-i-1]] += 1
        hash[B[N-i-1]] += 1
    end
    values = hash.values.sort
    if values.all?(&:even?)
        next
    elsif B[i] != B[N-i-1] && A[i] != B[i] && A[N-i-1] != B[N-i-1]
        ans += 2
    else
        ans += 1
    end
end
puts ans


Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:  Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.  Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman. After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?

The first line contains a single integer n (1 ≤ n ≤ 3·105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial group that is given to Toastman.

Print a single integer — the largest possible score.

NoteConsider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions.

n = gets.to_i
puts gets.chomp.split.map(&:to_i).sort.each_with_index.map{|x, i| x * (if i == n - 1 then i + 1 else i + 2 end)}.inject(:+)

n=gets.to_i
v=(gets.split.map &:to_i).sort
x=-v[-1]
(0...n).each{|i| x += (i+2)*v[i]}
p x

gets
x=gets.split.map{|e| e.to_i}.sort

sum1=x.inject(0){|sumA,e|
	sumA+e
}
ans=0
while x.size>1
	ans+=sum1
	sum1-=x[0]
	ans+=x[0]
	x.shift
end
ans+=x[0]
puts ans

n = gets.to_i
vec = (gets.split.map &:to_i).sort
x = 2*vec.reduce(:+) - vec[n-1]
for i in (1...n)
  x += i*vec[i]
end
p x

n=gets.to_i
v=(gets.split.map &:to_i).sort
x=2*v.reduce(:+)-v[-1]
(1...n).each{|i| x+=i*v[i]}
p x

# coding: utf-8

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

# 1 2 3 4 5
# X X X X X  sum [1 2 3 4 5]
# X X X X X  sp rt sum [1] [2 3 4 5]
# ? X X X X  throw sp rt sum [2] [3 4 5]
# ? ? X X X  throw sp rt sum [3] [4, 5]
# ? ? ? ? ?
# 1 3 5
# X X X [1 3 5]
# X X X [1] [3 5]
# ? X X [3] [5]
# ? ? ? empty
# 1 2 3 4
# X X X X [1 2 3 4]
# X X X X [1] [2 3 4]
# ? X X X [2] [3 4]
# ? ? X X [3] [4]

s = ar.sum
acc = s
while s > 0
    if ar.length > 1
        acc += s
        s -= ar.shift
    else
        break
    end
end

puts acc

n, v, r = gets.to_i, gets.split.map {|e| e.to_i}.sort!, 0
for i in 0...n-1
    r+=v[i]*(i+2)
end
p r+v[-1]*n

n = Integer(gets.chomp)
v = gets.chomp.split.map{|x| Integer(x)}.sort
sum = 0
for x in v do sum += x end
ans = sum
for x in v[0...-1] do
    ans += sum
    sum -= x
end

puts ans

M = 1_000_000_007
n = gets.to_i
xs = gets.split.map(&:to_i)
xs.sort!
sum = 0
n.times do |i|
  sum += xs[i] * [i + 2, n].min
end
p sum

#!/usr/bin/ruby2.0

n = STDIN.readline.to_i
numbers = STDIN.readline.split.collect {|s| s.to_i }
numbers.sort!

score = -numbers[n-1]
(n.downto 1).each do |i|
	score += (i+1)*numbers[i-1]
end

puts score

require 'pp'

n = STDIN.gets.chomp.to_i
vals = STDIN.gets.chomp.split(/ /).map(&:to_i)
vals.sort!.reverse!
ans = - vals.first
vals.each do |val|
  ans += val * (n + 1)
  n -= 1
end

puts ans

# 3
# 3 1 5

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

array_a.sort!

ans = 0

array_a.each_with_index do |a, i|
  break if i == n-1
  ans += a * (i+2)
end
ans += array_a.last * n

puts ans

n=gets.to_i
arr=gets.split(/ /).map(&:to_i)
sum=0
arr.each do |i|
  sum+=i
end
ans=0
arr.sort.each do |i|
  ans+=sum+i
  sum-=i
end
puts ans-arr.sort[-1]

N = gets.to_i
sum = 0
arr = gets.split.map{ |xx|
  x = xx.to_i
  sum += x
  x
}.sort_by{|x|x}
# p arr
# p sum
ans = sum
(N-1).times do |i|
  ans += sum
  sum -= arr[i]
  # p ans
end
puts ans

n = gets.to_i
a = gets.split(/\s+/).map(&:to_i).sort_by {|e| -e}
sum = result = a.inject {|a,b| a+b}

while a.size > 1
  x = a.pop
  result += sum
  sum -= x
end

p result

n=gets.to_i
arr=Array.new()
arr=gets.split.map(&:to_i)

arr.sort!
sum=arr[n-1]*n
for i in 2..n do
    sum+=arr[n-i]*(n+2-i)
end

puts sum

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

suffix_sum = tab[0..-2].reverse.inject([tab[-1]]){|x, y| x << x[-1]+y}.reverse

result = -tab[-1];

(0..tab.size-1).each do |i|
    result += suffix_sum[i] + tab[i]
end

puts result

# coding: utf-8

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

# 1 2 3 4 5
# X X X X X  [1 2 3 4 5]
# X X X X X  [1] [2 3 4 5]
# ? X X X X  [2] [3 4 5]
# ? X X X X  [2] [3] [4] [5]
# ? ? ? ? ?
# 1 3 5
# X X X [1 3 5]
# X X X [1] [3 5]
# ? X X [3] [5]
# ? ? ? empty
# 1 2 3 4
# X X X X [1 2 3 4]
# X X X X [1] [2 3 4]
# ? X X X [2 3 4]
# ? X X X [2] [3 4]
# ? ? X X [3 4]
# ? ? X X [3] [4]

s = ar.sum
acc = 0
while s > 0
    acc += s
    if ar.length > 2 # 왜냐면 2에선 split 된 다음이 없기 때문
        acc += s
        sub = ar.shift
        s -= sub
    else
        break
    end
end

puts acc


You are given a string $$$s$$$ of even length $$$n$$$. String $$$s$$$ is binary, in other words, consists only of 0's and 1's.String $$$s$$$ has exactly $$$\frac{n}{2}$$$ zeroes and $$$\frac{n}{2}$$$ ones ($$$n$$$ is even).In one operation you can reverse any substring of $$$s$$$. A substring of a string is a contiguous subsequence of that string.What is the minimum number of operations you need to make string $$$s$$$ alternating? A string is alternating if $$$s_i \neq s_{i + 1}$$$ for all $$$i$$$. There are two types of alternating strings in general: 01010101... or 10101010...

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$; $$$n$$$ is even) — the length of string $$$s$$$. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ ($$$s_i \in$$$ {0, 1}). String $$$s$$$ has exactly $$$\frac{n}{2}$$$ zeroes and $$$\frac{n}{2}$$$ ones. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.

For each test case, print the minimum number of operations to make $$$s$$$ alternating.

NoteIn the first test case, string 10 is already alternating.In the second test case, we can, for example, reverse the last two elements of $$$s$$$ and get: 0110 $$$\rightarrow$$$ 0101.In the third test case, we can, for example, make the following two operations:   11101000 $$$\rightarrow$$$ 10101100;  10101100 $$$\rightarrow$$$ 10101010.

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    s = gets.chomp.split("").map(&:to_i)
    count = 0
    i = 0
    until i == n
        if i >= 1
            if s[i] == s[i-1]
                count += 1
            end
        end
        i += 1
    end
    if count % 2 == 0
        puts count / 2
    else
        puts count / 2 + 1
    end
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    s = gets.chomp.split("").map(&:to_i)
    arr = []
    ar = [s.shift]
    tmp = ar[0]
    count = 0
    size = 1
    while true
        i = s.shift
        if i != tmp
            ar << i
            size += 1
        else
            if size % 2 != 0
                arr << ar.pop
                size -= 1
            end
            if size >= 2
                count += 1
            end
            ar = []
            ar << i
        end
        tmp = i
        if s == []
            break
        end
    end
    puts count
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    s = gets.chomp.split("").map(&:to_i)
    arr = []
    ar = [s.shift]
    tmp = ar[0]
    count = 0
    size = 1
    while true
        i = s.shift
        if i != tmp
            ar << i
            size += 1
        else
            if size % 2 != 0
                arr << ar.pop
                size -= 1
            end
            if size >= 2
                count += 1
            end
            ar = []
            size = 0
            ar << i
            size += 1
        end
        tmp = i
        if s == []
            if arr != []
                s = arr
            else
                break
            end
        end
        # puts "arr" + "#{arr}"
        # puts "ar" + "#{ar}"
        # puts "size" + "#{size}"
    end
    puts count
end


Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions:  The coordinates of each point in the set are integers.  For any two points from the set, the distance between them is a non-integer. Consider all points (x, y) which satisfy the inequations: 0 ≤ x ≤ n; 0 ≤ y ≤ m; x + y > 0. Choose their subset of maximum size such that it is also a beautiful set of points.

The single line contains two space-separated integers n and m (1 ≤ n, m ≤ 100).

In the first line print a single integer — the size k of the found beautiful set. In each of the next k lines print a pair of space-separated integers — the x- and y- coordinates, respectively, of a point from the set. If there are several optimal solutions, you may print any of them.

NoteConsider the first sample. The distance between points (0, 1) and (1, 2) equals , between (0, 1) and (2, 0) — , between (1, 2) and (2, 0) — . Thus, these points form a beautiful set. You cannot form a beautiful set with more than three points out of the given points. Note that this is not the only solution.

a=gets.split.map &:to_i
(p a.min+1).times{|i|puts [a[0]-i,i]*' '}

n,m=gets.split.map &:to_i
(p [n,m].min+1).times{|i|puts [n-i,i]*' '}

def run
  n, m = ARGF.readline.split.map(&:to_i)
  puts num = [n, m].min + 1
  num.times do |i|
    puts [n - i, i].join(' ')
  end
end

run if $0 == __FILE__

n, m = gets.split(' ').map &:to_i
q = [n,m].min
puts q + 1
(q+1).times do |time|
  puts [time, q - time].join(' ')
end

n,m=gets.split.map(&:to_i)
k=[n,m].min+1
puts k
i=0
k.times do
    puts "#{k-i-1} #{i}"
    i+=1
end

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

if n>m
  n = m
end
puts n+1
(0..n).each do |k|
  puts "#{k} #{n-k}"
end

n, m = gets.split(' ')
n = n.to_i
m = m.to_i

if n < m
	min = n
else
	min = m
end

beaty = []

osx = min
osy = 0

(min+1).times do |x|
	beaty << [osx, osy]
	osx -= 1
	osy += 1
	osx = n if osx < 0
	osy = 0 if osy > m
end

puts beaty.length

beaty.each do |e|
	puts e.join(' ')
end

n,m = gets.split(" ").map(&:to_i)
min = [n,m].min + 1
puts min
(0...min).each do |i|
	puts "#{i} #{min - i - 1}"
end

n,m = gets.chomp.split(" ").collect! {|x| x.to_i}
if n>m
	n = m
end

puts n+1
(0..n).each{|k|
	puts "#{k} #{n-k}"
}

n, m = gets.split.collect{|i| i.to_i}
ans = [n, m].min+1
puts ans
(0...ans).each do |i|
    print i, " ", ans-1-i, "\n"
end

n, m = gets.split.map { |x| x.to_i }
puts [n, m].min + 1
m.downto([0, m - n].max).each { |y| puts "#{m - y} #{y}" }

#!/usr/bin/env ruby

n = gets.split.collect{|i| i.to_i}.min

puts n + 1

0.upto(n) { |i| puts "#{i} #{n-i}" }

t = gets.split.collect{|x| x.to_i}
n,m = t[0],t[1]

min = t.min

puts min+1

(min+1).times do |i|
	print i,' ', min-i, "\n"
end

n,m=gets.split(&:to_i)
k=[n,m].min.to_i+1
puts k
i=0
k.times do
    puts "#{i} #{i}"
    i+=1
end

n,m=gets.split.map(&:to_i)
n+=1
m+=1
if n<m
    puts n
    for i in 1..n
        puts "#{i-1} #{i}"
    end
else
    puts m
    for i in 1..m
        puts "#{i%m} #{(i-1)%n}"
    end
end

n,m=gets.split(&:to_i)
k=[n,m].min.to_i+1
puts k
i=0
k.times do
    puts "#{k-i-1} #{i}"
    i+=1
end

n,m=gets.split(&:to_i)
k=[n,m].min.to_i
puts k+1
i=0
k.times do
    puts "#{i} #{i+1}"
    i+=1
end
puts "#{k} 0"

n, m = gets.split(' ')
n = n.to_i
m = m.to_i

if n < m
	min = n
else
	min = m
end

beaty = []

osx = 0
osy = 1

(min+1).times do |x|
	beaty << [osx, osy]
	osx += 1
	osy += 1
	osx = 0 if osx > n
	osy = 0 if osy > m
end

puts beaty.length

beaty.each do |e|
	puts e.join(' ')
end

n,m = gets.split(" ").map(&:to_i)
min = [n,m].min + 1
puts min
(0...min).each do |i|
	puts "#{i} #{min - i}"
end

#!/usr/bin/env ruby

n = gets.split.collect{|i| i.to_i}.min

puts n + 1

puts "0 1"
puts "1 0"

2.upto(n) { |i| puts "#{i} #{i}" }


Monocarp is the coach of the Berland State University programming teams. He decided to compose a problemset for a training session for his teams.Monocarp has $$$n$$$ problems that none of his students have seen yet. The $$$i$$$-th problem has a topic $$$a_i$$$ (an integer from $$$1$$$ to $$$n$$$) and a difficulty $$$b_i$$$ (an integer from $$$1$$$ to $$$n$$$). All problems are different, that is, there are no two tasks that have the same topic and difficulty at the same time.Monocarp decided to select exactly $$$3$$$ problems from $$$n$$$ problems for the problemset. The problems should satisfy at least one of two conditions (possibly, both):  the topics of all three selected problems are different;  the difficulties of all three selected problems are different. Your task is to determine the number of ways to select three problems for the problemset.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 50000$$$) — the number of testcases. The first line of each testcase contains an integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of problems that Monocarp have. In the $$$i$$$-th of the following $$$n$$$ lines, there are two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — the topic and the difficulty of the $$$i$$$-th problem. It is guaranteed that there are no two problems that have the same topic and difficulty at the same time. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

Print the number of ways to select three training problems that meet either of the requirements described in the statement.

NoteIn the first example, you can take the following sets of three problems:  problems $$$1$$$, $$$2$$$, $$$4$$$;  problems $$$1$$$, $$$3$$$, $$$4$$$;  problems $$$2$$$, $$$3$$$, $$$4$$$. Thus, the number of ways is equal to three.

gets.to_i.times do
  n=gets.to_i
  ab=[]
  la=[0]*(n+1)
  lb=[0]*(n+1)
  n.times do
    a,b=gets.split.map(&:to_i)
    ab << [a,b]
    la[a]+=1
    lb[b]+=1
  end
  c=0
  ab.each do |a,b|
    c+=(la[a]-1)*(lb[b]-1)
  end
  puts n*(n-1)*(n-2)/6-c
end


You have a sequence $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, consisting of integers between $$$1$$$ and $$$m$$$. You also have a string $$$s$$$, consisting of $$$m$$$ characters B.You are going to perform the following $$$n$$$ operations.   At the $$$i$$$-th ($$$1 \le i \le n$$$) operation, you replace either the $$$a_i$$$-th or the $$$(m + 1 - a_i)$$$-th character of $$$s$$$ with A. You can replace the character at any position multiple times through the operations. Find the lexicographically smallest string you can get after these operations.A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ of the same length if and only if in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.

The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2000$$$). The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 50$$$) — the length of the sequence $$$a$$$ and the length of the string $$$s$$$ respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the sequence $$$a$$$.

For each test case, print a string of length $$$m$$$ — the lexicographically smallest string you can get. Each character of the string should be either capital English letter A or capital English letter B.

NoteIn the first test case, the sequence $$$a = [1, 1, 3, 1]$$$. One of the possible solutions is the following.   At the $$$1$$$-st operation, you can replace the $$$1$$$-st character of $$$s$$$ with A. After it, $$$s$$$ becomes ABBBB.  At the $$$2$$$-nd operation, you can replace the $$$5$$$-th character of $$$s$$$ with A (since $$$m+1-a_2=5$$$). After it, $$$s$$$ becomes ABBBA.  At the $$$3$$$-rd operation, you can replace the $$$3$$$-rd character of $$$s$$$ with A. After it, $$$s$$$ becomes ABABA.  At the $$$4$$$-th operation, you can replace the $$$1$$$-st character of $$$s$$$ with A. After it, $$$s$$$ remains equal to ABABA.  The resulting string is ABABA. It is impossible to produce a lexicographically smaller string.In the second test case, you are going to perform only one operation. You can replace either the $$$2$$$-nd character or $$$4$$$-th character of $$$s$$$ with A. You can get strings BABBB and BBBAB after the operation. The string BABBB is the lexicographically smallest among these strings.In the third test case, the only string you can get is A.In the fourth test case, you can replace the $$$1$$$-st and $$$2$$$-nd characters of $$$s$$$ with A to get AABB.In the fifth test case, you can replace the $$$1$$$-st and $$$3$$$-rd characters of $$$s$$$ with A to get ABABBBB.

def main
  t = inp.to_i
  t.times do |i|
    n, m = mapint(inarr)
    a = mapint(inarr)
    str = 'B' * m
    n.times do |i|
      x = min(a[i], m + 1 - a[i])
      y = max(a[i], m + 1 - a[i])
      if str[x - 1] == 'B'
        str[x - 1] = 'A'
      else
        str[y - 1] = 'A'
      end
    end
    puts str
  end

end

# lib
def inp
  gets.chomp
end

def inarr
  gets.chomp.split
end

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

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

def min(a, b)
  (a < b)? a:b
end

main


A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not.The string t is called a substring of the string s if it can be read starting from some position in the string s. For example, the string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".You are given a string s, consisting of lowercase Latin letters and characters "?". You are also given a string p, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string p from it, replacing the "?" characters by Latin letters. Each "?" can be replaced by exactly one character of the Latin alphabet. For example, if the string p = «aba», then the string "a??" is good, and the string «?bc» is not. Your task is to find the number of good substrings of the string s (identical substrings must be counted in the answer several times).

The first line is non-empty string s, consisting of no more than 105 lowercase Latin letters and characters "?". The second line is non-empty string p, consisting of no more than 105 lowercase Latin letters. Please note that the length of the string p can exceed the length of the string s.

Print the single number representing the number of good substrings of string s. Two substrings are considered different in their positions of occurrence are different. Thus, if some string occurs several times, then it should be counted the same number of times.

NoteConsider the first sample test. Here the string s has two good substrings: "b??" (after we replace the question marks we get "baa"), "???" (after we replace the question marks we get "baa").Let's consider the second sample test. Here the string s has two good substrings: "ab?" ("?" can be replaced by "c"), "b?c" ("?" can be replaced by "a").

a=gets.split[0].bytes.to_a
b=gets.split[0].bytes.to_a
cntb=Array.new(256,0)
if a.length<b.length then
        puts 0
        exit
end
ans=0
cnta=Array.new(256,0)
0.upto(b.length-1){|i|
        cnta[a[i]]+=1
        cntb[b[i]]+=1
}
ok=true
for i in 97..122
        if cnta[i]>cntb[i] then
                ok=false
                break
        end
end
ans+=1 if ok
for i in 1..a.length-b.length
        cnta[a[i-1]]-=1
        cnta[a[i+b.length-1]]+=1
        ok=true
        for i in 97..122
                if cnta[i]>cntb[i] then
                        ok=false
                        break
                end
        end
        ans+=1 if ok
end
p ans

s, p = gets.chomp.unpack("C*"), gets.chomp.unpack("C*")
n, m = s.length, p.length

cnt = Array.new(256,0)
a = "abcdefghijklmnopqrstuvwxyz?".unpack("C*")

if n < m
 p 0
 exit
end

for i in 0...m
 cnt[s[i]] += 1
 cnt[p[i]] -= 1
end

ans = 0
for i in m..n
 tmp = cnt[a[26]]
 for j in 0..25
  tmp -= cnt[a[j]].abs
 end
 ans += 1 if tmp >= 0
 break if i == n
 cnt[s[i]] += 1
 cnt[s[i-m]] -= 1
end
p ans


You are given a rectangular grid of lattice points from (0, 0) to (n, m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.A polyline defined by points p1, p2, p3, p4 consists of the line segments p1 p2, p2 p3, p3 p4, and its length is the sum of the lengths of the individual line segments.

The only line of the input contains two integers n and m (0 ≤ n, m ≤ 1000). It is guaranteed that grid contains at least 4 different points.

Print 4 lines with two integers per line separated by space — coordinates of points p1, p2, p3, p4 in order which represent the longest possible polyline. Judge program compares your answer and jury's answer with 10 - 6 precision.

def dist(a, b)
  dx = a[0]-b[0]
  dy = a[1]-b[1]
  Math.sqrt(dx*dx+dy*dy)
end

def len(arr)
  dist(arr[0],arr[1]) + dist(arr[1],arr[2]) + dist(arr[2],arr[3])
end

n, m = gets.strip.split(" ").map{|x| x.to_i}

if n == 0
  puts "0 1"
  puts "0 #{m}"
  puts "0 0"
  puts "0 #{m-1}"
  exit
end
if m == 0
  puts "1 0"
  puts "#{n} 0"
  puts "0 0"
  puts "#{n-1} 0"
  exit
end

candidates = []

candidates.push [
  [n, m-1],
  [0, 0],
  [n, m],
  [0, 1]
]
candidates.push [
  [n-1, m],
  [0, 0],
  [n, m],
  [1, 0]
]
candidates.push [
  [0, 0],
  [n, m],
  [n, 0],
  [0, m]
]
candidates.push [
  [0, 0],
  [n, m],
  [0, m],
  [n, 0]
]

candidates.sort!{|a, b| -(len(a)<=>len(b))}

puts candidates.first.map{|x| x.join(" ")}

n, m = gets.split.map &:to_i
r = false
if n > m
  n, m = m, n
  r = true
end

ans = []
if n == 0
  ans << [0, 1] << [0, m] << [0, 0] << [0, m - 1]
elsif Math.hypot(n, m) * 2 + m > Math.hypot(n, m) + Math.hypot(m, n - 1) * 2
  ans << [0, 0] << [n, m] << [n, 0] << [0, m]
else
  ans << [1, 0] << [n, m] << [0, 0] << [n - 1, m]
end

ans.each{|i|
  if !r
    puts i * ' '
  else
    puts i.reverse * ' '
  end
}

n,m=gets.split.map{|i| i.to_i}
n,m=m,n if n>m
puts "0 1"
puts "#{n} #{m}"
puts "0 0"
puts "#{n} #{m-1}"

n,m=gets.split.map{|i| i.to_i}
n,m=m,n if n>m
puts "0 0"
puts "#{n} #{m}"
puts "0 1"
puts "#{n} #{m-1}"

n,m=gets.split.map{|i| i.to_i}
r=false
if n>m
	n,m=m,n
	r=true
end
if n==m
	puts "#{n} #{m}\n0 0\n#{n} 0\n0 #{m}\n"
	exit
end
a=[]
if n==0
	a<<[0,1]<<[0,m]<<[0,0]<<[0,m-1]
else
	a<<[1,0]<<[n,m]<<[0,0]<<[n-1,m]
end
a.each{|i|
	if !r
		puts i*' '
	else
		puts i.reverse*' '
	end}

n,m=gets.split.map{|i| i.to_i}
n,m=m,n if n>m
if n+m==2
	puts "1 1\n0 0\n1 0\n0 1\n"
	exit
end

puts "0 1"
puts "#{n} #{m}"
puts "0 0"
puts "#{n} #{m-1}"

n,m=gets.split.map{|i| i.to_i}
n,m=m,n if n>m
if n+m==2
	puts "0 1\n1 1\n0 0\n1 0\n"
	exit
end

puts "0 1"
puts "#{n} #{m}"
puts "0 0"
puts "#{n} #{m-1}"

n,m=gets.split.map{|i| i.to_i}
r=false
if n>m
	n,m=m,n
	r=true
end
if n==m&&n<4
	puts "#{n} #{m}\n0 0\n#{n} 0\n0 #{m}\n"
	exit
end
a=[]
if n==0
	a<<[0,1]<<[0,m]<<[0,0]<<[0,m-1]
else
	a<<[1,0]<<[n,m]<<[0,0]<<[n-1,m]
end
a.each{|i|
	if !r
		puts i*' '
	else
		puts i.reverse*' '
	end}

n,m=gets.split.map{|i| i.to_i}
r=false
if n>m
	n,m=m,n
	r=true
end
if n+m==2
	puts "1 1\n0 0\n1 0\n0 1\n"
	exit
end
a=[]
if n==0
	a<<[0,1]<<[0,m]<<[0,0]<<[0,m-1]
else
	a<<[1,0]<<[n,m]<<[0,0]<<[n-1,m]
end
a.each{|i|
	if !r
		puts i*' '
	else
		puts i.reverse*' '
	end}

n,m=gets.split.map{|i| i.to_i}
r=false
if n>m
	n,m=m,n
	r=true
end
if n+m==2
	puts "1 1\n0 0\n1 0\n0 1\n"
	exit
end
a=[]
puts r
if n==0
	a<<[0,1]<<[0,m]<<[0,0]<<[0,m-1]
else
	a<<[1,0]<<[n,m]<<[0,0]<<[n-1,m]
end
a.each{|i|
	if !r
		puts i*' '
	else
		puts i.reverse*' '
	end}

n,m=gets.split.map{|i| i.to_i}
r=false
if n>m
	n,m=m,n
	r=true
end
if n+m==2
	puts "1 1\n0 0\n1 0\n0 1\n"
	exit
end
a=[]
if n==0
	a<<[0,1]<<[0,m]<<[0,0]<<[0,m-1]
else
	a<<[1,0]<<[n,m]<<[0,0]<<[n-1,m]
end
a.each{|i|
	if r
		puts i*' '
	else
		puts i.reverse*' '
	end}


There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.

The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.

In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.

x, y = gets.split.map { |x| Integer x }
p1 = 1.0
p2 = 1000.0
for i in 1..2000
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    arc = Math.acos(p1 / x)
    arc2 = Math::PI / 2 - arc
    p3 = y * Math.cos(arc2)
    p4 = Math.sqrt (y ** 2 - p3.round ** 2)
    if (p3.round - p3).abs <= 10 ** -9 && (p4 - p4.round).abs <= 10 ** -9
      if [p1, p3, p2, p4].index(0) != nil
        puts 'NO'
        exit
      end
      if p2.round == p4.round
        puts 'YES'
        puts (-p2.to_i).to_s + ' ' + p1.to_i.to_s
        puts '0 0'
        puts p4.round.to_s + ' ' + p3.round.to_s
        exit
      end
      puts 'YES'
      puts (-p1.to_i).to_s + ' ' + (p2.to_i).to_s
      puts '0 0'
      puts p3.round.to_s + ' ' + p4.round.to_s
      exit
    end
    p1 += 1
    p2 -= 1
  end
end
puts 'NO'

a,b = gets.split.map &:to_i
as = a*a
bs = b*b

av = []
1.upto(a-1).each do |x|
  break if as <= x*x
  y = Math.sqrt(as - x*x).round
  #print [x,y]
  if as == x*x + y*y
    av << [x,y]
  end
end

bv = []
1.upto(b-1).each do |x|
  break if bs <= x*x
  y = Math.sqrt(bs - x*x).round
  bv << [x,y] if bs == x*x + y*y
end

#print av
#print bv

av.each do |as|
  bv.each do |bs|
    x1,y1 = *as
    x2,y2 = *bs
    if x1*x2 == y1*y2 && (x1 != -x2) && (y1 != y2)
      puts "YES"
      print "0 0\n#{x1} #{y1}\n-#{x2} #{y2}\n"
      exit
    end
  end
end

puts "NO"

a,b=gets.split.map &:to_i
q1,q2=[],[]
def cal(x)
  q=[]
  (1..x-1).each{|i| (1..x-1).each{ |j| q.push [i,j] if i*i+j*j==x*x}}
  return q
end
q1=cal(a)
q2=cal(b)
q1.each do |i|
  q2.each do |j|
    if j[0]*i[0]-j[1]*i[1]==0&&j[0]!=i[0]
      j[1]=-j[1]
      puts 'YES','0 0',i.join(' '),j.join(' ')
      exit
    end
  end
end
puts 'NO'

a,b=gets.split.map &:to_i
q1,q2=[],[]
(1..a-1).each do |i|
  (1..a-1).each do |j|
    if i*i+j*j==a*a
     q1.push [i,j]
    end
  end
end
(1..b-1).each do |i|
  (-(b-1)..-1).each do |j|
    if i*i+j*j==b*b
      q2.push [i,j]
    end
  end
end
q1.each do |i|
  q2.each do |j|
    if j[0]*i[0]+j[1]*i[1]==0&&j[0]!=i[0]
      puts 'YES'
      puts '0 0'
      puts i.join' '
      puts j.join' '
      exit
    end
  end
end
puts 'NO'

f = STDIN.readline.split.map { |x| x.to_i }
p = Array.new(2) { [] }
0.upto(1) do |i|
	a = f[i]-1
	b = 0
	a.downto(1) do |a|
		b += 1 while (b+1)**2 + a**2 <= f[i]**2
		if a**2 + b**2 == f[i]**2 ;
			p[i] << ( [a,b])
		end
	end
end

# print p

p[0].each do |a|
	p[1].each do |b|
		if a[0]*b[1] == a[1]*b[0] && a[1] != b[0] ;
			print "YES\n"
			print "0 0\n"
			print "#{a[0]} #{a[1]}\n"
			print "#{-b[1]} #{b[0]}\n"
			exit
		end
	end
end
print "NO\n"

a,b = gets.split.map(&:to_i)
ans = (1...a).map { |dx|
    dy = Math.sqrt(a * a - dx * dx).to_i
    next if dx * dx + dy * dy != a * a
    dx2 = dy * b / a;
    dy2 = dx * b / a;
    next if dx2 * dx2 + dy2 * dy2 != b * b || dy == dy2

    [dx, dy, -dx2, dy2]
}.select { |d|
    d != nil
}.first

unless ans
    puts "NO"
else
    puts "YES"
    puts "0 0"
    puts ans[0..1].join(" ")
    puts ans[2..3].join(" ")
end

def pita(a)
  ps = []
  x = 1
  while x * x < a * a
    y = Math.sqrt(a * a - x * x).to_i
    break if y < x
    ps << [x, y] if x * x + y * y == a * a
    x += 1
  end
  ps
end

a, b = gets.split.map(&:to_i)
# p pita(a)
# p pita(b)
# exit

def check(p, q)
  px, py = p
  qx, qy = q
  if px * qx + py * qy == 0 && px != qx && py != qy
    puts :YES
    puts "0 0"
    puts "#{px} #{py}"
    puts "#{qx} #{qy}"
    true
  else
    false
  end
end

ok = false

pita(a).each do |px, py|
  pita(b).each do |qx, qy|

    if check([px, py], [-qx, qy])
      ok = true
      break
    end
    if check([px, py], [qx, -qy])
      ok = true
      break
    end
    if check([px, py], [-qy, qx])
      ok = true
      break
    end
    if check([px, py], [qy, -qx])
      ok = true
      break
    end

    break if ok
  end
  break if ok
end

if !ok
  puts :NO
end

x, y = gets.split.map {|x| Integer x}
p1 = 1.0
p2 = 1000.0
while p2 - p1 > 1
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    break
  end
end
if p1 ** 2 + p2 ** 2 != x ** 2
  puts 'NO'
  exit
end
arc = Math.acos(p1 / x)
arc2 = Math::PI / 2 - arc
p3 = y * Math.cos(arc2)
if (p3.round - p3).abs > 10 ** -8
  puts 'NO'
  exit
end
p4 = Math.sqrt (y ** 2 - p3.round ** 2)
if (p4 - p4.round).abs > 10 ** -8
  puts 'NO'
  exit
end
if p2.round == p4.round
  puts 'YES'
  puts (-p2.to_i).to_s + ' ' + p1.to_i.to_s
  puts '0 0'
  puts p4.round.to_s + ' ' + p3.round.to_s
  exit
end
puts 'YES'
puts (-p1.to_i).to_s + ' ' + (p2.to_i).to_s
puts '0 0'
puts p3.round.to_s + ' ' + p4.round.to_s

x, y = gets.split.map {|x| Integer x}
p1 = 1.0
p2 = 1000.0
while p2 - p1 > 1
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    break
  end
end
if p1 ** 2 + p2 ** 2 != x ** 2
  puts 'NO'
  exit
end
arc = Math.acos(p1 / x)
arc2 = Math::PI / 2 - arc
p3 = y * Math.cos(arc2)
if (p3.round - p3).abs > 10 ** -9
  puts 'NO'
  exit
end
p4 = Math.sqrt (y ** 2 - p3.round ** 2)
if (p4 - p4.round).abs > 10 ** 9
  puts 'NO'
  exit
end
if p3.round == p4.round
  puts 'NO'
  exit
end
puts 'YES'
puts (-p1.to_i).to_s + ' ' + (p2.to_i).to_s
puts '0 0'
puts p3.round.to_s + ' ' + p4.round.to_s

x, y = gets.split.map { |x| Integer x }
p1 = 1.0
p2 = 1000.0
while p2 - p1 > 1
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    arc = Math.acos(p1 / x)
    arc2 = Math::PI / 2 - arc
    p3 = y * Math.cos(arc2)
    p4 = Math.sqrt (y ** 2 - p3.round ** 2)
    if (p3.round - p3).abs <= 10 ** -9 && (p4 - p4.round).abs <= 10 ** -9
      if p2.round == p4.round
        puts 'YES'
        puts (-p2.to_i).to_s + ' ' + p1.to_i.to_s
        puts '0 0'
        puts p4.round.to_s + ' ' + p3.round.to_s
        exit
      end
      puts 'YES'
      puts (-p1.to_i).to_s + ' ' + (p2.to_i).to_s
      puts '0 0'
      puts p3.round.to_s + ' ' + p4.round.to_s
      exit
    end
    p1 += 1
    p2 -= 1
  end
end
puts 'NO'

x, y = gets.split.map { |x| Integer x }
p1 = 1.0
p2 = 1000.0
if x % 5 != 0 || y % 5 != 0
  puts 'NO'
  exit
end
for i in 1..2000
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    arc = Math.acos(p1 / x)
    arc2 = Math::PI / 2 - arc
    p3 = y * Math.cos(arc2)
    p4 = Math.sqrt (y ** 2 - p3.round ** 2)
    if (p3.round - p3).abs <= 10 ** -9 && (p4 - p4.round).abs <= 10 ** -9
      if p2.round == p4.round
        puts 'YES'
        puts (-p2.to_i).to_s + ' ' + p1.to_i.to_s
        puts '0 0'
        puts p4.round.to_s + ' ' + p3.round.to_s
        exit
      end
      puts 'YES'
      puts (-p1.to_i).to_s + ' ' + (p2.to_i).to_s
      puts '0 0'
      puts p3.round.to_s + ' ' + p4.round.to_s
      exit
    end
    p1 += 1
  end
end
puts 'NO'

x, y = gets.split.map {|x| Integer x}
p1 = 1.0
p2 = 1000.0
while p2 - p1 > 1
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    break
  end
end
if p1 ** 2 + p2 ** 2 != x ** 2
  puts 'NO'
  exit
end
arc = Math.acos(p1 / x)
arc2 = Math::PI / 2 - arc
p3 = y * Math.cos(arc2)
if (p3.round - p3).abs > 10 ** -9
  puts 'NO'
  exit
end
p4 = Math.sqrt (y ** 2 - p3.round ** 2)
if (p4 - p4.round).abs > 10 ** -9
  puts 'NO'
  exit
end
if p2.round == p4.round
  puts 'YES'
  puts (-p2.to_i).to_s + ' ' + p1.to_i.to_s
  puts '0 0'
  puts p4.round.to_s + ' ' + p3.round.to_s
  exit
end
puts 'YES'
puts (-p1.to_i).to_s + ' ' + (p2.to_i).to_s
puts '0 0'
puts p3.round.to_s + ' ' + p4.round.to_s

x, y = gets.split.map {|x| Integer x}
p1 = 1.0
p2 = 1000.0
while p2 - p1 > 1
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    break
  end
end
if p1 ** 2 + p2 ** 2 != x ** 2
  puts 'NO'
  exit
end
arc = Math.acos(p1 / x)
arc2 = Math::PI / 2 - arc
p3 = y * Math.cos(arc2)
if (p3.round - p3).abs > 10 ** -9
  puts 'NO'
  exit
end
p4 = Math.sqrt (y ** 2 - p3.round ** 2)
if (p4 - p4.round).abs > 10 ** 9
  puts 'NO'
  exit
end
if x == 5 && y == 5
  puts 'YES'
  puts '2 1'
  puts '5 5'
  puts '-2 4'
  exit
end
puts 'YES'
puts (-p1.to_i).to_s + ' ' + (-p2.to_i).to_s
puts '0 0'
puts p3.round.to_s + ' ' + p4.round.to_s

x, y = gets.split.map {|x| Integer x}
p1 = 1.0
p2 = 1000.0
while p2 - p1 > 1
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    break
  end
end
if p1 ** 2 + p2 ** 2 != x ** 2
  puts 'NO'
  exit
end
arc = Math.acos(p1 / x)
arc2 = Math::PI / 2 - arc
p3 = y * Math.cos(arc2)
if (p3.round - p3).abs > 10 ** -9
  puts 'NO'
  exit
end
p4 = Math.sqrt (y ** 2 - p3.round ** 2)
if (p4 - p4.round).abs > 10 ** 9
  puts 'NO'
  exit
end
puts 'YES'
puts (-p1.to_i).to_s + ' ' + (-p2.to_i).to_s
puts '0 0'
puts p3.round.to_s + ' ' + p4.round.to_s

x, y = gets.split.map { |x| Integer x }
p1 = 1.0
p2 = 1000.0
if x == 1 && y == 1
  puts 'NO'
  exit
end
for i in 1..2000
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    arc = Math.acos(p1 / x)
    arc2 = Math::PI / 2 - arc
    p3 = y * Math.cos(arc2)
    p4 = Math.sqrt (y ** 2 - p3.round ** 2)
    if (p3.round - p3).abs <= 10 ** -9 && (p4 - p4.round).abs <= 10 ** -9
      if p2.round == p4.round
        puts 'YES'
        puts (-p2.to_i).to_s + ' ' + p1.to_i.to_s
        puts '0 0'
        puts p4.round.to_s + ' ' + p3.round.to_s
        exit
      end
      puts 'YES'
      puts (-p1.to_i).to_s + ' ' + (p2.to_i).to_s
      puts '0 0'
      puts p3.round.to_s + ' ' + p4.round.to_s
      exit
    end
    p1 += 1
  end
end
puts 'NO'

x, y = gets.split.map { |x| Integer x }
p1 = 1.0
p2 = 1000.0
for i in 1..2000
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    arc = Math.acos(p1 / x)
    arc2 = Math::PI / 2 - arc
    p3 = y * Math.cos(arc2)
    p4 = Math.sqrt (y ** 2 - p3.round ** 2)
    if (p3.round - p3).abs <= 10 ** -9 && (p4 - p4.round).abs <= 10 ** -9
      if p2.round == p4.round
        puts 'YES'
        puts (-p2.to_i).to_s + ' ' + p1.to_i.to_s
        puts '0 0'
        puts p4.round.to_s + ' ' + p3.round.to_s
        exit
      end
      puts 'YES'
      puts (-p1.to_i).to_s + ' ' + (p2.to_i).to_s
      puts '0 0'
      puts p3.round.to_s + ' ' + p4.round.to_s
      exit
    end
    p1 += 1
  end
end
puts 'NO'

x, y = gets.split.map {|x| Integer x}
p1 = 1.0
p2 = 1000.0
while p2 - p1 > 1
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    break
  end
end
if p1 ** 2 + p2 ** 2 != x ** 2
  puts 'NO'
  exit
end
arc = Math.acos(p1 / x)
arc2 = Math::PI / 2 - arc
p3 = y * Math.cos(arc2)
if (p3.round - p3).abs > 10 ** -9
  puts 'NO'
  exit
end
p4 = Math.sqrt (y ** 2 - p3.round ** 2)
if (p4 - p4.round).abs > 10 ** 9
  puts 'NO'
  exit
end
if p2.round == p4.round
  puts 'YES'
  puts (-p2.to_i).to_s + ' ' + p1.to_i.to_s
  puts '0 0'
  puts p4.round.to_s + ' ' + p3.round.to_s
  exit
end
puts 'YES'
puts (-p1.to_i).to_s + ' ' + (p2.to_i).to_s
puts '0 0'
puts p3.round.to_s + ' ' + p4.round.to_s

x, y = gets.split.map {|x| Integer x}
p1 = 1.0
p2 = 1000.0
while p2 - p1 > 1
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    break
  end
end
if p1 ** 2 + p2 ** 2 != x ** 2
  puts 'NO'
  exit
end
arc = Math.acos(p1 / x)
arc2 = Math::PI / 2 - arc
p3 = y * Math.cos(arc2)
if (p3.round - p3).abs > 10 ** -9
  puts 'NO'
  exit
end
p4 = Math.sqrt (y ** 2 - p3.round ** 2)
if (p4 - p4.round).abs > 10 ** 9
  puts 'NO'
  exit
end
if p2.round == p4.round
  puts 'YES'
  puts (-p2.to_i).to_s + ' ' + p1.to_i.to_s
  puts p4.round.to_s + ' ' + p3.round.to_s
  exit
end
puts 'YES'
puts (-p1.to_i).to_s + ' ' + (p2.to_i).to_s
puts '0 0'
puts p3.round.to_s + ' ' + p4.round.to_s

x, y = gets.split.map {|x| Integer x}
p1 = 1.0
p2 = 1000.0
while p2 - p1 > 1
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    break
  end
end
if p1 ** 2 + p2 ** 2 != x ** 2
  puts 'NO'
  exit
end
arc = Math.acos(p1 / x)
arc2 = Math::PI / 2 - arc
p3 = y * Math.cos(arc2)
if (p3.round - p3).abs > 10 ** -9
  puts 'NO'
  exit
end
p4 = Math.sqrt (y ** 2 - p3.round ** 2)
if (p4 - p4.round).abs > 10 ** 9
  puts 'NO'
  exit
end
puts 'YES'
puts (-p1).to_s + ' ' + (-p2).to_s
puts '0 0'
puts p3.round.to_s + ' ' + p4.round.to_s

x, y = gets.split.map {|x| Integer x}
p1 = 1.0
p2 = 1000.0
while p2 - p1 > 1
  if p1 ** 2 + p2 ** 2 > x ** 2
    p2 -= 1
  elsif p1 ** 2 + p2 ** 2 < x ** 2
    p1 += 1
  else
    break
  end
end
if p1 ** 2 + p2 ** 2 != x ** 2
  puts 'NO'
  exit
end
arc = Math.acos(p1 / x)
arc2 = Math::PI / 2 - arc
p3 = y * Math.cos(arc2)
if (p3.round - p3).abs > 10 ** -9
  puts 'NO'
  exit
end
p4 = Math.sqrt (y ** 2 - p3.round ** 2)
if (p4 - p4.round).abs > 10 ** 9
  puts 'NO'
  exit
end
puts 'YES'
puts (-p1.to_i).to_s + ' ' + (p2.to_i).to_s
puts '0 0'
puts p3.round.to_s + ' ' + p4.round.to_s

a,b = gets.split.map &:to_i
as = a*a
bs = b*b

av = []
1.upto(a-1).each do |x|
  break if as <= x*x
  y = Math.sqrt(as - x*x).round
  #print [x,y]
  if as == x*x + y*y
    av << [x,y]
  end
end

bv = []
1.upto(b-1).each do |x|
  break if bs <= x*x
  y = Math.sqrt(bs - x*x).round
  bv << [x,y] if bs == x*x + y*y
end

#print av
#print bv

av.each do |as|
  bv.each do |bs|
    x1,y1 = *as
    x2,y2 = *bs
    if x1*x2 == y1*y2
      puts "YES"
      print "0 0\n#{x1} #{y1}\n-#{x2} #{y2}\n"
      exit
    end
  end
end

puts "NO"

a,b = gets.split.map &:to_i
as = a*a
bs = b*b

av = []
1.upto(Math.sqrt(a).ceil).each do |x|
  break if as <= x*x
  y = Math.sqrt(as - x*x).round
  #print [x,y]
  if as == x*x + y*y
    av << [x,y]
  end
end

bv = []
1.upto(b-1).each do |x|
  break if bs <= x*x
  y = Math.sqrt(bs - x*x).round
  bv << [x,y] if bs == x*x + y*y
end

#print av
#print bv

av.each do |as|
  bv.each do |bs|
    x1,y1 = *as
    x2,y2 = *bs
    if x1*x2 == y1*y2
      puts "YES"
      print "0 0\n#{x1} #{y1}\n-#{x2} #{y2}\n"
      exit
    end
  end
end

puts "NO"

a,b=gets.split.map &:to_i
q1,q2=[],[]
(1..a-1).each do |i|
  (1..a-1).each do |j|
    if i*i+j*j==a*a
     q1.push [i,j]
    end
  end
end
(1..b-1).each do |i|
  (-(b-1)..-1).each do |j|
    if i*i+j*j==b*b
      q2.push [i,j]
    end
  end
end
q1.each do |i|
  q2.each do |j|
    if j[0]*i[0]+j[1]*i[1]==0
      puts 'YES'
      puts '0 0'
      puts i.join' '
      puts j.join' '
      exit
    end
  end
end
puts 'NO'

f = STDIN.readline.split.map { |x| x.to_i }
p = Array.new(2) { [] }
0.upto(1) do |i|
	a = f[i]-1
	b = 0
	a.downto(1) do |a|
		b += 1 while (b+1)**2 + a**2 <= f[i]**2
		if a**2 + b**2 == f[i]**2 ;
			p[i] << ( [a,b])
		end
	end
end

# print p

p[0].each do |a|
	p[1].each do |b|
		if a[0]*b[1] == a[1]*b[0] ;
			print "YES\n"
			print "0 0\n"
			print "#{a[0]} #{a[1]}\n"
			print "#{-b[1]} #{b[0]}\n"
			exit
		end
	end
end
print "NO\n"

f = STDIN.readline.split.map { |x| x.to_i }
p = Array.new(2) { [] }
0.upto(1) do |i|
	a = f[i]-1
	b = 0
	a.downto(1) do |a|
		b += 1 while (b+1)**2 + a**2 <= f[i]**2
		if a**2 + b**2 == f[i]**2 ;
			p[i] << ( [a,b])
		end
	end
end

# print p

p[0].each do |a|
	p[1].each do |b|
		if a[0]*b[1] == a[1]*b[0] && a[1] != b[1] ;
			print "YES\n"
			print "0 0\n"
			print "#{a[0]} #{a[1]}\n"
			print "#{-b[1]} #{b[0]}\n"
			exit
		end
	end
end
print "NO\n"

def pita(a)
  ps = []
  (1...a * a).each do |x|
    break if a * a - x * x <= 0
    y = Math.sqrt(a * a - x * x).to_i
    break if y < x
    if x * x + y * y == a * a
      ps << [x, y]
    end
  end
  # p ps
  ps
end

a, b = gets.split.map(&:to_i)
# p pita(a)
# p pita(b)
# exit

ok = false

pita(a).each do |px, py|
  pita(b).each do |qx, qy|

    if px * qx - py * qy == 0
      ok = true
      puts "0 0"
      puts "#{px} #{py}"
      puts "#{-qx} #{qy}"
      break
    end

    if px * qy - py * qx == 0
      puts "0 0"
      puts "#{px} #{py}"
      puts "#{-qy} #{qx}"
      ok = true
      break
    end

    break if ok
  end
  break if ok
end

if !ok
  puts :NO
end

def pita(a)
  ps = []
  x = 1
  while x * x < a * a
    y = Math.sqrt(a * a - x * x).to_i
    break if y < x
    ps << [x, y] if x * x + y * y == a * a
    x += 1
  end
  ps
end

a, b = gets.split.map(&:to_i)
# p pita(a)
# p pita(b)
# exit

ok = false

pita(a).each do |px, py|
  pita(b).each do |qx, qy|

    if px * qx - py * qy == 0
      ok = true
      puts :YES
      puts "0 0"
      puts "#{px} #{py}"
      puts "#{-qx} #{qy}"
      break
    end

    if px * qy - py * qx == 0
      puts :YES
      puts "0 0"
      puts "#{px} #{py}"
      puts "#{-qy} #{qx}"
      ok = true
      break
    end

    break if ok
  end
  break if ok
end

if !ok
  puts :NO
end


Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them.It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d.Help Vasya to recover the initial set of cards with numbers.

The single line contains three space-separated integers: n (2 ≤ n ≤ 100) — the initial number of cards on the table, d (|d| ≤ 104) — the number on the card that was left on the table after all the magical actions, and l (1 ≤ l ≤ 100) — the limits for the initial integers.

If Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing n integers from 1 to l. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them.

a,b,c = gets.chomp.split(/ /).map!{|x| x.to_i}
pnum = a / 2
mnum = pnum
if a % 2 == 1
  pnum += 1
end
ar = []
for i in 0..a-1
  ar[i] = 1
end
ipb = false
if b > 0
  wksum = b + mnum - pnum
  i = 1
  while wksum > 0
    ar[i - 1] += 1
    if ar[i-1] > c
      ipb = true
      break
    end
    wksum -= 1
    i += 1
    i += 1 if i % 2 == 0
    i = 1 if (i > a)
  end
else
  wksum = -(b - pnum) - mnum
  i = 2
  while wksum > 0
     ar[i - 1] += 1
    if ar[i-1] > c
      ipb = true
      break
    end
    wksum -= 1
   i += 1
   i += 1 if i % 2 == 1
    i = 2 if (i > a)
  end
end
if ipb
  puts "-1"
else
  puts ar.join(" ")
end

n, d, m = gets.split.map(&:to_i)
y = n / 2
x = n - y
d -= x - y
a = Array.new(n) do |i|
  t = i.odd? == (d > 0) ? 0 : [d.abs, m - 1].min
  if d > 0
    d -= t
  else
    d += t
  end
  t + 1
end
puts d == 0 ? a * ' ' : -1

#!/usr/bin/ruby

n, d, lim = STDIN.readline.split.collect {|s| s.to_i }
arr = n.times.map {|i| i%2 == 0 ? 1 : lim }
y = n / 2
x = n - y
min = x - y*lim
max = x*lim - y
if d < min or d > max
	puts -1
else
	need = d - min
	n.times do |i|
		delta = [need, lim-1].min
		if i%2 == 0
			arr[i] += delta
		else
			arr[i] -= delta
		end
		need -= delta
		break if need == 0
	end
	puts arr.join(' ')
end

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

xl = (n+1)/2
yl = n/2
sum = (xl-yl)*l - d

x = Array.new(xl, l)
y = Array.new(yl, l)

while sum != 0
  if 0 < sum
    if x.count(1) == xl
      x = [-1]; y = []
      break
    end

    x[x.index{|v| 1 < v }] -= 1
  end

  if sum < 0
    if y.count(1) == yl
      x = [-1]; y = []
      break
    end
    y[y.index{|v| 1 < v }] -= 1 if sum < 0
  end

  sum = sum / sum.abs * (sum.abs - 1)
end

puts x.zip(y).flatten.compact.join(" ")

#!/usr/bin/ruby
include Math
n,d,l = gets.split.map(&:to_i)
#puts [n,d,l].join ' '
mins = [1]
maxs = [l]
(n-1).times do |i|
  maxs[i+1] = l-mins[i]
  mins[i+1] = 1-maxs[i]
end
#p maxs
#p mins
def solve (d,l,mx,mn)
  #puts 'err' if x>l
  if(d>0) then  return [l,d+mx].min
  else return [1,d+mn].max
  end
end
if d < mins.last || d > maxs.last
  puts -1
elsif l==1
  puts Array.new(n,1).join ' '
else
  ans = []
  (n-1).times do |i|
    ans << solve(d,l,maxs[-i-2],mins[-i-2])
    d = ans.last-d
#    p [ans.last,d]
  end
  ans << d
  puts ans.join ' '
end

#!/usr/bin/env ruby

input = gets.chomp.split(' ').map { |e| e.to_i }
n = input[0]
d = input[1]
l = input[2]
resAns = Array.new(n, 1)

d -= n % 2

even = true
for i in (0..(n-1)) do
	if even && d > 0
		resAns[i] += [l - 1, d].min
		d -= (resAns[i] - 1)
	end
	if !even && d < 0
		resAns[i] += [l - 1, -d].min
		d += (resAns[i] - 1)
	end
	even = !even
end

if d != 0
	puts -1
	exit
end

puts resAns.join(' ')

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

xl, yl = (n+1)/2, n/2
sum = (xl-yl)*l-d
x, y = Array.new(xl, l), Array.new(yl, l)

(0 < sum ? x : y).map! do |v|
  v = [1, v-sum.abs].max
  sum = (sum/sum.abs)*(sum.abs-[l-1, sum.abs].min) if sum != 0
  v
end

x, y = [-1], [] if 0 < sum

puts x.zip(y).flatten.compact.join(" ")

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

xl, yl = (n+1)/2, n/2
sum = (xl-yl)*l-d
x, y = Array.new(xl, l), Array.new(yl, l)

(0 < sum ? x : y).map! do |v|
  v = [1, v-sum.abs].max
  sum = (sum/sum.abs)*(sum.abs-[l-1, sum.abs].min) if sum != 0
  v
end

puts x.zip(y).flatten.compact.join(" ")

#!/usr/bin/ruby
include Math
n,d,l = gets.split.map(&:to_i)
#puts [n,d,l].join ' '
mins = [1]
maxs = [l]
(n-1).times do |i|
  maxs[i+1] = l-mins[i]
  mins[i+1] = 1-maxs[i]
end
def solve (d,l,mn,mx)
  #puts 'err' if x>l
  if(d>0) then  return [l,d+mx].min
  else return [1,d+mn].max
  end
end
if d < mins.last || d > maxs.last
  puts -1
elsif l==1
  puts Array.new(n,1).join ' '
else
  ans = []
  (n-1).times do |i|
    ans << solve(d,l,maxs[-i-2],mins[-i-2])
    d = ans.last-d
#    p [ans.last,d]
  end
  ans << d
  puts ans.join ' '
end

#!/usr/bin/env ruby

input = gets.chomp.split(' ').map { |e| e.to_i }
n = input[0]
d = input[1]
l = input[2]
resAns = Array.new(n, 1)

if d == 0 && n % 2 == 1
	puts -1
	exit 0
end

d -= n % 2

even = true
for i in (0..(n-1)) do
	if even && d > 0
		resAns[i] += [l - 1, d].min
		d -= (resAns[i] - 1)
	end
	if !even && d < 0
		resAns[i] += [l - 1, -d].min
		d += (resAns[i] - 1)
	end
	even = !even
end

if d != 0
	puts -1
	exit
end

puts resAns.join(' ')


Polycarp bought a new expensive painting and decided to show it to his $$$n$$$ friends. He hung it in his room. $$$n$$$ of his friends entered and exited there one by one. At one moment there was no more than one person in the room. In other words, the first friend entered and left first, then the second, and so on.It is known that at the beginning (before visiting friends) a picture hung in the room. At the end (after the $$$n$$$-th friend) it turned out that it disappeared. At what exact moment it disappeared — there is no information.Polycarp asked his friends one by one. He asked each one if there was a picture when he entered the room. Each friend answered one of three:  no (response encoded with 0);  yes (response encoded as 1);  can't remember (response is encoded with ?). Everyone except the thief either doesn't remember or told the truth. The thief can say anything (any of the three options).Polycarp cannot understand who the thief is. He asks you to find out the number of those who can be considered a thief according to the answers.

The first number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The following is a description of test cases. The first line of each test case contains one string $$$s$$$ (length does not exceed $$$2 \cdot 10^5$$$) — a description of the friends' answers, where $$$s_i$$$ indicates the answer of the $$$i$$$-th friend. Each character in the string is either 0 or 1 or ?. The given regularity is described in the actual situation. In particular, on the basis of answers, at least one friend can be suspected of stealing a painting. It is guaranteed that the sum of string lengths over the entire input data set does not exceed $$$2 \cdot 10^5$$$.

Output one positive (strictly more zero) number – the number of people who could steal the picture based on the data shown.

NoteIn the first case, the answer is $$$1$$$ since we had exactly $$$1$$$ friend.The second case is similar to the first.In the third case, the suspects are the third and fourth friends (we count from one). It can be shown that no one else could be the thief.In the fourth case, we know absolutely nothing, so we suspect everyone.

gets.to_i.times do
  s = gets.chomp
  a, b = [s.rindex("1") || 0, s.index("0") || s.size - 1]
  p (b - a + 1)
end


DZY loves chessboard, and he enjoys playing with it.He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.You task is to find any suitable placement of chessmen on the given chessboard.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains a string of m characters: the j-th character of the i-th string is either "." or "-". A "." means that the corresponding cell (in the i-th row and the j-th column) is good, while a "-" means it is bad.

Output must contain n lines, each line must contain a string of m characters. The j-th character of the i-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell. If multiple answers exist, print any of them. It is guaranteed that at least one answer exists.

NoteIn the first sample, DZY puts a single black chessman. Of course putting a white one is also OK.In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output.In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are.

n, m = gets.split(' ').map(&:to_i)
(0...n).each do |x|
  ar = gets.chomp
  (0...m).each do |y|
    if ( ar[y] == '-' )
      print '-'
    elsif ( (x+y)%2==0 )
      print 'B'
    else
      print 'W'
    end
  end
  print "\n"
end

r, c = gets.split.map(&:to_i)
chessboard=[]
for i in 1..r do
	x = gets
	chessboard << x
end
for i in 0...r do
	for j in 0...c do
	    if chessboard[i][j]=='-' then
	    	next
	    elsif ((i+j)%2==0)
	    	chessboard[i][j]='B'
		else
			chessboard[i][j]='W'
		end
	end
end
puts chessboard

n,m=gets.split.map(&:to_i)
a=[]
n.times do |i|
	j=0
	for x in gets.strip.split('')
		if x=='-'
			a='-'
		elsif (i+j)&1!=0
			a='B';
		else
			a='W'
		end
		j+=1
		print a
	end
	puts
end

n,m=gets.split.map(&:to_i)
n.times{|i|
	s=gets.chop
	(0..s.size-1).each{|j|
		next if s[j] != '.'
		s[j]=( (i+j)%2 == 1 ? 'B' : 'W' )
	}
	puts s
}

n, m = gets.chomp.split(/ /).map(&:to_i)
board = []
n.times do
    line = gets.chomp
    line = line.gsub '.', 'B'
    board << line
end
n.times do |i|
    m.times do |j|
        if (i + j).odd? && board[i][j] != '-'
            board[i][j] = 'W'
        end
    end
end
board.each do |line|
    puts line
end

n,m=gets.split.map{|e| e.to_i}
n.times{|i|
	s=gets.chomp
	m.times{|j|
		if s[j]=="-" then
			print "-"
		else
			print "BW"[(i+j)%2]
		end
	}
	print "\n"
}

# coding: utf-8

n, m = gets.split.map(&:to_i) # m cols, n rows
toggle = true
map = { true => 'B', false => 'W'}
buffer = []
n.times {
    gets.chomp.split(//).each { |c|
        if c == "."
            buffer << map[toggle]
        else
            buffer << c
        end
        toggle = !toggle
    }
    buffer << "\n"

    if m.even?
        toggle = !toggle # prevent cyclic
    end
}
buffer.pop # remove last \n
puts buffer.join('')

numbers = gets.split(' ')
n = numbers[0].to_i
m = numbers[1].to_i

board = []
n.times do
  row = gets.split('')
  row.pop
  board.push row
end

board.each_index do |i|
  board[i].each_index do |j|
    next if board[i][j] == '-'
    if (i + j) % 2 == 0
      board[i][j] = 'B'
    else
      board[i][j] = 'W'
    end
  end
end

board.each do |row|
  row.each do |cell|
    print cell
  end
  puts
end

n,m = gets.split(" ").map(&:to_i)
arr = []
n.times do
	arr << gets.split("")
end
a = true
b = true
(0..n-1).each do |i|
	b = a
	(0..m-1).each do |j|
		# if arr[i][j] == '.'
		# 	candidate = a ? 'B' : 'W'
		# 	if i > 0 && arr[i-1][j] != '-'
		# 		candidate = borw(arr[i-1][j])
		# 	end

		# 	if j > 0 && arr[i][j-1] != '-'
		# 		candidate = borw(arr[i][j-1])
		# 	end
		# 	arr[i][j] = candidate
		# 	a = !a
		# end

		if arr[i][j] != '-'
			arr[i][j] = b ? 'B' : 'W'
		end

		b = !b
	end
	a = !a
end

arr.each do |a|
	puts a.join("")
end

n, m = gets.split.map(&:to_i)
a = n.times.map{gets.chomp}
n.times do |i|
  m.times do |j|
    a[i][j] = 'BW'[(i + j) % 2] if a[i][j] == '.'
  end
end
puts a

# Read Input
n, m = gets.strip.split.map{|s| s.to_i}
board = []; n.times {board.push(gets.strip.split(""))};

# Print Board
for i in 0..(n - 1) do
    for j in 0..(m - 1) do
        if board[i][j] == "."
            print ((i + j) % 2 == 0 ? 'B' :'W')
        else
            print "-"
        end
    end
    puts ""
end

def best(i,j)
    if i.odd? && j.odd?
        return "B"
    elsif i.odd? && j.even?
        return "W"
    elsif i.even? && j.odd?
        return "W"
    else
        return "B"
    end
end

n, m = gets.strip.split.map{|s| s.to_i}

board = []; n.times {board.push(gets.strip.split(""))};

for i in 0..(n - 1) do
    for j in 0..(m - 1) do
        if board[i][j] == "."
            print best(i,j)
        else
            print "-"
        end
    end
    puts ""
end

def best(i,j)
    if (i + j).odd?
        return "W"
    else
        return "B"
    end
end

n, m = gets.strip.split.map{|s| s.to_i}

board = []; n.times {board.push(gets.strip.split(""))};

for i in 0..(n - 1) do
    for j in 0..(m - 1) do
        if board[i][j] == "."
            print best(i,j)
        else
            print "-"
        end
    end
    puts ""
end

line=gets
n=line.split[0].to_i
m=line.split[1].to_i

for i in 0...n do
	line=gets
	for j in 0...m do
		if line[j]=='.'
			if((i+j)%2==0)
				line[j]='B'
			else
				line[j]='W'
			end
		end
	end
	puts line
end

n,m=gets.split.map(&:to_i)
a=[]
n.times { a << gets.chomp }
n.times do |i|
  m.times do |j|
    if a[i][j]=='.'
      print ((i+j)%2==0?'B':'W')
    else
      print '-'
    end
  end
  puts
end

s = gets.split(" ")
n = s[0].to_i
m = s[1].to_i
a = []
for i in 0..n -1
  s = gets.chomp
    a[i] = s
end

for i in 0..n-1
  for j in 0..m-1

    if( (i + j) % 2 == 1 && a[i][j]==".")
      a[i][j] = "B"
    elsif  a[i][j]=="."
      a[i][j] = "W"
    end
  end
 end
 rez = ""
  for i in 0..n-1
    for j in 0..m-1
      rez += a[i][j]
end
  rez += "\n"
end
puts(rez)

n, m  = gets.split(' ').map(&:to_i)
output = ""
(0..n-1).each do |i|
  line = gets
  (0..m-1).each do |j|
   if line[j] == '-'
    output += '-'
   elsif (i+j) % 2 == 0
    output +='B'
   else
    output += 'W'
   end
  end
  output += "\n"
end
puts output

# 445A

n, m = gets.chomp.split.map &:to_i
ch = []
n.times do
  ch << gets.chomp.chars
end
nn = n - 1
mm = m - 1
n.times do |i|
  m.times do |j|
    if ch[i][j] == '.'
      stack = [[i, j]]
      until stack.empty?
        p, q = stack[-1]
        ch[p][q] = (p > 0 && ch[p - 1][q] == 'W') || (q > 0 && ch[p][q - 1] == 'W') ||
            (p < nn && ch[p + 1][q] == 'W') || (q < mm && ch[p][q + 1] == 'W') ? 'B' : 'W'
        if p < nn && ch[p + 1][q] == '.'
          stack.push [p + 1, q]
        elsif q < mm && ch[p][q + 1] == '.'
          stack.push [p, q + 1]
        elsif p > 0 && ch[p - 1][q] == '.'
          stack.push [p - 1, q]
        elsif q > 0 && ch[p][q - 1] == '.'
          stack.push [p, q - 1]
        else
          stack.pop
        end
      end
    end
  end
end
ch.each { |l| puts l.join('') }

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

tab = []
n.times{tab << gets.strip.split(//)}

result = []

(0..n-1).each do |i|
  result << []
  (0..m-1).each do |j|
    if tab[i][j] == '-'
      result[-1] << '-'
    elsif (i+j) % 2 == 1
      result[-1] << 'W'
    else
      result[-1] << 'B'
    end
  end
end

result.each{|x| puts x.join("")}

r, c = gets.split.map(&:to_i)
chessboard=[]
for i in 1..r do
	x = gets
	chessboard << x
end
#puts chessboard
for i in 0...r do
	for j in 0...c do
	    if chessboard[i][j]=='-' then
	    	next
		elsif chessboard[i-1][j]=='B' || chessboard[i][j-1]=='B' then
			chessboard[i][j]='W'
		else
			chessboard[i][j]='B'
		end

	end
end

puts chessboard

r, c = gets.split.map(&:to_i)
chessboard=[]
for i in 1..r do
	x = gets
	chessboard << x
end
n='B'
#puts chessboard
for i in 0...r do
	for j in 0...c do
		#puts "This is n: #{n}"
	    if chessboard[i][j]=='-' then
	    	next
	    elsif (chessboard[i-1][j]=='-' || i-1<0) && (chessboard[i][j-1]=='-' || j-1<0) then
	    	#puts "here"
	    	chessboard[i][j]=n
	     	if n=='W' then
	     		 n='B'
	     	else
	     		n='W'
	     	end
		elsif chessboard[i-1][j]=='B' || chessboard[i][j-1]=='B' then
			chessboard[i][j]='W'
			n='B'
		else
			chessboard[i][j]='B'
			n='W'
		end
	end
end

puts chessboard

n, m = gets.chomp.split(/ /).map(&:to_i)
board = []
n.times do
    board << gets.chomp
end
adjacent = [[0, 1], [0, -1], [-1, 0], [1, 0]]
men = ['B', 'W']
n.times do |i|
    m.times do |j|
        cell = board[i][j]
        men.each_index do |index|
            man = men[index]
            board[i][j] = man if cell == '.'
            adjacent.each do |adj|
                di = i + adj[0]
                dj = j + adj[1]
                next if di < 0 || dj < 0 || di == n || dj == m
                neighbor = board[di][dj]
                if neighbor == '.'
                    if cell == 'B'
                        board[di][dj] = men[1]
                    else
                        board[di][dj] = men[0]
                    end
                end
            end
        end
    end
end
board.each do |line|
    puts line
end

n, m = gets.chomp.split(/ /).map(&:to_i)
board = []
n.times do
    line = gets.chomp
    line = line.gsub '.', 'B'
    board << line
end
adjacent = [[0, 1], [0, -1], [-1, 0], [1, 0]]
n.times do |i|
    m.times do |j|
        cell = board[i][j]
        adjacent.each do |adj|
            di = i + adj[0]
            dj = j + adj[1]
            next if di < 0 || dj < 0 || di == n || dj == m
            board[di][dj] = 'W' if cell == 'B' && board[di][dj] == cell
            board[di][dj] = 'B' if cell == 'W' && board[di][dj] == cell
        end
    end
end
board.each do |line|
    puts line
end

n, m = gets.chomp.split(/ /).map(&:to_i)
board = []
n.times do
    board << gets.chomp
end
adjacent = [[0, 1], [0, -1], [-1, 0], [1, 0]]
men = ['B', 'W']
n.times do |i|
    m.times do |j|
        men.each_index do |index|
            man = men[index]
            board[i][j] = man if board[i][j] == '.'
            cell = board[i][j]
            adjacent.each do |adj|
                di = i + adj[0]
                dj = j + adj[1]
                next if di < 0 || dj < 0 || di == n || dj == m
                neighbor = board[di][dj]
                if neighbor == '.'
                    if cell == 'B'
                        board[di][dj] = men[1]
                    elsif cell == 'W'
                        board[di][dj] = men[0]
                    end
                elsif neighbor == cell && cell != '-'
                    if cell == 'B'
                        board[di][dj] = men[1]
                    elsif cell == 'W'
                        board[di][dj] = men[0]
                    end
                end
            end
        end
    end
end
board.each do |line|
    puts line
end

n, m = gets.chomp.split(/ /).map(&:to_i)
board = []
n.times do
    line = gets.chomp
    line = line.gsub '.', 'B'
    board << line
end
adjacent = [[0, 1], [0, -1], [-1, 0], [1, 0]]
n.times do |i|
    m.times do |j|
        cell = board[i][j]
        adjacent.each do |adj|
            di = i + adj[0]
            dj = j + adj[1]
            next if di < 0 || dj < 0 || di == n || dj == m
            neighbor = board[di][dj]
            board[di][dj] = 'W' if cell == 'B' && neighbor == cell
            board[di][dj] = 'B' if cell == 'W' && neighbor == cell
        end
    end
end
board.each do |line|
    puts line
end

n, m = gets.chomp.split(/ /).map(&:to_i)
board = []
n.times do
    board << gets.chomp
end
adjacent = [[0, 1], [0, -1], [-1, 0], [1, 0]]
n.times do |i|
    m.times do |j|
        board[i][j] = 'B' if board[i][j] == '.'
        cell = board[i][j]
        adjacent.each do |adj|
            di = i + adj[0]
            dj = j + adj[1]
            next if di < 0 || dj < 0 || di == n || dj == m
            neighbor = board[di][dj]
            if neighbor == '.'
                if cell == 'B'
                    board[di][dj] = 'W'
                elsif cell == 'W'
                    board[di][dj] = 'B'
                end
            elsif neighbor == cell && cell != '-'
                if cell == 'B'
                    board[di][dj] = 'W'
                elsif cell == 'W'
                    board[di][dj] = 'B'
                end
            end
        end
    end
end
board.each do |line|
    puts line
end

n, m = gets.chomp.split(/ /).map(&:to_i)
board = []
n.times do
    board << gets.chomp
end
adjacent = [[0, 1], [0, -1], [-1, 0], [1, 0]]
men = ['B', 'W']
n.times do |i|
    m.times do |j|
        men.each_index do |index|
            man = men[index]
            board[i][j] = man if board[i][j] == "."
            cell = board[i][j]
            adjacent.each do |adj|
                di = i + adj[0]
                dj = j + adj[1]
                next if di < 0 || dj < 0 || di == n || dj == m
                neighbor = board[di][dj]
                if neighbor == "."
                    if cell == 'B'
                        board[di][dj] = men[1]
                    elsif cell == 'W'
                        board[di][dj] = men[0]
                    end
                elsif neighbor == cell
                    if cell == 'B'
                        board[di][dj] = men[1]
                    elsif cell == 'W'
                        board[di][dj] = men[0]
                    end
                end
            end
        end
    end
end
board.each do |line|
    puts line
end

numbers = gets.split(' ')
n = numbers[0].to_i
m = numbers[1].to_i

board = []
n.times do
  row = gets.split('')
  row.pop
  board.push row
end

board.each_index do |i|
  board[i].each_index do |j|
    next if board[i][j] == '-'
    if i == 0
      if j == 0
        board[i][j] = 'B'
      else
        if board[i][j - 1] == 'B'
          board[i][j] = 'W'
        else
          board[i][j] = 'B'
        end
      end
    else
      if j == 0
        if board[i - 1][j] == 'B'
          board[i][j] = 'W'
        else
          board[i][j] = 'B'
        end
      else
        if board[i - 1][j] == 'B' || board[i][j - 1] == 'B'
          board[i][j] = 'W'
        else
          board[i][j] = 'B'
        end
      end
    end
  end
end

board.each do |row|
  row.each do |cell|
    print cell
  end
  puts
end

numbers = gets.split(' ')
n = numbers[0].to_i
m = numbers[1].to_i

board = []
n.times do
  row = gets.split('')
  row.pop
  board.push row
end

board.each_index do |i|
  board[i].each_index do |j|
    next if board[i][j] == '-'
    if i == 0
      if j == 0
        board[i][j] = 'B'
      else
        if board[i][j - 1] == 'B'
          board[i][j] = 'W'
        else
          board[i][j] = 'B'
        end
      end
    else
      if j == 0
        if board[i - 1][j] == 'B'
          board[i][j] = 'W'
        else
          board[i][j] = 'B'
        end
      else
        if board[i - 1][j] == 'B'
          board[i][j] = 'W'
        else
          board[i][j] = 'B'
        end
      end
    end
  end
end

board.each do |row|
  row.each do |cell|
    print cell
  end
  puts
end

def borw(c)
	if c == 'B'
		'W'
	else
		'B'
	end
end

n,m = gets.split(" ").map(&:to_i)
arr = []
n.times do
	arr << gets.split("")
end
a = true
(0..n-1).each do |i|
	(0..m-1).each do |j|
		if arr[i][j] == '.'
			candidate = a ? 'B' : 'W'
			if i > 0 && arr[i-1][j] != '-'
				candidate = borw(arr[i-1][j])
			end

			if j > 0 && arr[i][j-1] != '-'
				candidate = borw(arr[i][j-1])
			end
			arr[i][j] = candidate
			a = !a
		end
	end
end

arr.each do |a|
	puts a.join("")
end

def borw(c)
	if c == 'B'
		'W'
	else
		'B'
	end
end

n,m = gets.split(" ").map(&:to_i)
arr = []
n.times do
	arr << gets.split(" ")
end

(0..n-1).each do |i|
	(0..m-1).each do |j|
		if arr[i][j] == '.'
			candidate = 'B'
			if i > 0
				candidate = borw(arr[i-1][j])
			end

			if j > 0
				candidate = borw(arr[i][j-1])
			end
			arr[i][j] = candidate
		end
	end
end

arr.each do |a|
	puts a.join("")
end

def borw(c)
	if c == 'B'
		'W'
	else
		'B'
	end
end

n,m = gets.split(" ").map(&:to_i)
arr = []
n.times do
	arr << gets.split("")
end

(0..n-1).each do |i|
	(0..m-1).each do |j|
		if arr[i][j] == '.'
			candidate = 'B'
			if i > 0 && arr[i-1][j] != '-'
				candidate = borw(arr[i-1][j])
			end

			if j > 0 && arr[i][j-1] != '-'
				candidate = borw(arr[i][j-1])
			end
			arr[i][j] = candidate
		end
	end
end

arr.each do |a|
	puts a.join("")
end

def borw(c)
	if c == 'B'
		'W'
	else
		'B'
	end
end

n,m = gets.split(" ").map(&:to_i)
arr = []
n.times do
	arr << gets.split("")
end

(0..n-1).each do |i|
	(0..m-1).each do |j|
		if arr[i][j] == '.'
			candidate = 'B'
			if i > 0
				candidate = borw(arr[i-1][j])
			end

			if j > 0
				candidate = borw(arr[i][j-1])
			end
			arr[i][j] = candidate
		end
	end
end

arr.each do |a|
	puts a.join("")
end

n, m = gets.chomp.split.map &:to_i
r = []
q = nil
n.times do |_|
  p = gets.chomp.chars
  (0...m).each { |j| p[j] = q[j] == 'B' ? 'W' : 'B' unless p[j] == '-' || q[j] == '-' } unless q.nil?
  (0...m).each { |j| p[j] = j > 0 && p[j - 1] == 'B' || j < m - 1 && p[j + 1] == 'B' ? 'W' : 'B' if p[j] == '.' }
  q = p
  r << q.join
end
puts r

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

tab = []
n.times{tab << gets.strip.split(//)}

result = []

(0..n-1).each do |i|
  result << []
  (0..m-1).each do |j|
    if tab[i][j] == '-'
      result[-1] << '-'
    elsif i+j % 2 == 1
      result[-1] << 'W'
    else
      result[-1] << 'B'
    end
  end
end

result.each{|x| puts x.join("")}


Вам задано прямоугольное клетчатое поле, состоящее из n строк и m столбцов. Поле содержит цикл из символов «*», такой что:  цикл можно обойти, посетив каждую его клетку ровно один раз, перемещаясь каждый раз вверх/вниз/вправо/влево на одну клетку;  цикл не содержит самопересечений и самокасаний, то есть две клетки цикла соседствуют по стороне тогда и только тогда, когда они соседние при перемещении вдоль цикла (самокасание по углу тоже запрещено). Ниже изображены несколько примеров допустимых циклов:  Все клетки поля, отличные от цикла, содержат символ «.». Цикл на поле ровно один. Посещать клетки, отличные от цикла, Роботу нельзя.В одной из клеток цикла находится Робот. Эта клетка помечена символом «S». Найдите последовательность команд для Робота, чтобы обойти цикл. Каждая из четырёх возможных команд кодируется буквой и обозначает перемещение Робота на одну клетку:  «U» — сдвинуться на клетку вверх,  «R» — сдвинуться на клетку вправо,  «D» — сдвинуться на клетку вниз,  «L» — сдвинуться на клетку влево. Робот должен обойти цикл, побывав в каждой его клетке ровно один раз (кроме стартовой точки — в ней он начинает и заканчивает свой путь).Найдите искомую последовательность команд, допускается любое направление обхода цикла.

В первой строке входных данных записаны два целых числа n и m (3 ≤ n, m ≤ 100) — количество строк и столбцов прямоугольного клетчатого поля соответственно. В следующих n строках записаны по m символов, каждый из которых — «.», «*» или «S». Гарантируется, что отличные от «.» символы образуют цикл без самопересечений и самокасаний. Также гарантируется, что на поле ровно одна клетка содержит «S» и что она принадлежит циклу. Робот не может посещать клетки, помеченные символом «.».

В первую строку выходных данных выведите искомую последовательность команд для Робота. Направление обхода цикла Роботом может быть любым.

ПримечаниеВ первом тестовом примере для обхода по часовой стрелке последовательность посещенных роботом клеток выглядит следующим образом:  клетка (3, 2);  клетка (3, 1);  клетка (2, 1);  клетка (1, 1);  клетка (1, 2);  клетка (1, 3);  клетка (2, 3);  клетка (3, 3);  клетка (3, 2).

#!/usr/bin/env ruby

h, w = gets.split.map(&:to_i)
lines = [[]]
for i in 0..h-1
  lines[i] = gets.chomp.chars
end
x = lines.detect { |a| a.include? ('S') }.index('S')
lines = lines.transpose
y = lines.detect { |a| a.include? ('S') }.index('S')

while true do
  if x-1>=0 and lines[x-1][y] == '*' then printf "L"; x-=1; lines[x][y] = '.'
  elsif x+1<w and lines[x+1][y] == '*' then printf "R"; x+=1; lines[x][y] = '.'
  elsif y+1<h and lines[x][y+1] == '*' then printf "D"; y+=1; lines[x][y] = '.'
  elsif y-1>=0 and lines[x][y-1] == '*' then printf "U"; y-=1; lines[x][y] = '.'
  else break end
end

if x-1>=0 and lines[x-1][y] == 'S' then printf "L"; x-=1; lines[x][y] = '.'
elsif x+1<w and lines[x+1][y] == 'S' then printf "R"; x+=1; lines[x][y] = '.'
elsif y+1<h and lines[x][y+1] == 'S' then printf "D"; y+=1; lines[x][y] = '.'
elsif y-1>=0 and lines[x][y-1] == 'S' then printf "U"; y-=1; lines[x][y] = '.' end
puts

#!/usr/bin/env ruby

h, w = gets.split.map(&:to_i)
lines = [[]]
for i in 0..h-1
  lines[i] = gets.chomp.chars
end
x = lines.detect { |a| a.include? ('S') }.index('S')
lines = lines.transpose
y = lines.detect { |a| a.include? ('S') }.index('S')

while true do
  if x-1>=0 and lines[x-1][y] == '*' then puts "L"; x-=1; lines[x][y] = '.'
  elsif x+1<w and lines[x+1][y] == '*' then puts "R"; x+=1; lines[x][y] = '.'
  elsif y+1<h and lines[x][y+1] == '*' then puts "D"; y+=1; lines[x][y] = '.'
  elsif y-1>=0 and lines[x][y-1] == '*' then puts "U"; y-=1; lines[x][y] = '.'
  else break end
end

if x-1>=0 and lines[x-1][y] == 'S' then puts "L"; x-=1; lines[x][y] = '.'
elsif x+1<w and lines[x+1][y] == 'S' then puts "R"; x+=1; lines[x][y] = '.'
elsif y+1<h and lines[x][y+1] == 'S' then puts "D"; y+=1; lines[x][y] = '.'
elsif y-1>=0 and lines[x][y-1] == 'S' then puts "U"; y-=1; lines[x][y] = '.' end


Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him.

The single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds.

Print n integers pi (1 ≤ pi ≤ n) which are the frog's route plan.    All the pi's should be mutually different.  All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1).  If there are several solutions, output any.

n = gets.to_i
p = Array.new(n)
p[0] = 1
(1...n).each {|i| p[i] = (i % 2 == 1 ? p[i-1] + i : p[i-1] - i)}
pmin = p.min
p.map!{|x| x - pmin + 1}
puts p.join(' ')

#sharyo
n=gets.to_i
i,j=1,n
while n!=0
	n-=1
	if (n&1)==1
     print i.to_s+" "
     i+=1
	else
     print j.to_s+" "
     j-=1
	end
end

num = gets.chomp.to_i

list = ""

flag = false
cnt = 0
cnt1 = 0
cnt2 = 0

while cnt != num
  if flag
    list << "#{num - cnt1} "
    cnt1 = cnt1 + 1
  else
    list << "#{1 + cnt2} "
    cnt2 = cnt2 + 1
  end
  flag = !flag
  cnt = cnt + 1
end

puts list.chomp

n = gets.to_i
printf "1 "
cc = 1
(n - 1).downto(1) do |c|
	sgn = (n - c) % 2 == 1 ? 1 : -1;
	cc = cc + c * sgn
	print "#{cc} "
end

a=[*1..gets.to_i]
print a.pop," ",a.shift," "while[]!=a

#sharyo
n=gets.to_i
i,j=1, n
while n>0
	n-=1
	if n&1
     print i.to_s+" "
     i+=1
	else
     print j.to_s+" "
     j-=1
	end
end


Ilya plays a card game by the following rules.A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded.More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of cards Ilya has. Each of the next n lines contains two non-negative space-separated integers — ai and bi (0 ≤ ai, bi ≤ 104) — the numbers, written at the top and the bottom of the i-th card correspondingly.

Print the single number — the maximum number of points you can score in one round by the described rules.

NoteIn the first sample none of two cards brings extra moves, so you should play the one that will bring more points.In the second sample you should first play the third card that doesn't bring any points but lets you play both remaining cards.

n = gets.to_i
a = Array.new(n){gets.split.map(&:to_i).reverse}.sort.reverse
b, c = 1, 0
a.each do |x, y|
    break if b == 0
    b += x - 1
    c += y
end
p c

n=gets.to_i
s=[]
ans=0
cnt=1
n.times{
        a,b=gets.split.map(&:to_i)

        s.push(a) if b==0
        cnt+=b
        if b!=0 then
                cnt-=1
                ans+=a
        end
}
s.sort!
s.reverse!
[cnt,s.size()].min.times{|i|
        ans+=s[i]
}
p ans

n = gets.chomp.to_i

cards = []
n.times do
  cards << gets.chomp.split(" ").map{|e| e.to_i}
end

cards.sort!{|a, b|
  if a[1] == b[1]
    b[0] <=> a[0]
  else
    b[1] <=> a[1]
  end
}

card = cards.shift
score = card[0]
time = card[1]

cards.each do |card|
  if time <= 0
    break
  else
    score += card[0]
    time += card[1]
  end
  time -= 1
end

puts score

n = STDIN.gets.chomp.to_i
the_cards = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

use = ->(point, counter, card) { [point + card[0], counter - 1 + card[1]] }
sort_card = ->(cards) { cards.sort {|a,b| (_ = a[1] <=> b[1]).zero? ? (a[0] <=> b[0]) : _ } }

solve = ->(cards, point, counter) do
  while !counter.zero? && !cards.empty?
    cards = sort_card[cards]
    card = cards.pop
    point, counter = use[point, counter, card]
  end
  point
end

p solve[the_cards,0,1]

aa,bb,ans,ct=[],[],0,1
n=gets.to_i
n.times do
	x,y=gets.chomp.split.map(&:to_i)
	aa<<x;bb<<y
end

n.times do
	a,b=0,0
	n.times do |i|
		a=i if aa[i]>aa[a]
		b=i if bb[i]>bb[b]
	end
	if ct==1&&bb[b]==0
		ans+=aa[a]
		break
	elsif bb[b]==0
		ans+=aa[a]
		ct-=1
		aa[a]=0
	else
		ans+=aa[b]
		ct+=bb[b]-1
		aa[b],bb[b]=0,0
	end
end
puts ans

n, st, i, score = gets.to_i, 1, 0, 0
a = readlines.map(&:chomp).map(&:split).each {|x| x.map!(&:to_i)}.sort_by! { |x| [-x[1], -x[0]] }
# p a
while st < n - i and i <= n and a[0][1].nonzero?
  st += a[0][1] - 1
  score += a[0][0]
  i += 1
  a.shift
end
# p a.sort_by! {|x| [-x[0], -x[1]]}
while st.nonzero? and !a.empty?
  st += a[0][1] - 1
  score += a[0][0]
  a.shift
end
p score

#!/usr/bin/ruby
def read_int; gets.chomp.to_i; end
def read_ints; gets.chomp.split.map(&:to_i); end

num = read_int
vals = []

num.times do
  vals << read_ints
end
vals.sort! {|a,b|
  if b[1] == a[1]
    b[0] <=> a[0]
  else
    b[1] <=> a[1]
  end
}
vals.delete_if {|a| a[1] == 0 && a[0] == 0 }

rest = 1
point = 0
vals.each do |i|
  point += i[0]
  rest += i[1]
  rest -= 1
  break if rest == 0
end

puts point

a = gets.to_i.times.map{ gets.split.map(&:to_i) }

b = a.sort{|i,j| (j[1] <=> i[1]).nonzero? or j[0] <=> i[0]}

pt = 0
c = 0

b.each do |e|
  pt += e[0]
  c  += e[1]
  break if c.zero?
  c -= 1
end

p pt

n = gets.to_i
arr = []
n.times do
	arr << gets.split(" ").map(&:to_i)
end
arr.sort!{|a,b|
	if a[1] == b[1]
		b[0] <=> a[0]
	else
		b[1] <=> a[1]
	end
	# puts "#{a} b #{b}"
}

i = 0
counter = 1
points = 0
while true
	points += arr[i][0]
	counter += arr[i][1]
	i += 1
	counter -= 1
	break if counter == 0 || !arr[i]
end
puts points

n = gets.to_i
li = []
(0...n).each{li.push(gets.split.collect{|i| i.to_i})}
li = li.sort_by{|i| [i[1], i[0]]}
ans = 0
cnt = 1
li.reverse.each do |i|
    ans += i[0]
    cnt += i[1]-1
    break if cnt.zero?
end
puts ans

n = gets.to_i
c = []
for i in 0..n-1
	line = gets.split
	c << [line[0].to_i, line[1].to_i]
end

c.sort_by! {|e| [e[1], e[0]]}
c.reverse!

score = 0
count = 1
for i in 0..n-1
	if(count == 0)
		break
	else
		score += c[i][0]
		count += c[i][1]
		count -= 1
	end
end

puts score

def read_next_line
  gets.split.map { |x| x.to_i }
end

n = gets.to_i
p = []
counter = 1
res = 0
for _ in 0...n
  a, b = read_next_line
  if b > 0
    counter += b - 1
    res += a
  else
    p << a
  end
end
if p.empty?
  puts res
  exit
end
res += p.sort[-[counter, p.size].min..-1].inject(:+)
puts res

a = []

gets.to_i.times do
  a << gets.split.map(&:to_i)
end

counter = 1
score = 0
a = a.sort_by {|col| [col[1], col[0]]}
until counter.zero? or a.empty?
  x = a.pop
  counter -= 1
  counter += x[1]
  score += x[0]
end

puts score

n=gets.to_i
zeros=[]
score=0
opportunity=1
n.times{
	a,b=gets.split.map(&:to_i)
	if b>0
		score+=a
		opportunity+=b-1
	else
		zeros<<a
	end
}
zeros.sort!.reverse!

p score+(zeros.empty? ? 0 : zeros.take(opportunity).inject(:+))

n = gets.chomp.to_i

cards = []
n.times do
  cards << gets.chomp.split(" ").map{|e| e.to_i}
end

cards.sort!{|a, b|
  if a[1] == b[1]
    b[0] <=> a[0]
  else
    b[1] <=> a[1]
  end
}

card = cards.shift
score = card[0]
time = card[1]

cards.each do |card|
  if time <= 0
    break
  else
    score += card[0]
    time += card[1]
  end
end

puts score

class Item
  attr_accessor :times, :cards, :score

  def initialize(times, cards, score)
    @times = times
    @cards = cards
    @score = score
  end
end

n = gets.chomp.to_i

cards = []
n.times do
  cards << gets.chomp.split(" ").map{|e| e.to_i}
end

queue = []
cards.each_with_index do |card, idx|
  tmp = cards.dup
  tmp.delete_at(idx)
  item = Item.new(card[1], tmp, card[0])

  queue << item
end

scores = []
loop do
  if queue.length == 0
    break
  end

  new_items = []
  queue.each do |item|
    if item.times > 0
      cards = item.cards
      item.times -= 1

      cards.each_with_index do |card, idx|
        tmp = cards.dup
        tmp.delete_at(idx)
        new_item = Item.new(item.times + card[1], tmp, item.score + card[0])
        new_items << new_item
      end
    else
      scores << item.score
    end
  end
  queue = new_items
end

puts scores.max

n = STDIN.gets.chomp.to_i
the_cards = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

use = ->(point, counter, card) { [point + card[0], counter - 1 + card[1]] }

solve = ->(cards, point, counter) do
  until counter.zero?
    cards = cards.sort {|a,b| (_ = a[1] <=> a[1]).zero? ? (a[0] <=> a[0]) : _ }
    point, counter = use[point, counter, cards.pop]
  end
  point
end

p solve[the_cards,0,1]

n = STDIN.gets.chomp.to_i
the_cards = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

use = ->(point, counter, card) { [point + card[0], counter - 1 + card[1]] }

solve = ->(cards, point, counter) do
  cards = cards.sort {|a,b| (_ = a[1] <=> a[1]).zero? ? (a[0] <=> a[0]) : _ }
  point, counter = use[point, counter, cards.pop]
  return point if counter.zero?
  solve[cards, point, counter]
end

p solve[the_cards,0,1]

n=gets.to_i
zeros=[]
score=0
opportunity=1
n.times{
	a,b=gets.split.map(&:to_i)
	if b>1
		score+=a
		opportunity+=b-1
	else
		zeros<<a
	end
}
zeros.sort!.reverse!

p score+zeros.take(opportunity).inject(:+)


It is the hard version of the problem. The only difference is that in this version $$$3 \le k \le n$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, such that:  $$$a_1 + a_2 + \ldots + a_k = n$$$  $$$LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \ldots, a_k$$$.We can show that for given constraints the answer always exists.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^4)$$$  — the number of test cases. The only line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \le n \le 10^9$$$, $$$3 \le k \le n$$$). It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, for which all conditions are satisfied.

t = gets.chomp.to_i
t.times do
	input = gets.chomp.split
	n, k = input

	n = n.to_i
	k = k.to_i

	answer = []

	for i in 0...k-3 do
		answer.push(1)
	end

	n -= (k-3)

	if (n & 1) == 1 then
		answer.push([1, (n-1)/2, (n-1)/2])
	elsif n % 4 == 0 then
		answer.push([n/2,n/4,n/4])
	else
		answer.push([2,(n-2)/2, (n-2)/2])
	end

	puts answer.join(" ")

end


Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.Chouti remembered that $$$n$$$ persons took part in that party. To make the party funnier, each person wore one hat among $$$n$$$ kinds of weird hats numbered $$$1, 2, \ldots n$$$. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.After the party, the $$$i$$$-th person said that there were $$$a_i$$$ persons wearing a hat differing from his own.It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let $$$b_i$$$ be the number of hat type the $$$i$$$-th person was wearing, Chouti wants you to find any possible $$$b_1, b_2, \ldots, b_n$$$ that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the number of persons in the party. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le n-1$$$), the statements of people.

If there is no solution, print a single line "Impossible". Otherwise, print "Possible" and then $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$). If there are multiple answers, print any of them.

NoteIn the answer to the first example, all hats are the same, so every person will say that there were no persons wearing a hat different from kind $$$1$$$.In the answer to the second example, the first and the second person wore the hat with type $$$1$$$ and all other wore a hat of type $$$2$$$.So the first two persons will say there were three persons with hats differing from their own. Similarly, three last persons will say there were two persons wearing a hat different from their own.In the third example, it can be shown that no solution exists.In the first and the second example, other possible configurations are possible.

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

possible=true
res = Array.new(n, 0)
i = 1
a.each_with_index do |x,index|
    if res[index] == 0
        h = n-x
        (index..n-1).each do |y|
            break if h == 0
            if a[y] == x
                res[y] = i
                h-=1
            end
        end
        if h != 0
            possible=false
            break
        end
        i+=1
    end
end

possible = false if res.include?(0)

if possible
    puts "Possible"
    print res.join(" ")
else
    puts "Impossible"
end

# Solution
def main(n, a)
  b = Array.new(n)

  # Main part of solution
  a_pairs = a.map.with_index { |v, i| {index: i, value: v.to_i} } # Creating array of index-value pairs
  a_pairs.sort! { |a, b| b[:value] <=> a[:value] } # Sorting by value

  hat_index = 1 # Currently considered index of hat
  person_index = 0 # Currently considered person
  while person_index < n
    value = a_pairs[person_index][:value]
    s = n - value # Size of group of co-hatters
    s.times do |j|
      i = person_index + j
      return nil if i >= n || a_pairs[i][:value] != value # Unable to get group of hatters
      b[a_pairs[i][:index]] = hat_index
    end
    hat_index += 1
    person_index += s
  end

  return b
end

# Input
n = gets.to_i # 1 <= n <= 10**5
a = gets.split(" ") # 1 <= a[i] <= n-1

# Processing
b = main(n, a)

# Output
if b
  puts "Possible"
  b.each { |s| puts s }
else
  puts "Impossible"
end


Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:  Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.  Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≤ i ≤ n).  Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.

The first line contains integers n, m (1 ≤ n, m ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≤ ti ≤ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≤ vi ≤ n, 1 ≤ xi ≤ 109). If ti = 2, then it is followed by integer yi (1 ≤ yi ≤ 104). And if ti = 3, then it is followed by integer qi (1 ≤ qi ≤ n).

For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.

n,m = gets.split.map(&:to_i)
as = gets.split.map(&:to_i)
acc = 0
$<.each do |line|
    a,b,c = line.split.map(&:to_i)
    #p [a,b,c]
    case a
    when 1 ; as[b - 1] = c - acc
    when 2 ; acc += b
    when 3 ; puts (as[b - 1] + acc)
    end
end


You are given two integers $$$a$$$ and $$$b$$$.In one move, you can choose some integer $$$k$$$ from $$$1$$$ to $$$10$$$ and add it to $$$a$$$ or subtract it from $$$a$$$. In other words, you choose an integer $$$k \in [1; 10]$$$ and perform $$$a := a + k$$$ or $$$a := a - k$$$. You may use different values of $$$k$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case, print the answer: the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.

NoteIn the first test case of the example, you don't need to do anything.In the second test case of the example, the following sequence of moves can be applied: $$$13 \rightarrow 23 \rightarrow 32 \rightarrow 42$$$ (add $$$10$$$, add $$$9$$$, add $$$10$$$).In the third test case of the example, the following sequence of moves can be applied: $$$18 \rightarrow 10 \rightarrow 4$$$ (subtract $$$8$$$, subtract $$$6$$$).

t = gets.to_i
t.times do
	a, b = gets.split.map &:to_i
	p ((b - a).abs + 9) / 10
end

t = gets.to_i

def play(a,b)
  return 0 if a == b

  if a > b
    c = a
    a = b
    b = c
  end

  x = b - a
  r = x % 10

  if r == 0
    return x / 10
  else
    return (x-r)/10 + 1
  end
end

while t > 0
  a,b = gets.split(/\s+/).map(&:to_i)
  puts play(a,b)
  t -= 1
end

t = gets.chomp.to_i
t.times do
    a, b = gets.chomp.split(" ").map(&:to_i)
    sa = (a - b).abs
    ans = sa / 10
    amari = sa % 10
    if amari == 0
        puts ans
    else
        puts ans + 1
    end
end

gets.to_i.times do
    a, b = gets.split.map &:to_i
    d = (a - b).abs
    puts d / 10 + (d % 10 > 0 ? 1 : 0)
end

def solve
  n, m = gets.strip.split(' ').map(&:to_i)
  n, m = m, n if n < m
  dif = n - m;
  puts (dif / 10.0).to_i + (dif % 10 != 0 ? 1 : 0)
end

gets.strip.to_i.times { solve }

gets.to_i.times {
  a,b = gets.split.map &:to_i
  x = (a-b).abs
  p (x+9)/10
}

n=gets.to_i
n.times do
  a,b = gets.split.map(&:to_i)
  puts ((b-a).abs/10.0).ceil
end

gets.to_i.times do
  a, b = gets.split.map &:to_i
  d = (a - b).abs
  puts d/10 + (d%10 == 0 ? 0 : 1)
end

t = gets.chomp.to_i
inputs = []
t.times do
  inputs << gets.chomp.split.map(&:to_i)
end

inputs.each do |a,b|
  ret = 0
  if b > a
    ret += (b-a)/10
    ret += 1 if b > a + ret*10
  elsif b < a
    ret += (a-b)/10
    ret += 1 if b < a - ret*10
  end
  puts ret
end

gets.to_i.times do
  a, b = gets.split(' ').map(&:to_i)

  d, m = (a-b).abs.divmod(10)

  puts d + (m.zero? ? 0 : 1)
end

tc = gets().to_i
tc.times do
    input = gets().split(' ').map(&:to_i)
    a = input[0]
    b = input[1]
    ans = (((a-b).abs().to_f)/10).ceil()
    puts ans
end

t = gets.chomp.to_i
inputs = []
t.times do
  inputs << gets.chomp.split.map(&:to_i)
end

inputs.each do |a,b|
  ret = 0
  if b > a
    ret += (b-a)/10
    ret += b - (a + ret * 10)
  elsif b < a
    ret += (a-b)/10
    ret += a - (b + ret * 10)
  end
  puts ret
end

t = gets.chomp.to_i
inputs = []
t.times do
  inputs << gets.chomp.split.map(&:to_i)
end

inputs.each do |a,b|
  ret = 0
  if b > a
    ret += (b-a)/10
    ret += 1
  elsif b < a
    ret += (a-b)/10
    ret += 1
  end
  puts ret
end