You are given a square grid with $$$n$$$ rows and $$$n$$$ columns. Each cell contains either $$$0$$$ or $$$1$$$. In an operation, you can select a cell of the grid and flip it (from $$$0 \to 1$$$ or $$$1 \to 0$$$). Find the minimum number of operations you need to obtain a square that remains the same when rotated $$$0^{\circ}$$$, $$$90^{\circ}$$$, $$$180^{\circ}$$$ and $$$270^{\circ}$$$.The picture below shows an example of all rotations of a grid.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the size of the grid. Then $$$n$$$ lines follow, each with $$$n$$$ characters $$$a_{i,j}$$$ ($$$0 \leq a_{i,j} \leq 1$$$) — the number written in each cell.

For each test case output a single integer  — the minimum number of operations needed to make the square look the same rotated $$$0^{\circ}$$$, $$$90^{\circ}$$$, $$$180^{\circ}$$$ and $$$270^{\circ}$$$.

NoteIn the first test case, we can perform one operations to make the grid $$$\begin{matrix}0 & 1 & 0\\ 1 & 1 & \color{red}{1}\\ 0 & 1 & 0\end{matrix}$$$. Now, all rotations of the square are the same.In the second test case, all rotations of the square are already the same, so we don't need any flips.

def solve(grid, i, j, n, m)
  return 0 if n == 1
  ans = 0
  (n-1).times do
    ones = 0
    zeros = 0
    4.times do
      if grid[i][j] == '1'
        ones += 1
      else
        zeros += 1
      end
      i, j = j, m-1-i
    end
    ans += [ones, zeros].min
    j += 1
  end
  ans
end

t = gets.to_i

t.times do
  n = gets.to_i
  a = Array.new(n) { gets.chomp }
  ans = 0
  ((n+1)/2).times do |i|
    ans += solve(a, i, i, n-2*i, n)
  end
  puts ans
end


Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.

The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.

If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.

abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0

def min(a,b)
    if a>b then
        return b
    else
        return a
    end
end
a=gets
b=gets
if a.length!=b.length then
    puts -1
    exit
end

a=a.bytes.to_a
b=b.bytes.to_a

INF=999999999
d=Array.new(128){Array.new(128,INF)}
r1=Array.new(128){Array.new(128,INF)}
r2=Array.new(128){Array.new(128,INF)}

0.upto(127){|i|
    d[i][i]=0
}
n=gets.to_i
0.upto(n-1){|i|
    input=gets.split
    for j in 0..1
        input[j]=input[j].bytes.to_a
    end

    if d[input[0][0]][input[1][0]]>input[2].to_i then
        d[input[0][0]][input[1][0]]=input[2].to_i
    end
}
97.upto(122){|k|
    97.upto(122){|i|
        97.upto(122){|j|
            if d[i][j]>d[i][k]+d[k][j] then
                d[i][j]=d[i][k]+d[k][j]
            end
        }
    }
}
for j in 97..122
    for i in 97..122
        tres=INF
        for k in 97..122
            tres=min(tres,d[i][k]+d[j][k])
        end
        r1[i][j]=tres
        for k in 97..122
            if tres==d[i][k]+d[j][k] then
                r2[i][j]=k.chr
                break
            end
        end

    end
end
res=0
str=""
q=a.length-2
0.upto(q){|i|
    res=res+r1[a[i]][b[i]]
}
if res>INF then
    puts -1
    exit
end
puts res
0.upto(q){|i|
    print r2[a[i]][b[i]]
}
puts

def min(a,b)
    if a>b then
        return b
    else
        return a
    end
end
a=gets
b=gets
if a.length!=b.length then
    puts -1
    exit
end

a=a.bytes.to_a
b=b.bytes.to_a

INF=999999999
d=Array.new(128){Array.new(128,INF)}
r1=Array.new(128){Array.new(128,INF)}
r2=Array.new(128){Array.new(128,INF)}

0.upto(127){|i|
    d[i][i]=0
}
n=gets.to_i
0.upto(n-1){|i|
    input=gets.split
    for j in 0..1
        input[j]=input[j].bytes.to_a
    end

    if d[input[0][0]][input[1][0]]>input[2].to_i then
        d[input[0][0]][input[1][0]]=input[2].to_i
    end
}
97.upto(122){|k|
    97.upto(122){|i|
        97.upto(122){|j|
            if d[i][j]>d[i][k]+d[k][j] then
                d[i][j]=d[i][k]+d[k][j]
            end
        }
    }
}
for j in 97..122
    for i in 97..122
        tres=INF
        for k in 97..122
            tres=min(tres,d[i][k]+d[j][k])
        end
        r1[i][j]=tres
        for k in 97..122
            if tres==d[i][k]+d[j][k] then
                r2[i][j]=k.chr
                break
            end
        end

    end
end
res=0
str=""
q=a.length-2
0.upto(q){|i|
    res+=r1[a[i]][b[i]]
    str+=r2[a[i]][b[i]]
}
puts res
puts str


Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.

A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.

On a single line print the answer to the problem. If such number does not exist, then you should print -1.

NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.

n = gets.to_i
arr = gets.split(" ").map(&:to_i).sort.reverse
ans = nil
if arr.include?(0)
	sum = arr.inject(0,:+)
	if sum % 3 == 0
		ans = arr.join("")
	elsif sum % 3 == 1

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		one.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			two.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 1 && one.length < 1
		# 		one << j
		# 		break
		# 	end

		# 	if a % 3 == 2  && two.length < 2
		# 		two << j
		# 	end
		# 	j -= 1
		# end
		# if one.empty?
		# 	arr.delete_at(two[0])
		# 	arr.delete_at(two[1])
		# else
		# 	arr.delete_at(one[0])
		# end

		# puts "here"
		# l = arr.rindex{|a| a % 3 == 1}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# end
	else

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		two.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			one.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# one = [1,4,7]
		# two = [2,5,8]
		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 2 && two.length < 1
		# 		two << j
		# 		break
		# 	end

		# 	if a % 3 == 1  && one.length < 2
		# 		one << j
		# 	end
		# 	j -= 1
		# end
		# if two.empty?
		# 	arr.delete_at(one[0])
		# 	arr.delete_at(one[1])
		# else
		# 	arr.delete_at(two[0])
		# end

		# l = arr.rindex{|a| a % 3 == 2}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# end
	end
	ans = arr.join("")
	unless /[^0]/ =~ ans
		puts "0"
	else
		puts ans
	end
else
	puts "-1"
end

n = gets.to_i
digits = gets.split.map(&:to_i).sort_by {|el| -el}

unless digits.last==0
  puts -1
  exit
end

sum = digits.inject{|sum,el| sum+=el}
ans = 0
size = digits.size

if sum%3 == 0
  ans =  digits.join unless digits[0] == 0
elsif sum%3 == 1
  (size-1).downto(0) do |i|
    if digits[i]%3==1
      digits.delete_at i
      break
    end
  end
  if digits.size == size
    (size-1).downto(0) do |i|
      if digits[i]%3==2 && ( size - digits.size < 2 )
        digits.delete_at i
      end
    end
  end
  ans =  digits.join unless digits[0] == 0
elsif sum%3 == 2
  (size-1).downto(0) do |i|
    if digits[i]%3==2
      digits.delete_at i
      break
    end
  end
  if digits.size == size
    (size-1).downto(0) do |i|
      if digits[i]%3==1 && ( size - digits.size < 2 )
        digits.delete_at i
      end
    end
  end
  ans =  digits.join unless digits[0] == 0
end

puts (ans[0] == '0' ? 0 : ans)

n = gets.to_i
arr = gets.split(" ").map(&:to_i).sort.reverse
ans = nil
if arr.include?(0)
	sum = arr.inject(0,:+)
	if sum % 3 == 0
		ans = arr.join("")
	elsif sum % 3 == 1

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		one.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			two.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 1 && one.length < 1
		# 		one << j
		# 		break
		# 	end

		# 	if a % 3 == 2  && two.length < 2
		# 		two << j
		# 	end
		# 	j -= 1
		# end
		# if one.empty?
		# 	arr.delete_at(two[0])
		# 	arr.delete_at(two[1])
		# else
		# 	arr.delete_at(one[0])
		# end

		# puts "here"
		# l = arr.rindex{|a| a % 3 == 1}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# end
	else

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		two.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			one.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# one = [1,4,7]
		# two = [2,5,8]
		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 2 && two.length < 1
		# 		two << j
		# 		break
		# 	end

		# 	if a % 3 == 1  && one.length < 2
		# 		one << j
		# 	end
		# 	j -= 1
		# end
		# if two.empty?
		# 	arr.delete_at(one[0])
		# 	arr.delete_at(one[1])
		# else
		# 	arr.delete_at(two[0])
		# end

		# l = arr.rindex{|a| a % 3 == 2}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# end
	end
	ans = arr.join("")
	# if ans.to_i == 0
	# 	puts "0"
	# else
		puts ans
	# end
else
	puts "-1"
end


Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct positions in the array. Also note that Petya must swap some two integers even if the original array meets all requirements.Array a (the array elements are indexed from 1) consisting of n elements is called sorted if it meets at least one of the following two conditions:  a1 ≤ a2 ≤ ... ≤ an;  a1 ≥ a2 ≥ ... ≥ an. Help Petya find the two required positions to swap or else say that they do not exist.

The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n non-negative space-separated integers a1, a2, ..., an — the elements of the array that Petya's mother presented him. All integers in the input do not exceed 109.

If there is a pair of positions that make the array unsorted if swapped, then print the numbers of these positions separated by a space. If there are several pairs of positions, print any of them. If such pair does not exist, print -1. The positions in the array are numbered with integers from 1 to n.

NoteIn the first two samples the required pairs obviously don't exist.In the third sample you can swap the first two elements. After that the array will look like this: 2 1 3 4. This array is unsorted.

n = gets.to_i
a = gets.split(' ').map(&:to_i)
if n < 3
  puts "-1"
  exit
end

incr = a.sort
decr = a.sort{|x,y| y <=> x}

i = 0
finish = false

1.upto(a.size-1) do |i|
  if a[i] != a[i-1]
    a[i],a[i-1] = a[i-1],a[i]

    finish = (a != incr) && (a != decr)
    if finish
      puts "#{i} #{i+1}"
      break
    end
    a[i],a[i-1] = a[i-1],a[i]
  end
end

if !finish
  puts "-1"
end

n = gets.to_i
a = gets.split(' ').map(&:to_i)
if n < 3
  puts "-1"
  exit
end

incr = a.sort
decr = a.sort{|x,y| y <=> x}

i = 0
finish = false

1.upto(a.size-1) do |i|
  if a[i] != a[i-1]
    a[i],a[i-1] = a[i-1],a[i]

    finish = (a != incr) && (a != decr)
    if finish
      puts "#{i} #{i+1}"
      break
    end
    a[i],a[i-1] = a[i-1],a[i]
  end
end

if !finish
  puts "-1 "
end

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

if n == 2
	puts "-1"
	exit 0
end

mn = x.min
k = x.index(mn)
lmx = x[0..k-1].max
rmx = x[k+1..-1].max
if 0 < k && k + 1 < n && lmx > mn && rmx > mn
	if lmx != rmx
		puts "#{x[0..k-1].index(lmx)+1} #{x[k+1..-1].index(rmx)+k+2}"
	else
		1.upto(k-1) do |i|
			if x[i] != mn
				puts "#{i+1} #{k+1}"
				exit 0
			end
		end
		(k+1).upto(n-2) do |i|
			if x[i] != mn
				puts "#{k+1} #{i+1}"
				exit 0
			end
		end
		if n == 3
			puts -1
			exit 0
		end
		puts "1 2"
	end
	exit 0
end

mx = x.max
k = x.index(mx)
lmn = x[0..k-1].min
rmn = x[k+1..-1].min
if 0 < k && k + 1 < n && lmn < mx && rmn < mx
	if lmn != rmn
		puts "#{x[0..k-1].index(lmn)+1} #{x[k+1..-1].index(rmn)+k+2}"
	else
		1.upto(k-1) do |i|
			if x[i] != mx
				puts "#{i+1} #{k+1}"
				exit 0
			end
		end
		(k+1).upto(n-2) do |i|
			if x[i] != mx
				puts "#{k+1} #{i+1}"
				exit 0
			end
		end
		if n == 3
			puts -1
			exit 0
		end
		puts "1 2"
	end
	exit 0
end

if mn == mx
	puts -1
	exit 0
end

x[1..-2].each_with_index do |v, i|
	if v != x[0]
		puts "1 #{i+2}"
		exit 0
	end
	if v != x[-1]
		puts "#{i+2} #{n}"
		exit 0
	end
end

puts -1

t = gets.to_i

a = gets.split.collect{|x| x.to_i}

up = a.sort
dn = a.sort{|x,y| y <=> x}

i = 0
finish = false

1.upto(a.size-1) do |i|
	if a[i-1] != a[i]
		a[i], a[i-1] = a[i-1], a[i]

		finish = a != up && a != dn

		if finish
			print i,' ', i+1
			break
		end

		a[i], a[i-1] = a[i-1], a[i]
	end
end

if not finish or a == Array.new(a.size, a[0])
	print -1
end

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

if n == 2
	puts "-1"
	exit 0
end

mn = x.min
k = x.index(mn)
lmx = x[0..k-1].max
rmx = x[k+1..-1].max
if 0 < k && k + 1 < n && lmx > mn && rmx > mn
	puts "#{x[0..k-1].index(lmx)+1} #{x[k+1..-1].index(rmx)+1}"
	exit 0
end

mx = x.max
k = x.index(mx)
lmn = x[0..k-1].min
rmn = x[k+1..-1].min
if 0 < k && k + 1 < n && lmn < mx && rmn < mx
	puts "#{x[0..k-1].index(lmn)+1} #{x[k+1..-1].index(rmn)+1}"
	exit 0
end

if mn == mx
	puts -1
	exit 0
end

x[1..-2].each_with_index do |v, i|
	if v != x[0]
		puts "1 #{i+2}"
		exit 0
	end
	if v != x[-1]
		puts "#{i+2} #{n}"
		exit 0
	end
end

puts -1

def gao(x, y)
	return [-1] if x.size == 2
	a, b = [], []
	x.each_index { |i| x[i] == y[i] ? a << x[i] : b << x[i] }
	a.uniq!
	ub = b.uniq
	if a.size >= 2
		[x.index(a[0]) + 1, x.index(a[1]) + 1]
	else
		if ub.size >= 2 && b.size >= 3
			[x.index(ub[0]) + 1, x.index(ub[1]) + 1]
		else
			[-1]
		end
	end
end

n = gets.to_i
x = gets.split.map(&:to_i)
r = gao(x, x.sort)
puts r.size == 1 ? gao(x, x.sort.reverse) : r.join(" ")

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

if n == 2
	puts "-1"
	exit 0
end

mn = x.min
k = x.index(mn)
lmx = x[0..k-1].max
rmx = x[k+1..-1].max
if 0 < k && k + 1 < n && lmx > mn && rmx > mn
	if lmx != rmx
		puts "#{x[0..k-1].index(lmx)+1} #{x[k+1..-1].index(rmx)+k+2}"
	else
		1.upto(k-1) do |i|
			if x[i] != mn
				puts "#{i+1} #{k+1}"
				exit 0
			end
		end
		(k+1).upto(n-1) do |i|
			if x[i] != mn
				puts "#{k+1} #{i+1}"
				exit 0
			end
		end
		if n == 3
			puts -1
			exit 0
		end
		puts "1 2"
	end
	exit 0
end

mx = x.max
k = x.index(mx)
lmn = x[0..k-1].min
rmn = x[k+1..-1].min
if 0 < k && k + 1 < n && lmn < mx && rmn < mx
	if lmx != rmx
		puts "#{x[0..k-1].index(lmn)+1} #{x[k+1..-1].index(rmn)+k+2}"
	else
		1.upto(k-1) do |i|
			if x[i] != mx
				puts "#{i+1} #{k+1}"
				exit 0
			end
		end
		(k+1).upto(n-1) do |i|
			if x[i] != mx
				puts "#{k+1} #{i+1}"
				exit 0
			end
		end
		if n == 3
			puts -1
			exit 0
		end
		puts "1 2"
	end
	exit 0
end

if mn == mx
	puts -1
	exit 0
end

x[1..-2].each_with_index do |v, i|
	if v != x[0]
		puts "1 #{i+2}"
		exit 0
	end
	if v != x[-1]
		puts "#{i+2} #{n}"
		exit 0
	end
end

puts -1


Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 people. Of course, each of n candidates can settle in only one of the cities. Thus, first some subset of candidates of size n1 settle in the first city and then some subset of size n2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home.To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth ai among all its residents divided by the number of them (n1 or n2 depending on the city). The division should be done in real numbers without any rounding.Please, help authorities find the optimal way to pick residents for two cities.

The first line of the input contains three integers n, n1 and n2 (1 ≤ n, n1, n2 ≤ 100 000, n1 + n2 ≤ n) — the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), the i-th of them is equal to the wealth of the i-th candidate.

Print one real value — the maximum possible sum of arithmetic means of wealth of cities' residents. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second.In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (a3 + a4) / 2 + a2 = (3 + 2) / 2 + 4 = 6.5

# first steps

n, n1, n2 = gets.split(' ')
a = gets.split(' ')

n = n.to_i
i = 0
while i < n
	a[i] = a[i].to_i
	i += 1
end

n1 = n1.to_i
n2 = n2.to_i

a = a.sort {|x, y| x.to_i <=> y.to_i}
a = a.reverse

if n1 > n2
	temp = n2
	n2 = n1
	n1 = temp
end

cnt1, cnt2 = [0, 0]

i = 0
n1.times do
	cnt1 += a[i].to_i
	i += 1
end
i = n1
n2.times do
	cnt2 += a[i].to_i
	i += 1
end
#puts a.join(', ')
#puts cnt1.to_s + ' ' + cnt2.to_s
puts cnt1.to_f / n1.to_f + cnt2.to_f / n2.to_f

n, n1, n2 = gets.split.map(&:to_i)
data = gets.split.map(&:to_i)

data.sort! { |x, y| y <=> x }
n1, n2 = [n1,n2].minmax

ans = data[0,n1].reduce(0,:+).to_f / n1.to_f + data[n1,n2].reduce(0,:+).to_f / n2.to_f
p ans


Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it:Consider an $$$n$$$ by $$$n$$$ chessboard. Its rows are numbered from $$$1$$$ to $$$n$$$ from the top to the bottom. Its columns are numbered from $$$1$$$ to $$$n$$$ from the left to the right. A cell on an intersection of $$$x$$$-th row and $$$y$$$-th column is denoted $$$(x, y)$$$. The main diagonal of the chessboard is cells $$$(x, x)$$$ for all $$$1 \le x \le n$$$.A permutation of $$$\{1, 2, 3, \dots, n\}$$$ is written on the main diagonal of the chessboard. There is exactly one number written on each of the cells. The problem is to partition the cells under and on the main diagonal (there are exactly $$$1+2+ \ldots +n$$$ such cells) into $$$n$$$ connected regions satisfying the following constraints:  Every region should be connected. That means that we can move from any cell of a region to any other cell of the same region visiting only cells of the same region and moving from a cell to an adjacent cell.  The $$$x$$$-th region should contain cell on the main diagonal with number $$$x$$$ for all $$$1\le x\le n$$$.  The number of cells that belong to the $$$x$$$-th region should be equal to $$$x$$$ for all $$$1\le x\le n$$$.  Each cell under and on the main diagonal should belong to exactly one region.

The first line contains a single integer $$$n$$$ ($$$1\le n \le 500$$$) denoting the size of the chessboard. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$. $$$p_i$$$ is the number written on cell $$$(i, i)$$$. It is guaranteed that each integer from $$$\{1, \ldots, n\}$$$ appears exactly once in $$$p_1$$$, ..., $$$p_n$$$.

If no solution exists, output $$$-1$$$. Otherwise, output $$$n$$$ lines. The $$$i$$$-th line should contain $$$i$$$ numbers. The $$$j$$$-th number on the $$$i$$$-th line should be $$$x$$$ if cell $$$(i, j)$$$ belongs to the the region with $$$x$$$ cells.

NoteThe solutions to the examples are illustrated in the following pictures:

def pa(a)
  0.upto(a.size - 1) do |i|
    puts a[i][0 .. i].join(" ")
  end
end

def fill(a, i, j, val, count)
  a[i][j] = val
  done = 1
  if done < count && j > 0 && a[i][j - 1] == 0
     done += fill(a, i, j - 1, val, count - 1)
  end
  if done < count && i < a.size - 1 && a[i + 1][j] == 0
     done += fill(a, i + 1, j, val, count - 1)
  end
  return done
end

n = gets.to_s.to_i
a = n.times.map {[0] * n}
d = gets.to_s.split.map {|x| x.to_i }
d.each.with_index {|x, i| fill(a, i, i, x, x) }

freq = {}
a.each {|row| row.each {|val| freq[val] = (freq[val] || 0) + 1 }}

bad = false
freq.each {|k, v| bad = true if k != 0 && k != v }

if bad
  printf("-1\n")
else
  pa(a)
end


Recently, Norge found a string $$$s = s_1 s_2 \ldots s_n$$$ consisting of $$$n$$$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $$$s$$$. Yes, all $$$\frac{n (n + 1)}{2}$$$ of them!A substring of $$$s$$$ is a non-empty string $$$x = s[a \ldots b] = s_{a} s_{a + 1} \ldots s_{b}$$$ ($$$1 \leq a \leq b \leq n$$$). For example, "auto" and "ton" are substrings of "automaton".Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only $$$k$$$ Latin letters $$$c_1, c_2, \ldots, c_k$$$ out of $$$26$$$.After that, Norge became interested in how many substrings of the string $$$s$$$ he could still type using his broken keyboard. Help him to find this number.

The first line contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq k \leq 26$$$) — the length of the string $$$s$$$ and the number of Latin letters still available on the keyboard. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains $$$k$$$ space-separated distinct lowercase Latin letters $$$c_1, c_2, \ldots, c_k$$$ — the letters still available on the keyboard.

Print a single number — the number of substrings of $$$s$$$ that can be typed using only available letters $$$c_1, c_2, \ldots, c_k$$$.

gets
s = gets.chomp
c = gets.split
p s.chars.chunk { c.include? _1 }.select { _1[0] }.sum {
		_2.size * (_2.size + 1) / 2
  }

MOD=10**9+7
cnt=0; sum=0; prev=nil; can=true; h=Hash.new(0)
def gs() gets.chomp end
def gi() gets.to_i end
def gsmi() gets.chomp.split.map(&:to_i) end

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end

def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n,k=gsmi
s=gs
c=gets.chomp.split

i=0
cnt=0
while i<n do
  if c.include?(s[i])
    cnt+=1
  else
    h[cnt]+=1
    cnt=0
  end
  i+=1
end
h[cnt]+=1

# substringなん文字が何個あるか
h.each do |key,val|
  cnt = key*(key+1)/2*val
  sum+=cnt
end
puts sum


Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya.

The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1 ≤ n ≤ 90) — the number of fouls.  Each of the following n lines contains information about a foul in the following form:    first goes number t (1 ≤ t ≤ 90) — the minute when the foul occurs;  then goes letter "h" or letter "a" — if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player;  then goes the player's number m (1 ≤ m ≤ 99);  then goes letter "y" or letter "r" — if the letter is "y", that means that the yellow card was given, otherwise the red card was given.  The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute.

For each event when a player received his first red card in a chronological order print a string containing the following information:   The name of the team to which the player belongs;  the player's number in his team;  the minute when he received the card.  If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards).

h = gets.chomp
a = gets.chomp
n = gets.to_i
hash = {}
processed = {}
result = []
n.times do
  m,team,player,card = gets.chomp.split
  if card == 'r'
    if !processed[[team,player]]
      result << [team,player,m.to_i]
      processed[[team,player]] = true
    end
  else
    if hash[[team,player]]
      if !processed[[team,player]]
        result << [team,player,m.to_i]
        processed[[team,player]] = true
      end
    else
      hash[[team,player]] = true
    end
  end
end
result = result.sort_by {|x| x[2]}
result.each do |team,player,minute|
  puts "#{team == 'h' ? h : a} #{player} #{minute}"
end

team_a = STDIN.readline.strip
team_b = STDIN.readline.strip
n = STDIN.readline.to_i
yellow, red = {}, {}
n.times do
  tokens = STDIN.readline.split
  time, player, color = tokens[0].to_i, tokens[2].to_i, tokens[3]
  team = tokens[1] == 'h' ? team_a : team_b
  key = [player, team]
  first_red = false
  if color == 'y'
    if yellow.include?(key) and not red.include?(key)
      red[key] = first_red = true
    end
    yellow[key] = true
  else
    if not red.include?(key)
      red[key] = first_red = true
    end
  end
  if first_red
    puts '%s %d %d' % [team, player, time]
  end
end

require 'pp'

teama = STDIN.gets.chomp
teamb = STDIN.gets.chomp

h ={teama => {}, teamb => {}}

n = STDIN.gets.chomp.to_i

n.times do
  t, ha, num, yr = STDIN.gets.chomp.split(/ /)
  team = ha == 'h' ? teama : teamb

  if h[team].has_key?(num) && h[team][num] == 2
    # nothing
  elsif h[team].has_key?(num) && h[team][num] == 1
    print "#{team} #{num} #{t}\n"
      h[team][num] = 2
  elsif !h[team].has_key?(num)
    if yr == 'r'
      print "#{team} #{num} #{t}\n"
      h[team][num] = 2
    else
      h[team][num] = 1
    end
  end
end

#! /usr/bin/env ruby
# coding: utf-8

class Player
  attr_reader :time, :team, :b_num, :card

  def initialize(l)
    @time  = l[0].to_i
    @team  = l[1]
    @b_num = l[2].to_i
    @card  = l[3]
  end

  def update(p)
    if @card != 'r'
      @time = p.time
      @card = 'r'
    end
  end

end

class Players
  def initialize
    @faul_receivers = []
  end

  def <<(p)
    if @faul_receivers.length < 1
      @faul_receivers << p
    else
      update = false
      @faul_receivers.each do |r|
        update= true if r.team == p.team and r.b_num == p.b_num
        if update
          r.update(p)
          break
        end
      end
      @faul_receivers << p unless update
    end
  end

  def red_card_list
    reds = []
    @faul_receivers.each do |p|
      reds << p if p.card == 'r'
    end

    reds.sort_by! { |p| p.time }
    return reds
  end

  def each(&block)
    @faul_receivers.each &block
  end
end

h, a, n = gets.chomp, gets.chomp, gets.chomp.to_i

p_l = Players.new
n.times do
  l = gets.chomp.split(' ')
  p = Player.new(l)
  p_l << p
end

p_l.red_card_list.each do |p|
  t = p.team == "a" ? a : h
  puts "#{t} #{p.b_num} #{p.time}"
end

name=[gets.chomp,gets.chomp]
foul=[{},{}]
done=[{},{}]
gets.to_i.times{
  time,team,n,type=gets.split
  team_n=team==?h?0:1
  if foul[team_n][n] || type==?r
    unless done[team_n][n]
      puts [name[team_n],n,time]*" "
      done[team_n][n]=true
    end
  else
    foul[team_n][n]=true
  end
}

home_team = gets.chomp
away_team = gets.chomp
N = gets.to_i
used = {}
red = {}
while $_ = gets do
    t_, team, m_, type = $_.split
    t = t_.to_i
    m = m_.to_i
    if red["#{team}:#{m}"]
        next
    end
    if type == "r" || used["#{team}:#{m}"] then
        if team == "h"
            print home_team
        else
            print away_team
        end
        print " #{m} #{t}\n"
        red["#{team}:#{m}"] = true
    end
    used["#{team}:#{m}"] = true
end

#!/usr/bin/ruby
home = STDIN.gets.chomp
away = STDIN.gets.chomp
n = STDIN.gets.chomp.to_i
marked = {'a' => [], 'h' => []}
teams = {'a' => away, 'h' => home}
n.times do
    tokens = STDIN.gets.chomp.split(' ')
    minute = tokens[0].to_i
    team = tokens[1]
    player = tokens[2].to_i
    card = tokens[3]
    marked[team][player] = 0 if not marked[team][player]
    next if marked[team][player] > 1
    if card == 'r' or marked[team][player] == 1
        marked[team][player] = 2
        puts "#{teams[team]} #{player} #{minute}"
    else
        marked[team][player] += 1
    end
end

a=Array.new(105,0)
b=Array.new(105,0)
sz=Array.new
sta=gets.to_s
stb=gets.to_s
n=gets.to_i
for i in 1..n
  stc=gets.to_s
  sz=stc.split
  if sz[3]=='y'
    tr=1
  elsif sz[3]=="r"
    tr=2
  end
  if sz[1]=="h"
    t=sz[2].to_i
    if a[t]>=2
      next
    end
    a[t]+=tr
    if a[t]>=2
      print sta.chomp
      print " "
      print t
      print " "
      puts sz[0]
    end
  elsif sz[1]=="a"
    t=sz[2].to_i
    if b[t]>=2
      next
    end
    b[t]+=tr
    if b[t]>=2
      print stb.chomp
      print " "
      print t
      print " "
      puts sz[0]
    end
  end
end

# 493A

class Foul
  include Comparable
  attr :time

  def initialize(player, time, team)
    @player = player
    @time = time.to_i
    @team = team
  end

  def <=>(another)
    time <=> another.time
  end

  def to_s
    [@team, @player, @time].join(' ')
  end
end

names = {h: gets.chomp, a: gets.chomp}
cards = {h: {y: {}, r: {}}, a: {y: {}, r: {}}}
gets.to_i.times do
  time, _team, player, card_colour = gets.chomp.split
  team = _team.to_sym
  unless cards[team][:r].include?(player)
    if card_colour == 'r'
      cards[team][:r][player] = time
    else
      if cards[team][:y].include?(player)
        cards[team][:r][player] = time
      else
        cards[team][:y][player] = time
      end
    end
  end
end

fouls = []
[:h, :a].each { |c| cards[c][:r].each { |k, v| fouls << Foul.new(k, v, names[c]) } }
fouls.sort.each { |foul| puts foul }

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]!= 'r') && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end

    if a[arry[i][1]] ==nil
      a.merge!( arry[i][1] => {} )
    end

    if a[arry[i][1]][arry[i][2]] == 'y'
      a[arry[i][1]][arry[i][2]] = 'r'
    end

    if a[arry[i][1]][arry[i][2]] == nil
      a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
    end

  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  if a[arry[i][1]][arry[i][2]] == nil
    a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
  end
end

h = gets.chomp
a = gets.chomp
n = gets.to_i
hash = {}
result = []
n.times do
  m,team,player,card = gets.chomp.split
  if card == 'r'
    result << [team,player,m.to_i]
  else
    if hash[[team,player]]
      result << [team,player,m.to_i]
    else
      hash[[team,player]] = true
    end
  end
end
result = result.sort_by {|x| x[2]}
result.each do |team,player,minute|
  puts "#{team == 'h' ? h : a} #{player} #{minute}"
end

h = gets.chomp
a = gets.chomp
n = gets.to_i
hash = {}
result = []
n.times do
  m,team,player,card = gets.chomp.split
  if card == 'r'
    result << [team,player,m.to_i]
    hash.delete([team,player]) if hash[[team,player]]
  else
    if hash[[team,player]]
      result << [team,player,m.to_i]
      hash.delete([team,player])
    else
      hash[[team,player]] = true
    end
  end
end
result = result.sort_by {|x| x[2]}
result.each do |team,player,minute|
  puts "#{team == 'h' ? h : a} #{player} #{minute}"
end

h = gets.chomp
a = gets.chomp
n = gets.to_i
hash = {}
result = []
n.times do
  m,team,player,card = gets.chomp.split
  if card == 'r'
    result << [team,player,m]
  else
    if hash[[team,player]]
      result << [team,player,m]
    else
      hash[[team,player]] = true
    end
  end
end
result = result.sort_by {|x| x[2]}
result.each do |team,player,minute|
  puts "#{team == 'h' ? h : a} #{player} #{minute}"
end

h = gets.chomp
a = gets.chomp
n = gets.to_i
hash = {}
result = []
n.times do
  m,team,player,card = gets.chomp.split
  if card == 'r'
    result << [team,player,m.to_i]
  else
    if hash[[team,player]]
      result << [team,player,[m.to_i,hash[[team,player]]].max]
    else
      hash[[team,player]] = m.to_i
    end
  end
end
result = result.sort_by {|x| x[2]}
result.each do |team,player,minute|
  puts "#{team == 'h' ? h : a} #{player} #{minute}"
end

team_a = STDIN.readline.strip
team_b = STDIN.readline.strip
n = STDIN.readline.to_i
foul = {}
n.times do
  tokens = STDIN.readline.split
  time, player, color = tokens[0].to_i, tokens[2].to_i, tokens[3]
  team = tokens[1] == 'h' ? team_a : team_b
  key = [player, team]
  if color == 'y'
    if foul[key] == 1
      puts '%s %d %d' % [team, player, time]
      foul[key] += 1
    else
      foul[key] = 1
    end
  else
    if not foul.include? key
      puts '%s %d %d' % [team, player, time]
      foul[key] = 2
    else
      if foul[key] == 1
        puts '%s %d %d' % [team, player, time]
      end
      foul[key] += 1
    end
  end
end

#! /usr/bin/env ruby
# coding: utf-8

class Player
  attr_reader :time, :team, :b_num, :card

  def initialize(l)
    @time  = l[0].to_i
    @team  = l[1]
    @b_num = l[2].to_i
    @card  = l[3]
  end

  def update(p)
    @time = p.time
    @card = 'r'
  end

end

class Players
  def initialize
    @faul_receivers = []
  end

  def <<(p)
    if @faul_receivers.length < 1
      @faul_receivers << p
    else
      update = false
      @faul_receivers.each do |r|
        update= true if r.team == p.team and r.b_num == p.b_num
        if update
          r.update(p)
          break
        end
      end
      @faul_receivers << p unless update
    end
  end

  def red_card_list
    reds = []
    @faul_receivers.each do |p|
      reds << p if p.card == 'r'
    end
    reds.sort_by! { |p| p.time }
    return reds
  end

  def each(&block)
    @faul_receivers.each &block
  end
end

h, a, n = gets.chomp, gets.chomp, gets.chomp.to_i

p_l = Players.new
n.times do
  l = gets.chomp.split(' ')
  p = Player.new(l)
  p_l << p
end

p_l.each do |p|
  if p.card == "r"
    t = p.team == "a" ? a : h
    puts "#{t} #{p.b_num} #{p.time}"
  end
end

#! /usr/bin/env ruby
# coding: utf-8

class Player
  attr_reader :time, :team, :b_num, :card

  def initialize(l)
    @time  = l[0].to_i
    @team  = l[1]
    @b_num = l[2].to_i
    @card  = l[3]
  end

  def update(p)
    @time = p.time
    @card = 'r'
  end

end

class Players
  def initialize
    @faul_receivers = []
  end

  def <<(p)
    if @faul_receivers.length < 1
      @faul_receivers << p
    else
      update = false
      @faul_receivers.each do |r|
        update= true if r.team == p.team and r.b_num == p.b_num
        if update
          r.update(p)
          break
        end
      end
      @faul_receivers << p unless update
    end
  end

  def red_card_list
    reds = []
    @faul_receivers.each do |p|
      reds << p if p.card == 'r'
    end

    reds.sort_by! { |p| p.time }
    return reds
  end

  def each(&block)
    @faul_receivers.each &block
  end
end

h, a, n = gets.chomp, gets.chomp, gets.chomp.to_i

p_l = Players.new
n.times do
  l = gets.chomp.split(' ')
  p = Player.new(l)
  p_l << p
end

p_l.red_card_list.each do |p|
  t = p.team == "a" ? a : h
  puts "#{t} #{p.b_num} #{p.time}"
end

home_team = gets.chomp
away_team = gets.chomp
N = gets.to_i
used = {}
while $_ = gets do
    t_, team, m_, type = $_.split
    t = t_.to_i
    m = m_.to_i
    if type == "r" || used["#{team}:#{m}"] then
        if team == "h"
            print home_team
        else
            print away_team
        end
        print " #{m} #{t}\n"
    end
    used["#{team}:#{m}"] = true
end

a=Array.new(105,0)
b=Array.new(105,0)
sz=Array.new
sta=gets.to_s
stb=gets.to_s
n=gets.to_i
for i in 1..n
  stc=gets.to_s
  sz=stc.split
  if sz[3]=='y'
    tr=1
  elsif sz[3]=="r"
    tr=2
  end
  if sz[1]=="h"
    t=sz[2].to_i
    a[t]+=tr
    if a[t]>=2
      print sta.chomp
      print " "
      print t
      print " "
      puts sz[0]
    end
  elsif sz[1]=="a"
    t=sz[2].to_i
    b[t]+=tr
    if b[t]>=2
      print stb.chomp
      print " "
      print t
      print " "
      puts sz[0]
    end
  end
end

# 493A

class Foul
  include Comparable
  attr :time

  def initialize(player, time, team)
    @player = player
    @time = time
    @team = team
  end

  def <=>(another)
    time <=> another.time
  end

  def to_s
    [@team, @player, @time].join(' ')
  end
end

names = {h: gets.chomp, a: gets.chomp}
cards = {h: {y: {}, r: {}}, a: {y: {}, r: {}}}
gets.to_i.times do
  time, _team, player, card_colour = gets.chomp.split
  team = _team.to_sym
  unless cards[team][:r].include?(player)
    if card_colour == 'r'
      cards[team][:r][player] = time
    else
      if cards[team][:y].include?(player)
        cards[team][:r][player] = time
      else
        cards[team][:y][player] = time
      end
    end
  end
end

fouls = []
[:h, :a].each { |c| cards[c][:r].each { |k, v| fouls << Foul.new(k, v, names[c]) } }
fouls.sort.each { |foul| puts foul }

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]!= 'r') && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
    if a[arry[i][1]] ==nil
      a.merge!( arry[i][1] => {} )
    end
    if a[arry[i][1]][arry[i][2]] == nil || a[arry[i][1]][arry[i][2]] == 'y'
      a[arry[i][1]][arry[i][2]] = 'r'
    end
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]==nil) && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if ((a[arry[i][1]]==nil && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (a[arry[i][1]] && a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y') || arry[i][3] == 'r'
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]!= 'r') && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end

    if a[arry[i][1]] ==nil
      a.merge!( arry[i][1] => {} )
    end

    if a[arry[i][1]][arry[i][2]] == 'y'
      a[arry[i][1]][arry[i][2]] = 'r'
    end

    if a[arry[i][1]][arry[i][2]] == nil
      a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
    end

  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]!= 'r') && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
    if a[arry[i][1]] ==nil
      a.merge!( arry[i][1] => {} )
    end
    a[arry[i][1]].merge!(  arry[i][2] => 'r' )
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]!= 'r') && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end


Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n × n matrix W, consisting of integers, and you should find two n × n matrices A and B, all the following conditions must hold:   Aij = Aji, for all i, j (1 ≤ i, j ≤ n);  Bij =  - Bji, for all i, j (1 ≤ i, j ≤ n);  Wij = Aij + Bij, for all i, j (1 ≤ i, j ≤ n). Can you solve the problem?

The first line contains an integer n (1 ≤ n ≤ 170). Each of the following n lines contains n integers. The j-th integer in the i-th line is Wij (0 ≤ |Wij| < 1717).

The first n lines must contain matrix A. The next n lines must contain matrix B. Print the matrices in the format equal to format of matrix W in input. It is guaranteed that the answer exists. If there are multiple answers, you are allowed to print any of them. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 4.

n = gets.to_i
a = []
n.times do
	a << gets.split(" ").map(&:to_i)
end
b = []
n.times do
	b << []
end
c = []
n.times do
	c << []
end
(0...n).each do |i|
	(0...n).each do |j|
		if i == j
			b[i][j] = a[i][j].to_f
			c[i][j] = 0.0
		elsif i > j
			t = (a[i][j]+a[j][i])/2.0
			b[i][j] = t
			b[j][i] = t
			c[i][j] = a[i][j] - t
			c[j][i] = -c[i][j]
 		end
	end
end

b.each do |v|
	puts v.join(" ")
end
c.each do |v|
	puts v.join(" ")
end


Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть n точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x1 километров вдоль улицы, второй — в точке x2 и так далее, n-й велопрокат находится в точке xn. Школа Аркадия находится в точке x1 (то есть там же, где и первый велопрокат), а дом — в точке xn (то есть там же, где и n-й велопрокат). Известно, что xi < xi + 1 для всех 1 ≤ i < n.Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы. Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.

В первой строке следуют два целых числа n и k (2 ≤ n ≤ 1 000, 1 ≤ k ≤ 100 000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде. В следующей строке следует последовательность целых чисел x1, x2, ..., xn (0 ≤ x1 < x2 < ... < xn ≤ 100 000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания.

Если Аркадий не сможет добраться от школы до дома только на велосипедах, выведите -1. В противном случае, выведите минимальное количество велосипедов, которые Аркадию нужно взять в точках проката.

ПримечаниеВ первом примере Аркадий должен взять первый велосипед в первом велопрокате и доехать на нём до второго велопроката. Во втором велопрокате он должен взять новый велосипед, на котором он сможет добраться до четвертого велопроката, рядом с которым и находится его дом. Поэтому Аркадию нужно всего два велосипеда, чтобы добраться от школы до дома.Во втором примере всего два велопроката, расстояние между которыми 10. Но максимальное расстояние, которое можно проехать на одном велосипеде, равно 9. Поэтому Аркадий не сможет добраться от школы до дома только на велосипедах.

n, k = gets.split.map(&:to_i)
xs = gets.split.map(&:to_i)
def get_result k, xs
  diffs=(0..xs.size-2).map do |i| xs[i+1]-xs[i]; end
  if diffs.any?{|d| d>k}
    return -1
  end

  diffs.inject([0]) do |memo,d|
    last = memo.pop
    if(last+d<=k)
      memo<<last+d
    else
      memo<<last
      memo<<d
    end
    memo
  end.length
end
puts get_result k, xs


'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2. The finals will have n questions, m of them are auction questions and n - m of them are regular questions. Each question has a price. The price of the i-th question is ai points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100; m ≤ min(n, 30)) — the total number of questions and the number of auction questions, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the prices of the questions. The third line contains m distinct integers bi (1 ≤ bi ≤ n) — the numbers of auction questions. Assume that the questions are numbered from 1 to n.

In the single line, print the answer to the problem — the maximum points the R2 company can get if it plays optimally well. It is guaranteed that the answer fits into the integer 64-bit signed type.

r=lambda{gets.split.map{|i| i.to_i}}
n,m=r.call
a=r.call
b=r.call
f=(0..n-1)
s=f.select{|i| !b.include?(i+1)}.inject(0){|s,i| s+=a[i]}
a=f.select{|i| b.include?(i+1)}.map{|i| a[i]}.sort
puts (s+[a.pop,s].max)*(2**a.length)

r=lambda{gets.split.map{|i| i.to_i}}
n,m=r.call
a=r.call
b=r.call
f=(0..n-1)
s=f.select{|i| !b.include?(i+1)}.inject(0){|s,i| s+=a[i]}
a=f.select{|i| b.include?(i+1)}.map{|i| a[i]}.sort
(0..a.length-1).each{|i| if a[i]>s*(2**i)
		s+=a.pop
		break
	end}
puts s*(2**a.length)

r=lambda{gets.split.map{|i| i.to_i}}
n,m=r.call
a=r.call
b=r.call
f=(0..n-1)
s=f.select{|i| !b.include?(i+1)}.inject(0){|s,i| s+=a[i]}
a=f.select{|i| b.include?(i+1)}.map{|i| a[i]}.sort
puts (s+a.pop)*(2**a.length)

r=lambda{gets.split.map{|i| i.to_i}}
n,m=r.call
a=r.call
b=r.call
f=(0..n-1)
s=f.select{|i| !b.include?(i+1)}.inject(0){|s,i| s+=a[i]}
a=f.select{|i| b.include?(i+1)}.map{|i| a[i]}.sort
a.each{|v| s+=(s>=v) ? s : a.pop*2}
puts s


The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.

The first line contains four space-separated integers x0, y0, x1, y1 (1 ≤ x0, y0, x1, y1 ≤ 109), denoting the initial and the final positions of the king. The second line contains a single integer n (1 ≤ n ≤ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 ≤ ri, ai, bi ≤ 109, ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily. It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.

If there is no path between the initial and final position along allowed cells, print -1. Otherwise print a single integer — the minimum number of moves the king needs to get from the initial position to the final one.

#!/usr/bin/env ruby

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

t = {}

x0, y0, x1, y1 = read_ints
n = read_ints[0]
n.times do
  r, a, b = read_ints
  t[r] = {} if not t.has_key?(r)
  (a..b).each do |i|
    t[r][i] = 1e9
  end
end

q = [[x0, y0]]
t[x0][y0] = 0
while not q.empty?
  x, y = q.shift
  (-1..1).each do |dx|
    (-1..1).each do |dy|
      if dx != 0 || dy != 0
        nx, ny = x + dx, y + dy
        if t.has_key?(nx) && t[nx].has_key?(ny) && t[x][y] + 1 < t[nx][ny]
          t[nx][ny] = t[x][y] + 1
          q.push([nx, ny])
          if nx == x1 && ny == y1
            break(3)
          end
        end
      end
    end
  end
end
if t[x1][y1] == 1e9
  puts -1
else
  puts t[x1][y1]
end


You are given $$$n$$$ of integers $$$a_1, a_2, \ldots, a_n$$$. Process $$$q$$$ queries of two types: query of the form "0 $$$x_j$$$": add the value $$$x_j$$$ to all even elements of the array $$$a$$$, query of the form "1 $$$x_j$$$": add the value $$$x_j$$$ to all odd elements of the array $$$a$$$.Note that when processing the query, we look specifically at the odd/even value of $$$a_i$$$, not its index.After processing each query, print the sum of the elements of the array $$$a$$$.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

The first line of the input contains an integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \leq n$$$, $$$q \leq 10^5$$$) — the length of array $$$a$$$ and the number of queries. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. The following $$$q$$$ lines contain queries as two integers $$$type_j$$$ and $$$x_j$$$ $$$(0 \leq type_j \leq 1$$$, $$$1 \leq x_j \leq 10^4$$$). It is guaranteed that the sum of values $$$n$$$ over all test cases in a test does not exceed $$$10^5$$$. Similarly, the sum of values $$$q$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print $$$q$$$ numbers: the sum of the elements of the array $$$a$$$ after processing a query.

# ○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．
def int(b = 0); gets.to_i + b end
def ints(b = 0); gets.split.map{ |x| x.to_i + b } end
def str; gets.chomp end
OO = (1<<62)-(1<<31)
# ○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．

def solve
  n, q = ints
  a = ints
  n_evens = a.count(&:even?)
  n_odds = a.count(&:odd?)
  s = a.sum
  q.times do
    t, x = ints
    case t
    when 0
      s += n_evens * x
      puts s
      if x.odd?
        n_odds += n_evens
        n_evens = 0
      end
    when 1
      s += n_odds * x
      puts s
      if x.odd?
        n_evens += n_odds
        n_odds = 0
      end
    end
  end
end

t = int
t.times do
  solve
end


Vus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings $$$a$$$ and $$$b$$$. It is known that $$$|b| \leq |a|$$$, that is, the length of $$$b$$$ is at most the length of $$$a$$$.The Cossack considers every substring of length $$$|b|$$$ in string $$$a$$$. Let's call this substring $$$c$$$. He matches the corresponding characters in $$$b$$$ and $$$c$$$, after which he counts the number of positions where the two strings are different. We call this function $$$f(b, c)$$$.For example, let $$$b = 00110$$$, and $$$c = 11000$$$. In these strings, the first, second, third and fourth positions are different.Vus the Cossack counts the number of such substrings $$$c$$$ such that $$$f(b, c)$$$ is even.For example, let $$$a = 01100010$$$ and $$$b = 00110$$$. $$$a$$$ has four substrings of the length $$$|b|$$$: $$$01100$$$, $$$11000$$$, $$$10001$$$, $$$00010$$$.  $$$f(00110, 01100) = 2$$$; $$$f(00110, 11000) = 4$$$; $$$f(00110, 10001) = 4$$$; $$$f(00110, 00010) = 1$$$. Since in three substrings, $$$f(b, c)$$$ is even, the answer is $$$3$$$.Vus can not find the answer for big strings. That is why he is asking you to help him.

The first line contains a binary string $$$a$$$ ($$$1 \leq |a| \leq 10^6$$$) — the first string. The second line contains a binary string $$$b$$$ ($$$1 \leq |b| \leq |a|$$$) — the second string.

NoteThe first example is explained in the legend.In the second example, there are five substrings that satisfy us: $$$1010$$$, $$$0101$$$, $$$1111$$$, $$$1111$$$.

A = gets.chomp
B = gets.chomp

nx = 0
core = 0
(0...B.size-1).each{ |i|
  nx = (nx + (B[i] == B[i+1] ? 0 : 1)) % 2
  core = (core + (A[i] == B[i] ? 0 : 1)) % 2
}

p (0..(A.size-B.size)).count{ |i|
  right = A[B.size+i-1] == B[-1] ? 0 : 1
  left = A[i] == B[0] ? 0 : 1
  v = (right + core) % 2 == 0
  core = core + left + right + nx
  v
}

A = gets.chomp
B = gets.chomp

nx = 0
core = 0
(0...B.size-1).each{ |i|
  nx = (nx + (B[i] == B[i+1] ? 0 : 1)) % 2
  core = (core + (A[i] == B[i] ? 0 : 1)) % 2
}

p (0..(A.size-B.size)).count{ |i|
  right = A[B.size+i-1] == B[-1] ? 0 : 1
  left = A[i] == B[0] ? 0 : 1
  v = (right + core) % 2 == 0
  core = core + left + right
  v
}


Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n = p1·p2·...·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109 + 7 is the password to the secret data base. Now he wants to calculate this value.

The first line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of primes in factorization of n.  The second line contains m primes numbers pi (2 ≤ pi ≤ 200 000).

Print one integer — the product of all divisors of n modulo 109 + 7.

NoteIn the first sample n = 2·3 = 6. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1·2·3·6 = 36.In the second sample 2·3·2 = 12. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1·2·3·4·6·12 = 1728.

MOD = 1000000000 + 7

def f(n, p)
  if p == 0 then
    return 1
  end
  m = f(n, p / 2)
  if p % 2 == 1 then
    return m * m * n % MOD
  else
    return m * m % MOD
  end
end

while s = $stdin.gets() do
  s = $stdin.gets()
  ps = s.split(" ")
  cnt = {}
  ps.each do |p|
    key = p.to_i()
    if cnt[key] then
      cnt[key] = cnt[key] + 1
    else
      cnt[key] = 1
    end
  end

  d = 1
  cnt.each do |key, val|
    d *= val + 1
  end

  ret = 1
  cnt.each do |key, val|
    x = f(key, (val * (val + 1) / 2) % (MOD - 1))
    y = f(x, (d / (val + 1)) % (MOD - 1))
    ret = ret * y % MOD
  end
  puts(ret)
end

def powmod(a, k, m)
  return 1 if k == 0
  t = powmod(a, k / 2, m)
  t = t * t % m
  t = t * a % m if k % 2 == 1
  return t
end

m = gets.chomp.to_i
ps = gets.chomp.split.map(&:to_i)
mod = 10**9 + 7
n = 1

hs = Hash.new(1)
ps.each do |p|
  hs[p] += 1
  n = n * p % mod
end

cnt = 1
hs.each do |_, v|
  cnt = cnt * v % (2 * (mod - 1))
end

r = 1
if cnt % 2 == 1
  hs.each do |k, v|
    r = r * powmod(k, (v - 1) / 2, mod) % mod
  end
end

puts r * powmod(n, cnt / 2, mod) % mod

def powmod(a, k, m)
  return 1 if k == 0
  t = powmod(a, k / 2, m)
  t = t * t % m
  t = t * a % m if k % 2 == 1
  return t
end

m = gets.chomp.to_i
ps = gets.chomp.split.map(&:to_i)
mod = 10**9 + 7
n = 1

hs = Hash.new(1)
ps.each do |p|
  hs[p] += 1
  n = n * p % mod
end

cnt = 1
hs.each do |_, v|
  cnt *= v
end

puts powmod(n, cnt / 2, mod)


President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.

The first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.

Print the only number — the amount of President's deputies.

s = gets.split

n = s[0].to_i
m = s[1].to_i

col = s[2]

dots = []
matrix = []
n.times do |x|
    matrix << gets.chomp
    k = -1
    while k = matrix[x].index(col, k+1) do
        dots << [x, k]
    end
end

t = {}

dots.size.times do |i|
    dot = dots[i]
    if dot[1]+1 < m then
        if matrix[dot[0]][dot[1]+1] != col then
            if t[matrix[dot[0]][dot[1]+1]] then
                t[matrix[dot[0]][dot[1]+1]] += 1
            else
                t[matrix[dot[0]][dot[1]+1]] = 1
            end
        end
    end
    if dot[1] > 0 then
        if matrix[dot[0]][dot[1]-1] != col then
            if t[matrix[dot[0]][dot[1]-1]] then
                t[matrix[dot[0]][dot[1]-1]] += 1
            else
                t[matrix[dot[0]][dot[1]-1]] = 1
            end
        end
    end
    if dot[0]+1 < n then
        if matrix[dot[0]+1][dot[1]] != col then
            if t[matrix[dot[0]+1][dot[1]]] then
                t[matrix[dot[0]+1][dot[1]]] += 1
            else
                t[matrix[dot[0]+1][dot[1]]] = 1
            end
        end
    end
    if dot[0] > 0 then
        if matrix[dot[0]-1][dot[1]] != col
            if t[matrix[dot[0]-1][dot[1]]] then
                t[matrix[dot[0]-1][dot[1]]] += 1
            else
                t[matrix[dot[0]-1][dot[1]]] = 1
            end
        end
    end
end

t.delete(".")

puts t.size

ns,ms,c = gets.chomp.split(/ /)
n = ns.to_i
m = ms.to_i
ar = Array.new
for i in 0..n-1
	ar[i] = gets.chomp.split(//)
end

s = Hash.new

for i in 0..n-1
	for j in 0..m-1
		if ar[i][j] == c
			s[ar[i-1][j]] = 1 if i > 0
			s[ar[i+1][j]] = 1 if i < n-1
			s[ar[i][j-1]] = 1 if j > 0
			s[ar[i][j+1]] = 1 if j < m-1
		end
	end
end

s.delete(c)
s.delete(".")
puts s.length

n, m, c = gets.chomp!.split
n = n.to_i
m = m.to_i
ary = []
hash = {}
n.times {ary << gets.chomp!}
n.times do |i|
	m.times do |j|
		if ary[i][j] == c
			hash[ary[i][j]] = 1
			hash[ary[i - 1][j]] = 1 if i - 1 >= 0
			hash[ary[i + 1][j]] = 1 if i + 1 < n
			hash[ary[i][j - 1]] = 1 if j - 1 >= 0
			hash[ary[i][j + 1]] = 1 if j + 1 < m
		end
	end
end
hash.delete c
hash.delete '.'
puts hash.size

def check(y,x)
  return 0<=y && y<$n && 0<=x && x<$m && $room[y][x,1]==$c
end

$n,$m,$c=STDIN.gets.chomp.split
$n=$n.to_i
$m=$m.to_i
$room=[]
$n.times {$room<<STDIN.gets.chomp}
desks={}
$n.times {|i|
  $m.times {|j|
    if $room[i][j,1]==$c || $room[i][j,1]=="." then next end
    if check(i,j-1) || check(i,j+1) || check(i-1,j) || check(i+1,j) then
      desks[$room[i][j,1]]=1
    end
  }
}
print(desks.length,"\n")

n,m,r=gets.split()
r=r[0]
n=n.to_i
m=m.to_i

map=Array.new(n)
for i in 0..n-1
        map[i]=gets.split[0]
end

res=[]
dx=[1,0,-1,0]
for i in 0..n-1
        for j in 0..m-1
                next if map[i][j]!=r
                for k in 0..3
                        nx=i+dx[k]
                        ny=j+dx[k^1]
                        if nx>=0&&nx<n&&ny>=0&&ny<m then
                                res.push(map[nx][ny]) unless map[nx][ny]==r
                        end
                end
        end
end
ans=0

for i in 0..res.length-1
        ok=1
        for j in 0..i-1
                ok=0 if res[i]==res[j]
        end
        next if ok==0||res[i]=="."
        ans+=1
end

p ans

y,x,p = gets.split
y = y.to_i
x = x.to_i

arr = []

y.times do |i|
    line = gets.chomp
    line = line.split(//).join(' ');
    arr[i] = line.split
end
count = 0
exists = []

y.times do |i|
    x.times do |j|
        if arr[i][j] == p
            if  i != 0 && arr[i-1][j] != '.' && arr[i-1][j] != p
                if exists.index(arr[i-1][j]) == nil
                    count = count+1
                    exists << arr[i-1][j]
                end
            end
            if j != 0 && arr[i][j-1] != '.' && arr[i][j-1] != p
                if exists.index(arr[i][j-1]) == nil
                    count = count+1
                    exists << arr[i][j-1]
                end
            end
            if  i != y-1 && arr[i+1][j] != '.' && arr[i+1][j] != p
                if exists.index(arr[i+1][j]) == nil
                    count = count+1
                    exists << arr[i+1][j]
                end
            end
            if j != x-1 && arr[i][j+1] != '.' && arr[i][j+1] != p
                if exists.index(arr[i][j+1]) == nil
                    count = count+1
                    exists << arr[i][j+1]
                end
            end
        end
    end
end
puts count

tmp=gets.chomp.split
n=tmp[0].to_i
m=tmp[1].to_i
c=tmp[2]
memo=Array.new(n)
n.times do |j|
  memo[j]= gets.chomp!.each_char.map{|i| i}
end
ti=0
tj=0
h={}
n.times do |i|
  m.times do |j|
    if memo[i][j]==c
      ti=i
      tj=j
      if ti!=0
        h[memo[ti-1][tj]]=true
      end
      if ti!=n-1
        h[memo[ti+1][tj]]=true
      end
      if tj!=0
        h[memo[ti][tj-1]]=true
      end
      if tj!=m-1
        h[memo[ti][tj+1]]=true
      end
    end
  end
end
h.delete(c)
h.delete(".")
puts h.size

require 'Set'
height,width,color = gets.split
width = width.to_i
height = height.to_i
#p width
#p height
#p color
dh = [-1, 0, 0, 1]
dw = [0, -1, 1, 0]
data = Array.new()
for h in 0...height do
  data[h] = gets
end
ans = Set.new()
ans.add?(color)
for h in 0...height do
  for w in 0...width do
    if data[h][w,1] == color then
      #print h, w
      #puts
      for d in 0...4 do
        nh = h + dh[d]
        nw = w + dw[d]
        if nh >= 0 && nw >= 0 && nh < height && nw < width && data[nh][nw,1] != "." then
          ans.add?(data[nh][nw,1])
        end
      end
    end
  end
end
p ans.size()-1

fst = gets.split
N=fst[0].to_i
M=fst[1].to_i
PresidentsColor=fst[2][0]
matrix = Array.new(N)
N.times do |i|
  line = gets.chomp
  matrix[i] = Array.new(M)
  M.times do |j|
    matrix[i][j] = line[j]
  end
end
deputies = []
matrix.each_index do |i|
  matrix[i].each_with_index do |c,j|
    if c==PresidentsColor
      deputies << matrix[i-1][j] if i!=0
      deputies << matrix[i+1][j] if i!=N-1
      deputies << matrix[i][j-1] if j!=0
      deputies << matrix[i][j+1] if j!=M-1
    end
  end
end
deputies.uniq!
deputies.delete "."[0]
deputies.delete PresidentsColor
puts deputies.size

require 'set'

n, m, p_desk = gets.split
n = n.to_i
m = m.to_i

grid = []
n.times do |index|
	row = gets.chomp.split('')
	grid << row
end

desks = Set.new
0.upto(n - 1) do |x|
	0.upto(m - 1) do |y|
		next if grid[x][y] == ?. or grid[x][y] == p_desk
		desks << grid[x][y] if (x > 0 and grid[x - 1][y] == p_desk) || (y > 0 and grid[x][y - 1] == p_desk) ||
							             (x < n - 1 and grid[x + 1][y] == p_desk) || (y < m - 1 and grid[x][y + 1] == p_desk)
  end
end

puts desks.size

n,m,c = gets.split(/\s+/)
n = n.to_i
m = m.to_i
c = c[0]
a = Array.new(n)
n.times do |i|
  a[i] = gets.strip
end

h = []

0.upto(n-1) do |i|
  0.upto(m-1) do |j|
    next if a[i][j] == ?. or a[i][j] == c
    h << a[i][j] if (i > 0 and a[i-1][j] == c) || (j > 0 and a[i][j-1] == c) ||
                    (i < n-1 and a[i+1][j] == c) || (j < m-1 and a[i][j+1] == c)
  end
end

puts h.uniq.size

def extractIndices(office, color)
  startingCol, endingCol, startingRow, endingRow = -1, -1, -1, -1
  office.each_with_index do |row, rIdx|
    if row.include? color
      if startingRow == -1 #we do this just for the first row
        startingCol = row.find_index(color)
        (startingCol..row.length-1).each do |idx|
          if row[idx] != color
            endingCol = idx-1
            break
          end
        end
        if endingCol == -1
          endingCol = row.length-1
        end
      end
      startingRow = rIdx if startingRow == -1
      endingRow = rIdx if rIdx >= endingRow
    end
  end
  return startingCol, endingCol, startingRow, endingRow
end

n, m, color = nil, nil, nil
office = []
# File.open("input1", "r") do |file|
#   n, m, color = file.readline.split(" ")
#   n = n.to_i
#   m = m.to_i
#   n.times do
#     office << file.readline.chomp.split("")
#   end
# end

n, m, color = gets.chomp.split(" ")
n = n.to_i
m = m.to_i
n.times do
  office << gets.chomp.split("")
end

startingCol, endingCol, startingRow, endingRow = extractIndices(office, color)
topRow = startingRow - 1
bottomRow = endingRow + 1
leftCol = startingCol - 1
rightCol = endingCol + 1
found = []

if topRow >= 0
  topRow = office[topRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if topRow[idx-startingCol] == "." or topRow[idx-startingCol] == lastFound
    lastFound = topRow[idx-startingCol]
    found << lastFound
  end
end

if bottomRow < n
  bottomRow = office[bottomRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if bottomRow[idx-startingCol] == "." or bottomRow[idx-startingCol] == lastFound
    lastFound = bottomRow[idx-startingCol]
    found << lastFound
  end
end

if leftCol >= 0
  leftCol = office[startingRow..endingRow].map{|r| r[leftCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if leftCol[idx-startingRow] == "." or leftCol[idx-startingRow] == lastFound
    lastFound = leftCol[idx-startingRow]
    found << lastFound
  end
end

if rightCol < m
  rightCol = office[startingRow..endingRow].map{|r| r[rightCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if rightCol[idx-startingRow] == "." or rightCol[idx-startingRow] == lastFound
    lastFound = rightCol[idx-startingRow]
    found << lastFound
  end
end

puts "#{found.count}"

n, m, c = gets.chomp.split
n = n.to_i
m = m.to_i
room = Array.new
n.times { room << gets.chomp }
ret = 0
x = Hash.new
dy = [0, -1, 0, 1]
dx = [-1, 0, 1, 0]
x[c] = true
x["."] = true
(0...n).each do |i|
  (0...m).each do |j|
    if room[i][j] == c
      (0...(dy.length)).each do |k|
        ii, jj = i + dy[k], j + dx[k]
        next unless ii >= 0 && ii < n && jj >= 0 && jj < m
        unless x.has_key? room[ii][jj]
          x[room[ii][jj]] = true
          ret += 1
        end
      end
    end
  end
end

puts ret

s = gets.split

n = s[0].to_i
m = s[1].to_i

col = s[2]

i = []
j = []

matrix = []
n.times do |x|
    matrix << gets.chomp
    k = -1
    while k = matrix[x].index(col, k+1) do
        i << x
        j << k
    end
end

i = i.uniq
j = j.uniq

t = {}

i.size.times do |x|
    m.times do |y|
        if matrix[i[x]][y] != col then
            if t[matrix[i[x]][y]] then
                t[matrix[i[x]][y]] += 1
            else
                t[matrix[i[x]][y]] = 1
            end
        end
    end
end

j.size.times do |x|
    n.times do |y|
        if matrix[y][j[x]] != col then
            if t[(matrix[y][j[x]])] then
                t[(matrix[y][j[x]])] += 1
            else
                t[(matrix[y][j[x]])] = 1
            end
        end
    end
end

puts t.size-1

s = gets.split

n = s[0].to_i
m = s[1].to_i

col = s[2]

i = []
j = []

matrix = []
n.times do |x|
    matrix << gets.chomp
    k = -1
    while k = matrix[x].index(col, k+1) do
        i << x
        j << k
    end
end

i = i.uniq
j = j.uniq

t = {}

i.size.times do |x|
    m.times do |y|
        if matrix[i[x]][y] != col then
            if t[matrix[i[x]][y]] then
                t[matrix[i[x]][y]] += 1
            else
                t[matrix[i[x]][y]] = 1
            end
        end
    end
end

j.size.times do |x|
    n.times do |y|
        if matrix[y][j[x]] != col then
            if t[(matrix[y][j[x]])] then
                t[(matrix[y][j[x]])] += 1
            else
                t[(matrix[y][j[x]])] = 1
            end
        end
    end
end

t.delete(".")

puts t.size

s = gets.split

n = s[0].to_i
m = s[1].to_i

col = s[2]

dots = []
matrix = []
n.times do |x|
    matrix << gets.chomp
    k = -1
    while k = matrix[x].index(col, k+1) do
        dots << [x, k]
    end
end

t = {}

dots.size.times do |i|
    dot = dots[i]
    if matrix[dot[0]][dot[1]+1] then
        if matrix[dot[0]][dot[1]+1] != col then
            if t[matrix[dot[0]][dot[1]+1]] then
                t[matrix[dot[0]][dot[1]+1]] += 1
            else
                t[matrix[dot[0]][dot[1]+1]] = 1
            end
        end
    end
    if matrix[dot[0]][dot[1]-1] then
        if matrix[dot[0]][dot[1]-1] != col then
            if t[matrix[dot[0]][dot[1]-1]] then
                t[matrix[dot[0]][dot[1]-1]] += 1
            else
                t[matrix[dot[0]][dot[1]-1]] = 1
            end
        end
    end
    if matrix[dot[0]+1] then
        if matrix[dot[0]+1][dot[1]] != col then
            if t[matrix[dot[0]+1][dot[1]]] then
                t[matrix[dot[0]+1][dot[1]]] += 1
            else
                t[matrix[dot[0]+1][dot[1]]] = 1
            end
        end
    end
    if matrix[dot[0]-1] then
        if matrix[dot[0]-1][dot[1]] != col
            if t[matrix[dot[0]-1][dot[1]]] then
                t[matrix[dot[0]-1][dot[1]]] += 1
            else
                t[matrix[dot[0]-1][dot[1]]] = 1
            end
        end
    end
end

t.delete(".")

puts t.size

n, m, c = gets.chomp!.split
n = n.to_i
m = m.to_i
ary = []
hash = {}
n.times {ary << gets.chomp!}
n.times do |i|
	m.times do |j|
		if ary[i][j] == c
			hash[ary[i][j]] = 1
			hash[ary[i - 1][j]] = 1 if i - 1 >= 0
			hash[ary[i + 1][j]] = 1 if i + 1 < n
			hash[ary[i][j - 1]] = 1 if j - 1 >= 0
			hash[ary[i][j + 1]] = 1 if j + 1 < m
		end
	end
end
puts hash

n,m,r=gets.split()
r=r[0]
n=n.to_i
m=m.to_i

map=Array.new(n)
for i in 0..n-1
        map[i]=gets.split[0]
end

res=[]
dx=[1,0,-1,0]
for i in 0..n-1
        for j in 0..m-1
                next if map[i][j]!=r
                for k in 0..3
                        nx=i+dx[k]
                        ny=j+dx[k^1]
                        if nx>=0&&nx<n&&ny>=0&&ny<m then
                                res.push(map[nx][ny]) unless map[nx][ny]==r
                        end
                end
        end
end
ans=0

for i in 0..res.length-1
        ok=1
        for j in 0..i-1
                ok=0 if res[i]==res[j]
        end
        next if ok==0||res[i]=="."
        p res[i]
        ans+=1
end

p ans

tmp=gets.chomp.split
n=tmp[0].to_i
m=tmp[1].to_i
c=tmp[2]
memo=Array.new(n)
n.times do |j|
  memo[j]= gets.chomp!.each_char.map{|i| i}
end
ti=0
tj=0
h={}
n.times do |i|
  m.times do |j|
    if memo[i][j]==c
      ti=i
      tj=j
      if ti!=0 &&memo[ti-1][tj]!="."
        h[memo[ti-1][tj]]=true
      end
      if ti!=n-1&&memo[ti+1][tj]!="."
        h[memo[ti+1][tj]]=true
      end
      if tj!=0 && memo[ti][tj-1]!="."
        h[memo[ti][tj-1]]=true
      end
    end
  end
end
h.delete(c)
puts h.size

require 'Set'
height,width,color = gets.split
width = width.to_i
height = height.to_i
#p width
#p height
#p color
dh = [-1, 0, 0, 1]
dw = [0, -1, 1, 0]
data = Array.new()
for h in 0...height do
  data[h] = gets
end
ans = Set.new()
ans.add?(color)
for h in 0...height do
  for w in 0...width do
    if data[h][w,1] == color then
      #print h, w
      #puts
      for d in 0...4 do
        nh = h + dh[d]
        nw = w + dw[d]
        if nh >= 0 && nw >= 0 && nh < height && nw < width && data[nh][nw,1] != "." then
          ans.add?(data[h-1][w-1,1])
        end
      end
    end
  end
end
p ans.size()-1

def extractIndices(office, color)
  startingCol, endingCol, startingRow, endingRow = -1, -1, -1, -1
  office.each_with_index do |row, rIdx|
    if row.include? color
      if startingRow == -1 #we do this just for the first row
        startingCol = row.find_index(color)
        (startingCol..row.length-1).each do |idx|
          if row[idx] != color
            endingCol = idx-1
            break
          end
        end
        if endingCol == -1
          endingCol = row.length-1
        end
      end
      startingRow = rIdx if startingRow == -1
      endingRow = rIdx if rIdx >= endingRow
    end
  end
  return startingCol, endingCol, startingRow, endingRow
end

n, m, color = nil, nil, nil
office = []
# File.open("input1", "r") do |file|
#   n, m, color = file.readline.split(" ")
#   n = n.to_i
#   m = m.to_i
#   n.times do
#     office << file.readline.chomp.split("")
#   end
# end

n, m, color = gets.chomp.split(" ")
n = n.to_i
m = m.to_i
n.times do
  office << gets.chomp.split("")
end

startingCol, endingCol, startingRow, endingRow = extractIndices(office, color)
topRow = startingRow - 1
bottomRow = endingRow + 1
leftCol = startingCol - 1
rightCol = endingCol + 1
found = []

puts "#{topRow}, #{bottomRow}, #{leftCol}, #{rightCol}"

if topRow >= 0
  topRow = office[topRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if topRow[idx-startingCol] == "." or topRow[idx-startingCol] == lastFound
    lastFound = topRow[idx-startingCol]
    found << lastFound
  end
end

if bottomRow < n
  bottomRow = office[bottomRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if bottomRow[idx-startingCol] == "." or bottomRow[idx-startingCol] == lastFound
    lastFound = bottomRow[idx-startingCol]
    found << lastFound
  end
end

if leftCol >= 0
  leftCol = office[startingRow..endingRow].map{|r| r[leftCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if leftCol[idx-startingRow] == "." or leftCol[idx-startingRow] == lastFound
    lastFound = leftCol[idx-startingRow]
    found << lastFound
  end
end

if rightCol < m
  rightCol = office[startingRow..endingRow].map{|r| r[rightCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if rightCol[idx-startingRow] == "." or rightCol[idx-startingRow] == lastFound
    lastFound = rightCol[idx-startingRow]
    found << lastFound
  end
end

puts "#{found.count}"

def extractIndices(office, color)
  startingCol, endingCol, startingRow, endingRow = -1, -1, -1, -1
  office.each_with_index do |row, rIdx|
    if row.include? color
      if startingRow == -1 #we do this just for the first row
        startingCol = row.find_index(color)
        (startingCol..row.length-1).each do |idx|
          if row[idx] != color
            endingCol = idx-1
          end
        end
        if endingCol == -1
          endingCol = row.length-1
        end
      end
      startingRow = rIdx if startingRow == -1
      endingRow = rIdx if rIdx >= endingRow
    end
  end
  return startingCol, endingCol, startingRow, endingRow
end

n, m, color = nil, nil, nil
office = []
# File.open("input1", "r") do |file|
#   n, m, color = file.readline.split(" ")
#   n = n.to_i
#   m = m.to_i
#   n.times do
#     office << file.readline.chomp.split("")
#   end
# end

n, m, color = gets.chomp.split(" ")
n = n.to_i
m = m.to_i
n.times do
  office << gets.chomp.split("")
end

startingCol, endingCol, startingRow, endingRow = extractIndices(office, color)
topRow = startingRow - 1
bottomRow = endingRow + 1
leftCol = startingCol - 1
rightCol = endingCol + 1
found = []

if topRow >= 0
  topRow = office[topRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if topRow[idx-startingCol] == "." or topRow[idx-startingCol] == lastFound
    lastFound = topRow[idx-startingCol]
    found << lastFound
  end
end

if bottomRow < n
  bottomRow = office[bottomRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if bottomRow[idx-startingCol] == "." or bottomRow[idx-startingCol] == lastFound
    lastFound = bottomRow[idx-startingCol]
    found << lastFound
  end
end

if leftCol >= 0
  leftCol = office[startingRow..endingRow].map{|r| r[leftCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if leftCol[idx-startingRow] == "." or leftCol[idx-startingRow] == lastFound
    lastFound = leftCol[idx-startingRow]
    found << lastFound
  end
end

if rightCol < m
  rightCol = office[startingRow..endingRow].map{|r| r[rightCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if rightCol[idx-startingRow] == "." or rightCol[idx-startingRow] == lastFound
    lastFound = rightCol[idx-startingRow]
    found << lastFound
  end
end

puts "#{found.count}"

def extractIndices(office, color)
  startingCol, endingCol, startingRow, endingRow = -1, -1, -1, -1
  office.each_with_index do |row, rIdx|
    if row.include? color
      if startingRow == -1 #we do this just for the first row
        startingCol = row.find_index(color)
        (startingCol..row.length-1).each do |idx|
          if row[idx] != color
            endingCol = idx-1
          end
        end
        if endingCol == -1
          endingCol = row.length-1
        end
      end
      startingRow = rIdx if startingRow == -1
      endingRow = rIdx if rIdx >= endingRow
    end
  end
  return startingCol, endingCol, startingRow, endingRow
end

n, m, color = nil, nil, nil
office = []
# File.open("input2", "r") do |file|
#   n, m, color = file.readline.split(" ")
#   n = n.to_i
#   m = m.to_i
#   n.times do
#     office << file.readline.chomp.split("")
#   end
# end

n, m, color = gets.chomp.split(" ")
n = n.to_i
m = m.to_i
n.times do
  office << gets.chomp.split("")
end

startingCol, endingCol, startingRow, endingRow = extractIndices(office, color)
topRow = startingRow - 1
bottomRow = endingRow + 1
leftCol = startingCol - 1
rightCol = endingCol + 1
found = []

if topRow >= 0
  topRow = office[topRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if topRow[idx-startingCol] == "." or topRow[idx-startingCol] == lastFound
    lastFound = topRow[idx-startingCol]
    found << lastFound
  end
end

if bottomRow < n
  bottomRow = office[bottomRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if bottomRow[idx-startingCol] == "." or bottomRow[idx-startingCol] == lastFound
    lastFound = bottomRow[idx-startingCol]
    found << lastFound
  end
end

if leftCol >= 0
  leftCol = office[startingRow..endingRow].map{|r| r[leftCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if leftCol[idx-startingRow] == "." or leftCol[startingRow] == lastFound
    lastFound = leftCol[idx]
    found << lastFound
  end
end

if rightCol < m
  rightCol = office[startingRow..endingRow].map{|r| r[rightCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if rightCol[idx-startingRow] == "." or rightCol[startingRow] == lastFound
    lastFound = rightCol[idx]
    found << lastFound
  end
end

puts "#{found.length}"


The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers. All these integers are distinct, each value from $$$1$$$ to $$$n$$$ appears in the sequence exactly once.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[2, 1, 5, 4, 3]$$$ the answer is $$$4$$$ (you take $$$2$$$ and the sequence becomes $$$[1, 5, 4, 3]$$$, then you take the rightmost element $$$3$$$ and the sequence becomes $$$[1, 5, 4]$$$, then you take $$$4$$$ and the sequence becomes $$$[1, 5]$$$ and then you take $$$5$$$ and the sequence becomes $$$[1]$$$, the obtained increasing sequence is $$$[2, 3, 4, 5]$$$).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. All these integers are pairwise distinct.

In the first line of the output print $$$k$$$ — the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.

NoteThe first example is described in the problem statement.

N = gets.to_i
A = gets.split.map(&:to_i)

cur = -1
ans = []

until A.empty?
  l = A[0]
  r = A[-1]

  l = Float::INFINITY if l < cur && cur > 0
  r = Float::INFINITY if r < cur && cur > 0

  if cur < l && l <= r && l != Float::INFINITY
    cur = A.shift
    ans << 'L'
  elsif cur < r && l >= r && r != Float::INFINITY
    cur = A.pop
    ans << 'R'
  else
    break
  end
end

puts ans.size
puts ans.join

N = gets.to_i
A = gets.split.map(&:to_i)

cur = -1
ans = []

until A.empty?
  l = A[0]
  r = A[-1]

  l = Float::INFINITY if l < cur && cur > 0
  r = Float::INFINITY if r < cur && cur > 0

  if cur < l && l <= r
    cur = A.shift
    ans << 'L'
  elsif cur < r && l >= r
    cur = A.pop
    ans << 'R'
  else
    break
  end
end

puts ans.size
puts ans.join


You are given an array of integers $$$a_1,a_2,\ldots,a_n$$$. Find the maximum possible value of $$$a_ia_ja_ka_la_t$$$ among all five indices $$$(i, j, k, l, t)$$$ ($$$i<j<k<l<t$$$).

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t\le 2 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$5\le n\le 10^5$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$-3\times 10^3\le a_i\le 3\times 10^3$$$) — given array. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print one integer — the answer to the problem.

NoteIn the first test case, choosing $$$a_1,a_2,a_3,a_4,a_5$$$ is a best choice: $$$(-1)\cdot (-2) \cdot (-3)\cdot (-4)\cdot (-5)=-120$$$.In the second test case, choosing $$$a_1,a_2,a_3,a_5,a_6$$$ is a best choice: $$$(-1)\cdot (-2) \cdot (-3)\cdot 2\cdot (-1)=12$$$.In the third test case, choosing $$$a_1,a_2,a_3,a_4,a_5$$$ is a best choice: $$$(-1)\cdot 0\cdot 0\cdot 0\cdot (-1)=0$$$.In the fourth test case, choosing $$$a_1,a_2,a_3,a_4,a_6$$$ is a best choice: $$$(-9)\cdot (-7) \cdot (-5)\cdot (-3)\cdot 1=945$$$.

gets.to_i.times do
  gets
  a = gets.split(" ").map(&:to_i)
  a.sort!

  a[5...a.size-5] = nil
  a.compact!

  best = -999999999999999999999999999999999999999999999999999999999

  (0...a.size).each do |i|
  ((i+1)...a.size).each do |j|
  ((j+1)...a.size).each do |k|
  ((k+1)...a.size).each do |l|
  ((l+1)...a.size).each do |t|
    x = a[i]*a[j]*a[k]*a[l]*a[t]
    best = x if x > best
  end
  end
  end
  end
  end
  p best
end

gets.to_i.times do
  gets
  a = gets.split(" ").map(&:to_i)
  a.sort!

  a[5...a.size-5] = nil
  a.compact!

  best = -9999999999999

  (0...a.size).each do |i|
  ((i+1)...a.size).each do |j|
  ((j+1)...a.size).each do |k|
  ((k+1)...a.size).each do |l|
  ((l+1)...a.size).each do |t|
    x = a[i]*a[j]*a[k]*a[l]*a[t]
    best = x if x > best
  end
  end
  end
  end
  end
  p best
end


To improve the boomerang throwing skills of the animals, Zookeeper has set up an $$$n \times n$$$ grid with some targets, where each row and each column has at most $$$2$$$ targets each. The rows are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns are numbered from $$$1$$$ to $$$n$$$ from left to right.  For each column, Zookeeper will throw a boomerang from the bottom of the column (below the grid) upwards. When the boomerang hits any target, it will bounce off, make a $$$90$$$ degree turn to the right and fly off in a straight line in its new direction. The boomerang can hit multiple targets and does not stop until it leaves the grid.   In the above example, $$$n=6$$$ and the black crosses are the targets. The boomerang in column $$$1$$$ (blue arrows) bounces $$$2$$$ times while the boomerang in column $$$3$$$ (red arrows) bounces $$$3$$$ times. The boomerang in column $$$i$$$ hits exactly $$$a_i$$$ targets before flying out of the grid. It is known that $$$a_i \leq 3$$$.However, Zookeeper has lost the original positions of the targets. Thus, he asks you to construct a valid configuration of targets that matches the number of hits for each column, or tell him that no such configuration exists. If multiple valid configurations exist, you may print any of them.

The first line contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$.  The next line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ $$$(0 \leq a_i \leq 3)$$$.

If no configuration of targets exist, print $$$-1$$$.  Otherwise, on the first line print a single integer $$$t$$$ $$$(0 \leq t \leq 2n)$$$: the number of targets in your configuration.   Then print $$$t$$$ lines with two spaced integers each per line. Each line should contain two integers $$$r$$$ and $$$c$$$ $$$(1 \leq r,c \leq n)$$$, where $$$r$$$ is the target's row and $$$c$$$ is the target's column. All targets should be different.   Every row and every column in your configuration should have at most two targets each.

NoteFor the first test, the answer configuration is the same as in the picture from the statement. For the second test, the boomerang is not supposed to hit anything, so we can place $$$0$$$ targets. For the third test, the following configuration of targets matches the number of hits, but is not allowed as row $$$3$$$ has $$$4$$$ targets.   It can be shown for this test case that no valid configuration of targets will result in the given number of target hits.

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
ans = []
target1 = []
target2 = []
tate = n-1
(n-1).downto(0) do |i|
  if a[i] == 1
    ans << [tate+1,i+1]
    target1 << [tate+1,i+1]
    tate -= 1
  elsif a[i] == 2
    if target1.empty?.!
      ans << [target1[0][0],i+1]
      target2 << [target1[0][0],i+1]
      target1.shift
    else
      puts -1
      exit
    end
  elsif a[i] == 3
    if target2.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target2[0][1]]
      target2.shift
      target2 << [tate+1,i+1]
      tate -= 1
    elsif target1.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target1[0][1]]
      target1.shift
      target2 << [tate+1,i+1]
      tate -= 1
    else
      puts -1
      exit
    end
  end
end
puts ans.length
ans.each do |v|
  puts "#{v[0]} #{v[1]}"
end

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
ans = []
target1 = []
tate = n-1
(n-1).downto(0) do |i|
  if a[i] == 1
    ans << [tate+1,i+1]
    target1 << [tate+1,i+1]
    tate -= 1
  elsif a[i] == 2
    if target1.empty?.!
      ans << [target1[0][0],i+1]
      target1.shift
    else
      puts -1
      exit
    end
  elsif a[i] == 3
    if target1.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target1[0][1]]
      target1.shift
      tate -= 1
    else
      puts -1
      exit
    end
  end
end
puts ans.length
ans.each do |v|
  puts "#{v[0]} #{v[1]}"
end

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
ans = []
target1 = []
tate = n-1
(n-1).downto(0) do |i|
  if a[i] == 1
    ans << [tate+1,i+1]
    target1 << [tate+1,i+1]
    tate -= 1
  elsif a[i] == 2
    if target1.empty?.!
      ans << [target1[0][0],i+1]
      target1.shift
    else
      puts -1
      exit
    end
  elsif a[i] == 3
    if target1.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target1[0][1]]
      target1.shift
    else
      puts -1
      exit
    end
  end
end
puts ans.length
ans.each do |v|
  puts "#{v[0]} #{v[1]}"
end

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
ans = []
target1 = []
target2 = []
tate = n-1
(n-1).downto(0) do |i|
  if a[i] == 1
    ans << [tate+1,i+1]
    target1 << [tate+1,i+1]
    tate -= 1
  elsif a[i] == 2
    if target1.empty?.!
      ans << [target1[0][0],i+1]
      target2 << [target1[0][0],i+1]
      target1.shift
    else
      puts -1
      exit
    end
  elsif a[i] == 3
    if target2.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target2[0][1]]
      target2.shift
      tate -= 1
    elsif target1.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target1[0][1]]
      target1.shift
      target2 << [tate+1,i+1]
      tate -= 1
    else
      puts -1
      exit
    end
  end
end
puts ans.length
ans.each do |v|
  puts "#{v[0]} #{v[1]}"
end


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You want to distribute these $$$n$$$ integers into two groups $$$s_1$$$ and $$$s_2$$$ (groups can be empty) so that the following conditions are satisfied:  For each $$$i$$$ $$$(1 \leq i \leq n)$$$, $$$a_i$$$ goes into exactly one group. The value $$$|sum(s_1)| - |sum(s_2)|$$$ is the maximum possible among all such ways to distribute the integers.Here $$$sum(s_1)$$$ denotes the sum of the numbers in the group $$$s_1$$$, and $$$sum(s_2)$$$ denotes the sum of the numbers in the group $$$s_2$$$.Determine the maximum possible value of $$$|sum(s_1)| - |sum(s_2)|$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 2 \cdot 10^4)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2 \ldots a_n$$$ $$$(-10^9 \leq a_i \leq 10^9)$$$  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, output a single integer  — the maximum possible value of $$$|sum(s_1)| - |sum(s_2)|$$$.

gets.to_i.times do
    n=gets
    arr=gets.chomp.split.map(&:to_i)
    s1=arr.select{|x| x>0}.sum
    s2=-1*arr.select{|x| x<0}.sum
    puts [s1,s2].max-[s1,s2].min
end