There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X" or "O". Then the player chooses two positive integers a and b (a·b = 12), after that he makes a table of size a × b from the cards he put on the table as follows: the first b cards form the first row of the table, the second b cards form the second row of the table and so on, the last b cards form the last (number a) row of the table. The player wins if some column of the table contain characters "X" on all cards. Otherwise, the player loses.Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers a and b to choose. Help her win the game: print to her all the possible ways of numbers a, b that she can choose and win.

The first line of the input contains integer t (1 ≤ t ≤ 100). This value shows the number of sets of test data in the input. Next follows the description of each of the t tests on a separate line. The description of each test is a string consisting of 12 characters, each character is either "X", or "O". The i-th character of the string shows the character that is written on the i-th card from the start.

For each test, print the answer to the test on a single line. The first number in the line must represent the number of distinct ways to choose the pair a, b. Next, print on this line the pairs in the format axb. Print the pairs in the order of increasing first parameter (a). Separate the pairs in the line by whitespaces.

4
OXXXOXOOXOOX
OXOXOXOXOXOX
XXXXXXXXXXXX
OOOOOOOOOOOO

#!/usr/bin/ruby
gets.to_i.times{
	s=gets.chomp.split('')
	n=s.size
	h={}
	n.times{|i|h[i]=1 if s[i]=='X'}
	r=(1..n).select{|i|n%i==0 && (n/i).times.any?{|j|
		i.times.all?{|k|h[k*(n/i)+j]}
	}}.map{|e|'%dx%d'%[e,n/e]}
	puts r.size.to_s+' '+r*' '
}

t = gets.to_i

def check(row,s)
    arr = s.split('').each_slice(row).to_a.transpose

    arr.each_with_index do |r,ri|
         bool = true
         r.each_with_index do |rri,rj|
            if r[rj]=='O'
                bool = false
            end
        end

        if bool
        return true

        end
    end
    return false
end

t.times do |i|
    s = gets.chomp
    fact = [12,6,4,3,2,1]
    ans = []
    fact.each_with_index do |f,i|
        if check(f,s)
            a = (s.length/f).to_s+'x'+f.to_s
            ans << a
        end
    end
    puts ans.length.to_s+' '+ans.join(' ')
end

def run
  n = $stdin.gets.to_i
  $stdin.readlines.each do |line|
    chars = line.chomp.split(//)
    len = chars.length
    ans = []
    1.upto(len) do |i|
      f = [true] * (len / i)
      next if len % i != 0
      len.times do |j|
        f[j % (len / i)] = false if chars[j] == 'O'
      end
      ans << "#{i}x#{chars.length / i}" if f.find_index(true)
    end
    puts "#{ans.length} #{ans.join(" ")}"
  end
end

run if $0 == __FILE__

gets
while s = gets
  r = []
  for a in 1..12
    if 12 % a == 0
      b = 12 / a
      ok = [ true ] * b
      s.chars.each_with_index do |c, i|
        ok[i % b] = false if c == 'O'
      end
      if ok.find_index(true)
        r << "#{a}x#{b}"
      end
    end
  end
  puts "#{r.size} #{r.join(' ')}"
end

tests = gets.to_i
tests.times do
  s = gets
  result = []
  for a in 1..12
    if 12 % a == 0
      b = 12 / a
      ok = [ true ] * b
      s.split(//).each_with_index do |c, i|
        ok[i % b] = false if c == 'O'
      end
      if ok.find_index(true)
        result << "#{a}x#{b}"
      end
    end
  end
  puts "#{result.size} #{result.join(' ')}"
end

class ProblemA

  def initialize
    @dats = STDIN.read.split("\n")
    @num_of_dat = @dats[0]
    @final_str = ""
  end

  def solve(line)
    out_line = ""
    num_of_ways = 0
    return if line.length != 12
    [1,2,3,4,6,12].each do |a|
      b = 12/a
      has_way = false
      str = ""
      (0..(b-1)).each do |col_idx|
        is_x = true
        (0..(a-1)).each do |row_idx|
          if line[col_idx+(row_idx)*b] != "X"
            is_x = false
          end
        end

        if is_x
          has_way = true
          num_of_ways += 1
          break
        end
      end
      out_line += " #{a}x#{b}" if has_way
    end
    @final_str += "#{num_of_ways} #{out_line}\n"
  end

  def solve_all
    (1..@num_of_dat.to_i).each do |i|
      solve(@dats[i])
    end
    puts @final_str
  end
end

solver = ProblemA.new
solver.solve_all

a=gets.chomp.to_i
ans= ["1x12 ", "2x6 ", "3x4 ", "4x3 ", "6x2 "]

def chk (a,b)
x=0
y=(12/b)
temp=[]
0.upto(y-1) do |i|
temp=[]
0.upto(b-1) do|j|
temp<<a[i+j*y]
end
if temp.count("X")==b
x=1
end
break if x==1
end
if x==1
return 1
else
return 0
end
end

a.times do
temp=gets.chomp
d=temp.count("X")

if d==0
puts "0"

elsif d==1
puts "1 1x12"

elsif d==12
puts "6 1x12 2x6 3x4 4x3 6x2 12x1"

elsif d==2
p=1
p+=chk(temp,2)
if p==1
puts "1 1x12"
else
puts "2 1x12 2x6"
end

elsif d==3
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
printf "#{ansa.length} "
puts"#{ansa.join}"

elsif d>=4 && d<6
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
p=chk(temp,4)
if p==1
ansa<<ans[3]
end
printf "#{ansa.length} "
puts"#{ansa.join}"

elsif d>=6 && d<12
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
p=chk(temp,4)
if p==1
ansa<<ans[3]
end
p=chk(temp,6)
if p==1
ansa<<ans[4]
end
printf "#{ansa.length} "
puts"#{ansa.join}"
end
end

n = gets.to_i
n.times do
	s = ?0 + gets
	ans = []
	1.upto(12) do |i|
		if 12 % i == 0 ;
			flag = false
			1.upto(12/i) do |j|
				tflag = true
				1.upto(i) do |k|
					if s[(k-1)*(12/i)+j] == ?O ;
						tflag = false;
					end
				end
				flag = true if tflag == true
			end
			ans << i if flag == true
		end
	end
	print ans.size
	ans.each do |x|
		print ' ', x, ?x, 12/x
	end
	print ?\n
end

(1..gets.to_i).each {
  s = gets.chomp.chars
  a = [1, 2, 3, 4, 6, 12].select { |v| u = 12/v; t = s.each_slice(u); (0...u).any? { |i| t.all? { |r| r[i] == 'X' } } }
  out = a.size.to_s
  out += ' ' + a.map { |v| "#{v}x#{12/v}" } * ' ' unless a.empty?
  puts out
}

a=gets.chomp.to_i
ans= ["1x12 ", "2x6 ", "3x4 ", "4x3 ", "6x2 "]

def chk (a,b)
x=0
y=(12/b)
temp=[]
0.upto(y-1) do |i|
temp=[]
0.upto(b-1) do|j|
temp<<a[i+j*y]
end
if temp.count("X")==b
x=1
end
break if x==1
end
if x==1
return 1
else
return 0
end
end

a.times do
temp=gets.chomp
d=temp.count("X")

if d==0
puts "0"

elsif d==1
puts "1 1x12"

elsif d==12
puts "6 1x12 2x6 3x4 4x3 6x2 12x1"

elsif d==2
p=1
p+=chk(temp,2)
if p==1
puts "1 1x12 2x6"
else
puts "1 1x12 2x6"
end

elsif d==3
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
printf "#{ansa.length} "
puts"#{ansa.join}"

elsif d>=4 && d<6
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
p=chk(temp,4)
if p==1
ansa<<ans[3]
end
printf "#{ansa.length} "
puts"#{ansa.join}"

elsif d>=6 && d<12
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
p=chk(temp,4)
if p==1
ansa<<ans[3]
end
p=chk(temp,6)
if p==1
ansa<<ans[4]
end
printf "#{ansa.length} "
puts"#{ansa.join}"
end
end

a=gets.chomp.to_i
ans= ["1x12 ", "2x6 ", "3x4 ", "4x3 ", "6x2 "]

def chk (a,b)
x=0
y=(12/b)
temp=[]
0.upto(y-1) do |i|
temp=[]
0.upto(b-1) do|j|
temp<<a[i+j*y]
end
if temp.count("X")==b
x=1
end
break if x==1
end
if x==1
return 1
else
return 0
end
end

a.times do
temp=gets.chomp
d=temp.count("X")

if d==0
puts "0"

elsif d==1
puts "1 1x12"

elsif d==12
puts "6 1x12 2x6 3x4 4x3 6x2 12x1"

elsif d==2
p=1
p+=chk(temp,2)
if p==1
puts "1 1x12 2x6"
else
puts "1 1x12"
end

elsif d==3
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
printf "#{ansa.length} "
puts"#{ansa.join}"

elsif d>=4 && d<6
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
p=chk(temp,4)
if p==1
ansa<<ans[3]
end
printf "#{ansa.length} "
puts"#{ansa.join}"

elsif d>=6 && d<12
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
p=chk(temp,4)
if p==1
ansa<<ans[3]
end
p=chk(temp,6)
if p==1
ansa<<ans[4]
end
printf "#{ansa.length} "
puts"#{ansa.join}"
end
end

a=gets.chomp.to_i
ans= ["1x12 ", "2x6 ", "3x4 ", "4x3 ", "6x2 "]

def chk (a,b)
x=0
y=(12/b)
temp=[]
0.upto(y-1) do |i|
temp=[]
0.upto(b-1) do|j|
temp<<a[i+j*y]
end
if temp.count("X")==b
x=1
end
break if x==1
end
if x==1
return 1
else
return 0
end
end

a.times do
temp=gets.chomp
d=temp.count("X")

if d==0
puts "0"

elsif d==1
puts "1 1x12"

elsif d==12
puts "6 1x12 2x6 3x4 4x3 6x2 12x1"

elsif d==2
p=1
p+=chk(temp,2)
if p==1
puts "1 1x12"
else
puts "1 1x12 2x6"
end

elsif d==3
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
printf "#{ansa.length} "
puts"#{ansa.join}"

elsif d>=4 && d<6
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
p=chk(temp,4)
if p==1
ansa<<ans[3]
end
printf "#{ansa.length} "
puts"#{ansa.join}"

elsif d>=6 && d<12
ansa=[]
ansa<<ans[0]
p=1
p=chk(temp,2)
if p==1
ansa<<ans[1]
end
p=chk(temp,3)
if p==1
ansa<<ans[2]
end
p=chk(temp,4)
if p==1
ansa<<ans[3]
end
p=chk(temp,6)
if p==1
ansa<<ans[4]
end
printf "#{ansa.length} "
puts"#{ansa.join}"
end
end


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $$$a$$$ to make it a good array. Recall that the prefix of the array $$$a=[a_1, a_2, \dots, a_n]$$$ is a subarray consisting several first elements: the prefix of the array $$$a$$$ of length $$$k$$$ is the array $$$[a_1, a_2, \dots, a_k]$$$ ($$$0 \le k \le n$$$).The array $$$b$$$ of length $$$m$$$ is called good, if you can obtain a non-decreasing array $$$c$$$ ($$$c_1 \le c_2 \le \dots \le c_{m}$$$) from it, repeating the following operation $$$m$$$ times (initially, $$$c$$$ is empty):  select either the first or the last element of $$$b$$$, remove it from $$$b$$$, and append it to the end of the array $$$c$$$. For example, if we do $$$4$$$ operations: take $$$b_1$$$, then $$$b_{m}$$$, then $$$b_{m-1}$$$ and at last $$$b_2$$$, then $$$b$$$ becomes $$$[b_3, b_4, \dots, b_{m-3}]$$$ and $$$c =[b_1, b_{m}, b_{m-1}, b_2]$$$.Consider the following example: $$$b = [1, 2, 3, 4, 4, 2, 1]$$$. This array is good because we can obtain non-decreasing array $$$c$$$ from it by the following sequence of operations:  take the first element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2, 1]$$$, $$$c = [1]$$$;  take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2]$$$, $$$c = [1, 1]$$$;  take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4]$$$, $$$c = [1, 1, 2]$$$;  take the first element of $$$b$$$, so $$$b = [3, 4, 4]$$$, $$$c = [1, 1, 2, 2]$$$;  take the first element of $$$b$$$, so $$$b = [4, 4]$$$, $$$c = [1, 1, 2, 2, 3]$$$;  take the last element of $$$b$$$, so $$$b = [4]$$$, $$$c = [1, 1, 2, 2, 3, 4]$$$;  take the only element of $$$b$$$, so $$$b = []$$$, $$$c = [1, 1, 2, 2, 3, 4, 4]$$$ — $$$c$$$ is non-decreasing. Note that the array consisting of one element is good.Print the length of the shortest prefix of $$$a$$$ to delete (erase), to make $$$a$$$ to be a good array. Note that the required length can be $$$0$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: the length of the shortest prefix of elements you need to erase from $$$a$$$ to make it a good array.

NoteIn the first test case of the example, the array $$$a$$$ is already good, so we don't need to erase any prefix.In the second test case of the example, the initial array $$$a$$$ is not good. Let's erase first $$$4$$$ elements of $$$a$$$, the result is $$$[4, 5, 2]$$$. The resulting array is good. You can prove that if you erase fewer number of first elements, the result will not be good.

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).chunk_while { _1 == _2 }.to_a
	pos =
		(1...a.size - 1).reverse_each.find do |i|
			a[i - 1][0] > a[i][0] && a[i][0] < a[i + 1][0]
		end || 0
	puts (0...pos).sum { a[_1].size }
end

tc = gets.chomp.to_i
while tc > 0
  n = gets.chomp.to_i
  a = gets.split.collect{|i| i.to_i}
  i = n - 1
  while i >= 1 && a[i - 1] >= a[i]
    i -= 1
  end
  while i >= 1 && a[i - 1] <= a[i]
    i -= 1
  end
  puts i
  tc -= 1
end

t = gets.chomp.to_i
t.times do
    ln = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i)
    i = ln - 1
    while i >= 1 && a[i-1] >= a[i]
             i -= 1
    end
    while i >= 1 && a[i-1] <= a[i]
        i -= 1
    end
    puts i
end

tc = gets.to_i

tc.times do
    n = gets.to_i
    arr = gets.split().map{|i| i.to_i}
    ans = 0
    crr = Array.new(n) {0}
    maxi = arr[n-1]
    ((n-2).step(0,-1)).each do |i|
        maxi  = [maxi,arr[i+1]].max
        crr[i] = maxi
    end
    (1...n-1).each do |i|
        if(arr[i] < arr[i-1] && arr[i] < crr[i])
            ans = i
        end
    end
    puts(ans)
end

gets.to_i.times do
    n = gets.to_i
    a = gets.split.map(&:to_i)
    res = n - 1
    res -= 1 while res > 0 && a[res - 1] >= a[res]
    res -= 1 while res > 0 && a[res - 1] <= a[res]
    puts res
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  rm = n - 1
  state = :inc
  (n - 2).downto(0) do |i|
    if a[i] < a[i + 1] then state = :dec end
    break if state == :dec and a[i] > a[i + 1]
    rm = i
  end
  puts rm
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	puts (1...n - 1).reverse_each.find { |i|
			a[i - 1] > a[i] && a[i] < a[i + 1]
	     } || 0
end

t = gets.chomp.to_i
t.times do
    ln = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i)
    i = ln - 1
    while i >= 0 && a[i-1] >= a[i]
             i -= 1
    end
    while i >= 0 && a[i-1] < a[i]
        i -= 1
    end
    puts i
end

t = gets.chomp.to_i
t.times do
    ln = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i)
    i = ln - 1
    while i >= 0 && a[i-1] >= a[i]
             i -= 1
    end
    while i >= 0 && a[i-1] <= a[i]
        i -= 1
    end
    puts i
end

t = gets.chomp.to_i
t.times do
    ln = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i)
    i = ln - 1
    while i >= 0 && a[i-1] > a[i]
             i -= 1
    end
    while i >= 0 && a[i-1] < a[i]
        i -= 1
    end
    puts i
end

tc = gets.to_i

tc.times do
    n = gets.to_i
    arr = gets.split().map{|i| i.to_i}

    brr = Array.new(n) {0}
    crr = Array.new(n) {0}

    maxi = arr[0]
    (1...n).each do |i|
        maxi = [maxi,arr[i-1]].max
        brr[i] = maxi
    end
    # print(brr)
    maxi = arr[n-1]
    ((n-2).step(0,-1)).each do |i|
        maxi  = [maxi,arr[i+1]].max
        crr[i] = maxi
    end
    # print(crr)
    ans = 0
    (1...n-1).each do |i|
        if(arr[i] < brr[i]  && arr[i] < crr[i])
            ans = i
        end
    end
    puts(ans)
end

tc = gets.to_i

tc.times do
    n = gets.to_i
    arr = gets.split().map{|i| i.to_i}
    # print(arr)
    brr = Array.new(n) {0}
    crr = Array.new(n) {0}

    maxi = arr[0]
    (1...n).each do |i|
        maxi = [maxi,arr[i-1]].max
        brr[i] = maxi
    end
    # print(brr)
    maxi = arr[n-1]
    ((n-2).step(0,-1)).each do |i|
        maxi  = [maxi,arr[i+1]].max
        crr[i] = maxi
    end
    # print(crr)
    ans = 0
    (1...n-1).each do |i|
        if(arr[i] < brr[i]  && arr[i] < crr[i])
            if(arr[i] != arr[i-1])
                ans = i
            end
        end
    end
    puts(ans)
end

tc = gets.to_i

tc.times do
    n = gets.to_i
    arr = gets.split().map{|i| i.to_i}
    ans = 0
    (1...n-1).each do |i|
        if(arr[i] < arr[i-1] && arr[i] < arr[i+1])
            ans = i
        end
    end
    puts(ans)
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  rm = n - 2
  state = :inc
  (n - 2).downto(0) do |i|
    if a[i] < a[i + 1] then state = :dec end
    break if state == :dec and a[i] > a[i + 1]
    rm = i
  end
  puts rm
end


You have array of $$$n$$$ numbers $$$a_{1}, a_{2}, \ldots, a_{n}$$$. Rearrange these numbers to satisfy $$$|a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|$$$, where $$$|x|$$$ denotes absolute value of $$$x$$$. It's always possible to find such rearrangement.Note that all numbers in $$$a$$$ are not necessarily different. In other words, some numbers of $$$a$$$ may be same.You have to answer independent $$$t$$$ test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$3 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).

For each test case, print the rearranged version of array $$$a$$$ which satisfies given condition. If there are multiple valid rearrangements, print any of them.

NoteIn the first test case, after given rearrangement, $$$|a_{1} - a_{2}| = 0 \le |a_{2} - a_{3}| = 1 \le |a_{3} - a_{4}| = 2 \le |a_{4} - a_{5}| = 2 \le |a_{5} - a_{6}| = 10$$$. There are other possible answers like "5 4 5 6 -2 8".In the second test case, after given rearrangement, $$$|a_{1} - a_{2}| = 1 \le |a_{2} - a_{3}| = 2 \le |a_{3} - a_{4}| = 4$$$. There are other possible answers like "2 4 8 1".

# coding: utf-8

# |a1 - a2| <= |a2 - a3| <= |a3 - a4| ....
# 를 만족시키도록 a를 정렬
# 꽤 재밌는 유형의 문제이다. 이렇게 숫자 배열을 타고 순회하는걸 oscillation이라 한다는군.
# naive하게 구성한 알고리즘은 다음과 같음
# 1. 삽입 정렬 구조를 가짐
# 2. 빈 배열에 a1 삽입
# 3. 빈 배열에 a2 삽입
# (여기까진 |a1 - a2| = |a2 - a1|이므로 큰 지장은 없음)
# 4. 빈 배열에 a3 을 넣기 위한 자리를 선택함( 전체 순회가 필요함 O(n))
# 5. 이후 a3부터 aN까지 모든 절차를 반복해야하므로 O(n^2)
# 이렇게 잡았지만 부분적으로는 해답일 수 있으나 아무래도 오답이 자꾸 나오네.
# 결국은 몇번 고민해보다가 찾은 해가 이 접근법이다.

# 일단 숫자를 모두 정렬한다. 1 2 9 5 8 8을 감소가 없는 순서대로 정렬하면,
# 1 2 5 8 8 9 이다. 이 숫자는 재밌는 성질을 갖고 있는데, 한 숫자를 기준으로
# 오른쪽은 0혹은 1이상만큼 크며 왼쪽은 0혹은 1이상만큼 작다.
# 그래서 자신에게 k 거리만큼 먼쪽일 수록 자신과의 차이가 매우 커질거란 기대를 할 수 있다.
# 자신에게 0에 가까운 거리일수록 자신과의 차이는 매우 작아진다.
# 그래서 중앙에서부터 왼쪽 절반의 제일 후미부터, 오른쪽 절반의 제일 선두부터 숫자를
# 추출하면 거리가 가까운 순서부터 먼 순서대로 뽑을 수 있다.

# 처음에 평균을 이용한 접근을 한건 평균이 중앙에 올 경우에는 성공할 수 있는 방법이지만,
# 평균값이 중앙에 있지 못한 경우에는 잘못된 동작을 할 수 있다.
# 결국 평균이 아니라 '중간값'을 찾아야하는 문제. 정렬은 이러한 방법으로 순회하기 위해
# 안정적인 전제를 제공하는 것이다.
t = gets.to_i
t.times {
    n = gets.to_i
    a = gets.split.map(&:to_i)
    a.sort!
    mid = n/2
    la, ra = a[0...mid], a[mid...n]
    b = []
    while !la.empty? || !ra.empty?
        b << ra.shift unless ra.empty?
        b << la.pop unless la.empty?
    end

    #p la
    #p ra

    puts b.join(' ')
}

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  a.sort!
  b = Array.new(n, nil)
  pos = (n - 1) / 2
  n.times do |i|
    b[i] = a[pos]
    if i % 2 == 0
      pos += i + 1
    else
      pos -= i + 1
    end
  end
  puts b.join(" ")
end

# coding: utf-8

# |a1 - a2| <= |a2 - a3| <= |a3 - a4| ....
# 를 만족시키도록 a를 정렬

t = gets.to_i
t.times {
    n = gets.to_i
    a = gets.split.map(&:to_i)
    a.sort!
    mid = n/2
    la, ra = a[0...mid], a[mid...n]
    b = []
    while !la.empty? && !ra.empty?
        b << ra.shift unless ra.empty?
        b << la.pop unless la.empty?
    end

    puts b.join(' ')
}

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  a.sort!
  b = Array.new(n, nil)
  pos = (n - 1) / 2
  n.times do |i|
    puts pos
    b[i] = a[pos]
    if i % 2 == 0
      pos += i + 1
    else
      pos -= i + 1
    end
  end
  puts b.join(" ")
end


There are $$$n$$$ people participating in some contest, they start participating in $$$x$$$ minutes intervals. That means the first participant starts at time $$$0$$$, the second participant starts at time $$$x$$$, the third — at time $$$2 \cdot x$$$, and so on.Duration of contest is $$$t$$$ minutes for each participant, so the first participant finishes the contest at time $$$t$$$, the second — at time $$$t + x$$$, and so on. When a participant finishes the contest, their dissatisfaction equals to the number of participants that started the contest (or starting it now), but haven't yet finished it.Determine the sum of dissatisfaction of all participants.

The first line contains a single integer $$$k$$$ ($$$1 \le k \le 1000$$$) — the number of test cases. Each of the next $$$k$$$ lines contains three integers $$$n$$$, $$$x$$$, $$$t$$$ ($$$1 \le n, x, t \le 2 \cdot 10^9$$$) — the number of participants, the start interval and the contest duration.

Print $$$k$$$ lines, in the $$$i$$$-th line print the total dissatisfaction of participants in the $$$i$$$-th test case.

NoteIn the first example the first participant starts at $$$0$$$ and finishes at time $$$5$$$. By that time the second and the third participants start, so the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$2$$$ and finishes at time $$$7$$$. By that time the third the fourth participants start, so the dissatisfaction of the second participant is $$$2$$$. The third participant starts at $$$4$$$ and finishes at $$$9$$$. By that time the fourth participant starts, so the dissatisfaction of the third participant is $$$1$$$.The fourth participant starts at $$$6$$$ and finishes at $$$11$$$. By time $$$11$$$ everyone finishes the contest, so the dissatisfaction of the fourth participant is $$$0$$$.In the second example the first participant starts at $$$0$$$ and finishes at time $$$2$$$. By that time the second participants starts, and the third starts at exactly time $$$2$$$. So the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$1$$$ and finishes at time $$$3$$$. At that time the third participant is solving the contest.

k = gets.to_i

while (k > 0)
  n, x, t = gets.split(' ').map(&:to_i)

  forFirst = [t / x, n - 1].min;

  puts(forFirst * [n - forFirst, 0].max + forFirst * (forFirst - 1) / 2)

  k -= 1
end

gets.to_i.times do
  n,x,t=gets.split.map(&:to_i)
  if t>=x*(n-1)
    puts (n-1)*n/2
  else
    cc=t/x
    puts cc*(cc+1)/2+(n-cc-1)*cc
  end
end


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.You are allowed to perform this operation any number of times (possibly, zero):   choose an index $$$i$$$ ($$$2 \le i \le n$$$), and change $$$a_i$$$ to $$$a_i - a_{i-1}$$$. Is it possible to make $$$a_i=0$$$ for all $$$2\le i\le n$$$?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 100$$$)  — the number of test cases. The description of the test cases follows. The first line contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the length of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$).

For each test case, print "YES" (without quotes), if it is possible to change $$$a_i$$$ to $$$0$$$ for all $$$2 \le i \le n$$$, and "NO" (without quotes) otherwise. You can print letters in any case (upper or lower).

NoteIn the first test case, the initial array is $$$[5,10]$$$. You can perform $$$2$$$ operations to reach the goal:  Choose $$$i=2$$$, and the array becomes $$$[5,5]$$$.  Choose $$$i=2$$$, and the array becomes $$$[5,0]$$$. In the second test case, the initial array is $$$[1,2,3]$$$. You can perform $$$4$$$ operations to reach the goal:   Choose $$$i=3$$$, and the array becomes $$$[1,2,1]$$$.  Choose $$$i=2$$$, and the array becomes $$$[1,1,1]$$$.  Choose $$$i=3$$$, and the array becomes $$$[1,1,0]$$$.  Choose $$$i=2$$$, and the array becomes $$$[1,0,0]$$$. In the third test case, you can choose indices in the order $$$4$$$, $$$3$$$, $$$2$$$.

def solve(arr)
  a0 = arr[0]
  (1...arr.length).each do |i|
    if arr[i] % a0 != 0
      puts "NO"
      return
    end
  end
  puts "YES"
end

n = gets.chomp.to_i
n.times do
  gets
  solve(gets.chomp.split(' ').map(&:to_i))
end

def solve(arr)
  a0 = arr[0]
  (1...arr.length).each do |i|
    if arr[i] % a0 != 0
      puts "NO"
      break
    end
  end
  puts "YES"
end

n = gets.chomp.to_i
n.times do
  gets
  solve(gets.chomp.split(' ').map(&:to_i))
end


You are planning to buy an apartment in a $$$n$$$-floor building. The floors are numbered from $$$1$$$ to $$$n$$$ from the bottom to the top. At first for each floor you want to know the minimum total time to reach it from the first (the bottom) floor.Let:  $$$a_i$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$ be the time required to go from the $$$i$$$-th floor to the $$$(i+1)$$$-th one (and from the $$$(i+1)$$$-th to the $$$i$$$-th as well) using the stairs;  $$$b_i$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$ be the time required to go from the $$$i$$$-th floor to the $$$(i+1)$$$-th one (and from the $$$(i+1)$$$-th to the $$$i$$$-th as well) using the elevator, also there is a value $$$c$$$ — time overhead for elevator usage (you need to wait for it, the elevator doors are too slow!). In one move, you can go from the floor you are staying at $$$x$$$ to any floor $$$y$$$ ($$$x \ne y$$$) in two different ways:  If you are using the stairs, just sum up the corresponding values of $$$a_i$$$. Formally, it will take $$$\sum\limits_{i=min(x, y)}^{max(x, y) - 1} a_i$$$ time units.  If you are using the elevator, just sum up $$$c$$$ and the corresponding values of $$$b_i$$$. Formally, it will take $$$c + \sum\limits_{i=min(x, y)}^{max(x, y) - 1} b_i$$$ time units. You can perform as many moves as you want (possibly zero).So your task is for each $$$i$$$ to determine the minimum total time it takes to reach the $$$i$$$-th floor from the $$$1$$$-st (bottom) floor.

The first line of the input contains two integers $$$n$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5, 1 \le c \le 1000$$$) — the number of floors in the building and the time overhead for the elevator rides. The second line of the input contains $$$n - 1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the time required to go from the $$$i$$$-th floor to the $$$(i+1)$$$-th one (and from the $$$(i+1)$$$-th to the $$$i$$$-th as well) using the stairs. The third line of the input contains $$$n - 1$$$ integers $$$b_1, b_2, \dots, b_{n-1}$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the time required to go from the $$$i$$$-th floor to the $$$(i+1)$$$-th one (and from the $$$(i+1)$$$-th to the $$$i$$$-th as well) using the elevator.

Print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$, where $$$t_i$$$ is the minimum total time to reach the $$$i$$$-th floor from the first floor if you can perform as many moves as you want.

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end

def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end

def na(n=0,d=0) Array.new(n,d)end

def na2(n=0,m=0,d=0) Array.new(n){Array.new(m,d)}end

def na3(n=0,m=0,l=0,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def bit(n) n.to_s(2).split("").map(&:to_i) end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

t3 = []
(0..44).each{|d|t3<<3**d}

n,k = inp
a = inp
b = inp
dp = na2(n,2)
dp[0][0] = 0
dp[0][1] = 9999
(n-1).times do |i|
  dp[i+1][1] = [dp[i][0] + b[i] + k,dp[i][1] + b[i]].min
  dp[i+1][0] = [dp[i][0] + a[i], dp[i][1] + a[i]].min
end
ans = []
dp.each do |a|
  ans << [a[0],a[1]].min
end
puts ans.join(" ")


Let's call a permutation $$$p$$$ of length $$$n$$$ anti-Fibonacci if the condition $$$p_{i-2} + p_{i-1} \ne p_i$$$ holds for all $$$i$$$ ($$$3 \le i \le n$$$). Recall that the permutation is the array of length $$$n$$$ which contains each integer from $$$1$$$ to $$$n$$$ exactly once.Your task is for a given number $$$n$$$ print $$$n$$$ distinct anti-Fibonacci permutations of length $$$n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 48$$$) — the number of test cases.  The single line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$).

For each test case, print $$$n$$$ lines. Each line should contain an anti-Fibonacci permutation of length $$$n$$$. In each test case, you cannot print any permutation more than once. If there are multiple answers, print any of them. It can be shown that it is always possible to find $$$n$$$ different anti-Fibonacci permutations of size $$$n$$$ under the constraints of the problem.

n = gets.chomp.to_i
results = []

n.times do |_|
    size = gets.chomp.to_i
    data = (1..size).to_a
    result = []

    until result.size == size do
        temp = data.shuffle
        valid = temp.each_with_index.all?{|x, i| i < 2 ? true : temp[i - 2] + temp[i - 1] != x}
        if valid and !result.include?(temp)
            result.push(temp)
        end
    end
    results.push(result)
end

results.flatten(1).each{|x| puts x.join(' ')}


Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.

First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.

If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.

NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.

r, c = gets.split.map &:to_i

pasture = Array.new(){Array.new(c)}

r.times do
  pasture << gets.strip.split("")
end

def place_dogs(pasture, i, j)
  r = pasture.length
  c = pasture[0].length
  pasture[i - 1][j] = "D" if i - 1 >= 0 && pasture[i - 1][j] == "."
  pasture[i + 1][j] = "D" if i + 1 < r && pasture[i + 1][j] == "."
  pasture[i][j - 1] = "D" if j - 1 >= 0 && pasture[i][j - 1] == "."
  pasture[i][j + 1] = "D" if j + 1 < c && pasture[i][j + 1] == "."
end

def dead_sheep?(pasture)
  r = pasture.length
  c = pasture[0].length
  dead_sheep = false
  pasture.each_index do |i|
    pasture[i].each_index do |j|
      if pasture[i][j] == "W"
        up = pasture[i - 1][j] if i - 1 >= 0
        down = pasture[i + 1][j] if i + 1 < r
        right = pasture[i][j + 1] if j + 1 < c
        left = pasture[i][j - 1] if j - 1 >= 0
        if up == "S" || down == "S" || right == "S" || left == "S"
          dead_sheep = true
          break
        end
      end
    end
  end
  dead_sheep
end

if dead_sheep?(pasture)
  puts "No"
else
  pasture.each_index do |i|
    pasture[i].each_index do |j|
      if pasture[i][j] == "W"
        place_dogs(pasture, i, j)
      end
    end
  end
  pasture = pasture.map &:join
  puts "Yes", pasture.join("\n")
end

r,c = gets.split.map(&:to_i)
a = []

check = true
r.times do
  a << gets.chomp
end
r.times do |i|
  c.times do |j|
    if a[i][j] == "S"
      check = false if i > 0 && a[i-1][j] == "W"
      check = false if i < r-1 && a[i+1][j] == "W"
      check = false if j > 0 && a[i][j-1] == "W"
      check = false if j < c-1 && a[i][j+1] == "W"
    end
    a[i][j] = "D" if a[i][j] == "."
  end
end
if check
  puts "Yes"
  r.times do |i|
    puts a[i]
  end
else
  puts "No"
end

n, m = gets.split.map(&:to_i)
ar = Array.new(0)
res = false
n.times { ar << gets.chomp}
n.times do |i|
  ar[i] = ar[i].gsub('.', 'D')
  if ar[i].include?('WS') || ar[i].include?('SW')
    res = true
    break
  end
end
n.times do |i|
  m.times do |j|
    break if i == n-1
    curr = ar[i][j]
    bottom = ar[i+1][j] if ar[i+1]
    if [curr, bottom].sort == ['S','W']
      res = true
      break
    end
  end
end
puts res ? "NO" : "YES"
puts ar if !res

a, b= gets.chomp.split(" ").map { |e| e.to_i  }

arr = Array.new(a) { Array.new(b)  }

(0...a).to_a.each do |i|
	inp = gets.chomp.split("")
	(0...b).to_a.each do |j|
		arr[i][j] = inp[j]
		if arr[i][j] == '.'
			arr[i][j] = 'D'
		end
	end
end

(0...a).to_a.each do |i|
	(0...b).to_a.each do |j|
		if arr[i][j] == 'W' && (((j-1) >= 0 && arr[i][j-1] == 'S') || ((j+1)<b && arr[i][j+1] == 'S') || ((i-1)>=0 && arr[i-1][j] == 'S') || (i+1) < a && arr[i+1][j] == 'S')
			puts "No"
			exit
		end
	end
end
puts 'Yes'
arr.each do |el|
	puts el.join("")
end


Given an integer $$$n$$$, find the maximum value of integer $$$k$$$ such that the following condition holds:  $$$n$$$ & ($$$n-1$$$) & ($$$n-2$$$) & ($$$n-3$$$) & ... ($$$k$$$) = $$$0$$$  where & denotes the bitwise AND operation.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, output a single integer — the required integer $$$k$$$.

NoteIn the first testcase, the maximum value for which the continuous & operation gives 0 value, is 1.In the second testcase, the maximum value for which the continuous & operation gives 0 value, is 3. No value greater then 3, say for example 4, will give the & sum 0.   $$$5 \, \& \, 4 \neq 0$$$,  $$$5 \, \& \, 4 \, \& \, 3 = 0$$$. Hence, 3 is the answer.

gets.to_i.times{|c|
	n = gets.to_i
	puts ('1'*(n.to_s(2).size-1)).to_i(2)
}

gets.to_i.times {
  n = gets.to_i

  p = 1
  p *= 2 while p < n
  p /= 2 if p > n

  puts(p - 1)
}

gets.to_i.times do
    n = gets.to_i
    res = 0
    while n > 0
        n /= 2
        res += 1
    end
    puts (1 << (res - 1)) - 1
end

t = gets.chomp.to_i

def solve(n)
  cnt = 0
  while n > 0 do
    cnt += 1
    n /= 2
  end

  (1 << (cnt - 1)) - 1
end

t.times do
  n = gets.chomp.to_i
  puts solve(n)
end

t = gets.to_i
t.times do
  n = gets.to_i.to_s(2)
  l = 1 << (n.size - 1)
  puts l - 1
end

gets.to_i.times{|c|
	n = gets.to_i
	puts n-n.digits(2).count(1)
}


The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.The Berland capital's map is represented by an n × m rectangular table. Each cell of the table on the map represents some districts of the capital. The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map. Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.

The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 100) — the number of rows and columns in the table, correspondingly. Each of the next n lines contains m characters — the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".". It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements.

Print two integers — the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right.

n, m = gets.split.map &:to_i
mat = Array.new(n) { gets.strip }
dx = Hash.new(0)
dy = Hash.new(0)

mat.each_with_index do |row, i|
  row.chars.to_a.each_with_index do |char, j|
    if char == '*'
      dx[i] += 1
      dy[j] += 1
    end
  end
end

p dx.select { |k, v| v.odd? }.keys[0].to_i + 1
p dy.select { |k, v| v.odd? }.keys[0].to_i + 1

n,m = gets.chomp.split(/ /).map!{|x| x.to_i}
sa = []
rety = 0
retx = 0
xa = []
for i in 0..n-1
    sa << gets.chomp
    wk = sa[i].index("*")
    if wk != nil
        wk2 = sa[i].rindex("*")
        if wk == wk2
            rety = i+1
            retx = wk+1
        else
            xa = [wk+1, wk2+1]
        end
    end
end
xa.delete(retx)
puts rety.to_s + " " + xa[0].to_s

r,c=gets.split.map(&:to_i)
x,y=0,0
r.times{|i|gets;c.times{|j|x^=i and y^=j if $_[j]=='*'}}
puts "#{x+1} #{y+1}"

r, c = gets.split.map(&:to_i)
x, y = 0, 0
1.upto(r){|i|
    gets.chars.each_with_index{|c, j|
        if c == '*'
            x ^= i
            y ^= j + 1
        end
    }
}
puts "#{x} #{y}"

#!/usr/bin/ruby1.9

(n, m) = STDIN.readline.split.map {|s| s.to_i}

rs = []
cs = []
(1..n).each do |r|
	row = STDIN.readline.strip
	(1..row.length).each do |c|
		if row[c-1].chr == '*'
			rs.push(r)
			cs.push(c)
		end
	end
end

def get_odd_one_out(xs)
	xs = xs.sort
	if xs[0] == xs[1]
		return xs[2]
	end
	return xs[0]
end

r = get_odd_one_out(rs)
c = get_odd_one_out(cs)
puts '%d %d' % [r, c]

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

list = []
n.times do |j|
  gets.chomp.split("").each_with_index do |c, i|
    if c == '*'
      list << [j, i]
    end
  end
end

count_y = Hash.new(0)
count_x = Hash.new(0)

list.each do |y, x|
  count_y[y] += 1
  count_x[x] += 1
end

puts "#{count_y.key(1) + 1} #{count_x.key(1) + 1}"

n,m = gets.to_s.split(" ").map{|x| Integer x}
points = []
n.times do |i|
	a = gets.to_s.split("")
	a.each_index do |j|
		if a[j] == "*" then
			points.push [i,j]
		end
	end
end
p = []
3.times do |x|
	pnt = points.pop
	if (pnt[0] == points[0][0] or pnt[0] == points[1][0]) and (pnt[1] == points[0][1] or pnt[1] == points[1][1]) then
		p = pnt
		break
	end
	points.push pnt
	points.rotate!
end
#puts "#{p[0]} #{p[1]}"
newP = [0,0]
if p[0] == points[0][0] then
	p1 = points[0]
	p2 = points[1]
else
	p1 = points[1]
	p2 = points[0]
end
#puts "#{p1[0]} #{p1[1]}"
#puts "#{p2[0]} #{p2[1]}"
newP[1] = p[1] + p1[1] - p[1]
newP[0] = p[0] + p2[0] - p[0]

puts "#{newP[0]+1} #{newP[1]+1}"

a = gets.to_i.times.map{ gets.strip }
b = []
a.each_with_index do |s,i|
  s.split(//).each_with_index do |c,j|
    b << [i,j] if c == "*"
  end
end
hx = Hash.new(0)
hy = Hash.new(0)
b.each do |i,j|
  hx[i] += 1
  hy[j] += 1
end

puts [hx.key(1)+1,hy.key(1)+1] * " "

require "scanf"

input = ARGF.read.lines

crime_scenes = []
row = 0
input.drop(1).each do |row_data|
	crime_scenes += row_data
		.chars
		.each_with_index
		.select { |e,i| e == '*' }
		.map { |e,i| [row, i] }

	row += 1
end

res =
	if crime_scenes[0][0] == crime_scenes[1][0] # on row with second point
		if crime_scenes[0][1] == crime_scenes[2][1]
			[crime_scenes[2][0], crime_scenes[1][1]]
		else
			[crime_scenes[2][0], crime_scenes[0][1]]
		end
	else
		if crime_scenes[0][1] == crime_scenes[2][1] # on one column with third point
			[crime_scenes[0][0], crime_scenes[1][1]]
		else
			if crime_scenes[1][0] == crime_scenes[2][0]
				[crime_scenes[0][0], crime_scenes[2][1]]
			else
				[crime_scenes[1][0], crime_scenes[2][1]]
			end
		end
	end

puts [res.first + 1, res.last + 1].join ' '

h, w = gets.split.map(&:to_i)
m = Array.new(h)
x, y, xx, yy = 101, 102, -1, -2
h.times{ |i| m[i] = gets
	w.times{ |j|
		if m[i][j, 1] == "*" then
			xx = [xx, j].max
			x = [x, j].min
			yy = [yy, i].max
			y = [y, i].min
		end
	}
}
[x, xx].each{ |a|
	[y, yy].each{ |b|
		if m[b][a, 1] == "." then
			print b + 1, " ", a + 1, "\n"
		end
	}
}

n, m = gets.split.map &:to_i
a = []
n.times { a << gets.chomp.split('') }
(0...n).each { |i| (0...m).each { |j| puts "#{i + 1} #{j + 1}" if a[i].count('*') == 1 && a.transpose[j].count('*') == 1 } }

n,m=gets.split.map(&:to_i)
i=x=y=0
table=n.times.map{i+=1;x=i if gets.count(?*)==1;$_.each_char.to_a}
i=0
table.transpose.each{|l|i+=1;y=i if l.join.count(?*)==1}
puts "%d %d"%[x,y]

require 'scanf'

input = ARGF.read.lines

crime_scenes = []
row = 0
input.drop(1).each do |row_data|
	crime_scenes += row_data
		.chars
		.each_with_index
		.select { |e,i| e == '*' }
		.map { |e,i| [row, i] }

	row += 1
end

res =
	if crime_scenes[0][0] == crime_scenes[1][0] # on row
		if crime_scenes[0][1] == crime_scenes[2][1]
			[crime_scenes[2][0], crime_scenes[1][1]]
		else
			[crime_scenes[2][0], crime_scenes[0][1]]
		end
	else
		if crime_scenes[0][0] == crime_scenes[2][0]
			[crime_scenes[1][0], crime_scenes[0][1]]
		else
			[crime_scenes[0][0], crime_scenes[1][1]]
		end
	end

puts [res.first + 1, res.last + 1].join ' '

require 'scanf'

input = ARGF.read.lines

crime_scenes = []
row = 0
input.drop(1).each do |row_data|
	crime_scenes += row_data
		.chars
		.each_with_index
		.select { |e,i| e == '*' }
		.map { |e,i| [row, i] }

	row += 1
end

res =
	if crime_scenes[0][0] == crime_scenes[1][0] # on row with second point
		if crime_scenes[0][1] == crime_scenes[2][1]
			[crime_scenes[2][0], crime_scenes[1][1]]
		else
			[crime_scenes[2][0], crime_scenes[0][1]]
		end
	else
		if crime_scenes[0][1] == crime_scenes[2][1] # on one column with third point
			[crime_scenes[0][0], crime_scenes[1][1]]
		else
			[crime_scenes[1][0], crime_scenes[0][1]]
		end
	end

puts [res.first + 1, res.last + 1].join ' '

require "scanf"

input = ARGF.read.lines

crime_scenes = []
row = 0
input.drop(1).each do |row_data|
	crime_scenes += row_data
		.chars
		.each_with_index
		.select { |e,i| e == '*' }
		.map { |e,i| [row, i] }

	row += 1
end

res =
	if crime_scenes[0][0] == crime_scenes[1][0] # on row with second point
		if crime_scenes[0][1] == crime_scenes[2][1]
			[crime_scenes[2][0], crime_scenes[1][1]]
		else
			[crime_scenes[2][0], crime_scenes[0][1]]
		end
	else
		if crime_scenes[0][1] == crime_scenes[2][1] # on one column with third point
			[crime_scenes[0][0], crime_scenes[1][1]]
		else
			[crime_scenes[1][0], crime_scenes[0][1]]
		end
	end

puts [res.first + 1, res.last + 1].join ' '


Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.

The first line contains two integers n and m — the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b — the numbers of students tied by the i-th lace (1 ≤ a, b ≤ n, a ≠ b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.

Print the single number — the number of groups of students that will be kicked out from the club.

NoteIn the first sample Anna and Maria won't kick out any group of students — in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then — two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.

n,m=gets.chomp.split.map(&:to_i)
i,j,f,a,b,ar=0,0,0,[],[],Array.new(100,0)
m.times do |i|
	x,y=gets.chomp.split.map(&:to_i)
	a<<(x-1);b<<(y-1)
end
while i<105
	f,c=0,Array.new(100,0)
	m.times do |j|
		if ar[a[j]]==0 && ar[b[j]]==0
			c[a[j]]+=1
			c[b[j]]+=1
		end
	end
	n.times do |j|
		if c[j]==1
			f=1
			ar[j]=1
		end
	end
	break if f==0
	i+=1
end
puts i

class Kid
    attr_accessor :tied_to, :number
    def initialize (num)
        @tied_to = []
        @number = num
    end
end

result = -1
input = STDIN.gets.strip
laces = []
input.split.last.to_i.times do |i|
    laces.push STDIN.gets.strip.split.collect {|i| i.to_i}
end

while true
    kids = Array.new(input.split.first.to_i) {|i| Kid.new(i+1)}
    result += 1
    laces.each do |i|
        kids[i[0]-1].tied_to.push i[1] unless kids[i[0]-1].tied_to.include? i[1]
        kids[i[1]-1].tied_to.push i[0] unless kids[i[1]-1].tied_to.include? i[0]
    end
    remove = []
    kids.each do |i|
        remove.push(i.number) if i.tied_to.size == 1
    end
    break if remove.size == 0
    remove.each do |i|
        laces.delete_if {|l| l.include? i}
    end
end
p result

include Math

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

m.times{
	a,b=gets.split.map(&:to_i)

	if graph.has_key?(a)
		graph[a] << b
	else
		graph[a] = [b]
	end

	if graph.has_key?(b)
		graph[b] << a
	else
		graph[b] = [a]
	end
}

ans=0
loop{
	delete_them = []

	graph.keys.each{|key|
		if graph[key].size==1
			delete_them << key
		end
	}

	#deleting vals in arrays
	graph.keys.each{|key|
		delete_them.each{|el|	graph[key].delete(el)}
	}

	# deleting keys
	delete_them.each{|el| graph.delete(el)}

	ans+=1 if delete_them.size!=0
	break if delete_them.size==0
}

puts ans

n,m=gets.split.map(&:to_i);g=Hash.new []
m.times{a,b=gets.split.map(&:to_i);g[a]+=[b];g[b]+=[a]}
s=0;loop{d=[];g.keys.each{|k| d << k if g[k].size==1};g.keys.each{|k|d.each{|l|g[k].delete(l)}};d.each{|l|g.delete(l)};s+=1 if d.size!=0;break if d.size==0};p s

n,m=gets.split.map(&:to_i);g=Hash.new [];m.times{a,b=gets.split.map(&:to_i);g[a]+=[b];g[b]+=[a]};s=0;loop{d=[];g.keys.each{|k|d<<k if g[k].size==1};g.keys.each{|k|d.each{|l|g[k].delete(l)}};d.each{|l|g.delete(l)};d.empty? ? break: s+=1};p s

n,m=gets.split.map(&:to_i);g=Hash.new [];m.times{a,b=gets.split.map(&:to_i);g[a]+=[b];g[b]+=[a]};s=0;loop{d=[];g.keys.each{|k|d << k if g[k].size==1};g.keys.each{|k|d.each{|l|g[k].delete(l)}};d.each{|l|g.delete(l)};s+=1 if !d.empty?;break if d.empty?};p s

input = gets.chomp.split
n = Integer(input[0])
m = Integer(input[1])
lace_connect = []
for i in 0...m
    lace_connect[i] = gets.chomp.split.map{|j| Integer(j)}
end
require 'pp'
connection = []
for i in 0...n
    connection[i] = Array.new(n)
end
for j in 0...m
    connection[lace_connect[j][1] - 1][lace_connect[j][0] - 1] = true
    connection[lace_connect[j][0] - 1][lace_connect[j][1] - 1] = true
end

groups = []
count = 0
kick_out = 0
for h in 0...n
    for i in 0...n
        for j in 0...n
            if connection[i][j]
                count += 1
            end
        end
        if count == 1
            groups.push(i)
        end
        count = 0
    end
    if groups.length != 0
        for i in groups
            for j in 0...n
                if connection[i][j]
                    connection[i][j] = false
                    connection[j][i] = false
                end
            end
        end
        kick_out += 1
        groups = []
    else
        break
    end
end
puts kick_out

require 'Set'

class Vertex
	attr_accessor :list,:name
	def initialize(name)
		self.name = name
		self.list = Set.new
	end

	def add_element(v)
		self.list << v
	end

	def remove_element(v)
		self.list.delete(v)
	end
end

class Graph
	attr_accessor :vertices
	def initialize
		self.vertices = Set.new
	end

	def add(v)
		self.vertices << v
	end

	def get(name)
		self.vertices.detect{|v| v.name == name}
	end
end

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

g = Graph.new
n.times do |i|
	g.add(Vertex.new(i+1))
end

m.times do
	a,b = gets.split(" ").map(&:to_i)
	x,y = g.get(a),g.get(b)
	x.add_element(y)
	y.add_element(x)
end
count = 0
while true
	removed = false
	removal = []
	g.vertices.each do |a|
		if a.list.count == 1
			removal << [a,a.list.first]
			removed = true
		end
	end
	if removed
		removal.each do |(a,el)|
			a.remove_element(el)
			el.remove_element(a)
		end
		count += 1
	else
		break
	end
end

puts count

require 'Set'

class Vertex
	attr_accessor :list,:name
	def initialize(name)
		self.name = name
		self.list = Set.new
	end

	def add_element(v)
		self.list << v
	end

	def remove_element(v)
		self.list.delete(v)
	end
end

class Graph
	attr_accessor :vertices
	def initialize
		self.vertices = Set.new
	end

	def add(v)
		self.vertices << v
	end

	def get(name)
		self.vertices.detect{|v| v.name == name}
	end
end

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

g = Graph.new
n.times do |i|
	g.add(Vertex.new(i+1))
end

m.times do
	a,b = gets.split(" ").map(&:to_i)
	x,y = g.get(a),g.get(b)
	x.add_element(y)
	y.add_element(x)
end
count = 0
while true
	removed = false
	dont_check = Hash.new(false)

	g.vertices.each do |a|
		next if dont_check[a.name]
		if a.list.count == 1
			el = a.list.first
			a.remove_element(el)
			el.remove_element(a)
			dont_check[el.name] = true
			removed = true
		end
	end
	if removed
		count += 1
	else
		break
	end
end

puts count

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

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

hash = Hash.new { |h, k| h[k] = [] }
tied.each do |a, b|
  hash[a] << b
  hash[b] << a
end

kicked = 0
loop do
  kick = hash.select { |k, v| v.size == 1 }
  if kick.any?
    kick.each do |a, b|
      b = b.first
      hash.delete a
      hash[b].delete a
    end
    kicked += 1
  else
    break
  end
end

p kicked

n, m = gets.split.map(&:to_i)
e = []
0.upto(n+1){ |i| e[i] = [] }
m.times{
 a, b = gets.split.map(&:to_i)
 e[a] << b
 e[b] << a
}
ans = 0
while true
 f = true
 ne = Marshal.load(Marshal.dump(e))
 e.each_with_index{ |x,i|
  next if x.length != 1
  ne[x[0]].delete(i)
  ne[i] = []
  f = false
 }
 e = ne
 break if f
 ans += 1
end
p ans

n, m = gets.split.map(&:to_i)
a = Array.new(n){[false] * n}
c = [0] * n
v = n.times.to_a
m.times do
	x, y = gets.split.map{|_| _.to_i - 1}
	a[x][y] = a[y][x] = true
	c[x] += 1
	c[y] += 1
end

ans = 0
loop do
	w = v.select{|i| c[i] == 1}
	break if w.empty?
	w.each do |i|
		next if c[i] != 1
		j = a[i].index(true)
		a[i][j] = a[j][i] = false
		c[i] -= 1
		c[j] -= 1
	end
	ans += 1
end
p ans

n,m=gets.split.map(&:to_i)
g=Array.new(n){Array.new(n,0)}
cnt=Array.new(n,0)
m.times{
        a,b=gets.split.map(&:to_i)
        a-=1
        b-=1
        g[a][b]=1
        g[b][a]=1
        cnt[a]+=1
        cnt[b]+=1
}
ans=0
loop {
        t=0
        n.times{|i|
                t+=(cnt[i]>0?1:0)
        }
        if t<=1 then break end
        t=0
        n.times{|i|
                t+=(cnt[i]==1?1:0)
        }
        if t==0 then break end
        r=cnt.clone
        n.times{|i|
                if r[i]==1 then
                        n.times{|j|
                                if g[i][j]>0 then
                                        g[i][j]-=1
                                        g[j][i]-=1
                                        cnt[i]-=1
                                        cnt[j]-=1
                                end
                        }
                end
        }
        ans+=1
}
p ans

class Kid
    attr_accessor :tied_to, :number
    def initialize (num)
        @tied_to = []
        @number = num
    end
end

result = -1
input = STDIN.gets.strip
laces = []
input.split.last.to_i.times do |i|
    laces.push STDIN.gets.strip.split.collect {|i| i.to_i}
end

while true
    kids = Array.new(input.split.first.to_i) {|i| Kid.new(i+1)}
    result += 1
    laces.each do |i|
        kids[i[0]-1].tied_to.push i[1] unless kids[i[0]-1].tied_to.include? i[1]
        kids[i[1]-1].tied_to.push i[0] unless kids[i[1]-1].tied_to.include? i[0]
    end
    remove = []
    kids.each do |i|
        remove.push(i.number) if i.tied_to.size == 1
    end
    break if remove.size == 0
    remove.each do |i|
        laces.delete_if {|l| l.include? i}
    end
    break if result == 2
end
p result

n, m = gets.split.map(&:to_i)
e = []
0.upto(n+1){ |i| e[i] = [] }
m.times{
 a, b = gets.split.map(&:to_i)
 e[a] << b
 e[b] << a
}
ans = 0
while true
 f = true
 ne = e.clone
 e.each_with_index{ |x,i|
  next if x.length != 1
  x.each{ |y| ne.each{ |z| z.delete(y) } }
  e[i] = []
  f = false
 }
 e = ne
 break if f
 ans += 1
end
p ans


Given a string $$$s$$$ of length $$$n$$$ and integer $$$k$$$ ($$$1 \le k \le n$$$). The string $$$s$$$ has a level $$$x$$$, if $$$x$$$ is largest non-negative integer, such that it's possible to find in $$$s$$$:  $$$x$$$ non-intersecting (non-overlapping) substrings of length $$$k$$$,  all characters of these $$$x$$$ substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings). A substring is a sequence of consecutive (adjacent) characters, it is defined by two integers $$$i$$$ and $$$j$$$ ($$$1 \le i \le j \le n$$$), denoted as $$$s[i \dots j]$$$ = "$$$s_{i}s_{i+1} \dots s_{j}$$$".For example, if $$$k = 2$$$, then:  the string "aabb" has level $$$1$$$ (you can select substring "aa"),  the strings "zzzz" and "zzbzz" has level $$$2$$$ (you can select two non-intersecting substrings "zz" in each of them),  the strings "abed" and "aca" have level $$$0$$$ (you can't find at least one substring of the length $$$k=2$$$ containing the only distinct character). Zuhair gave you the integer $$$k$$$ and the string $$$s$$$ of length $$$n$$$. You need to find $$$x$$$, the level of the string $$$s$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the length of the string and the value of $$$k$$$. The second line contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.

Print a single integer $$$x$$$ — the level of the string.

NoteIn the first example, we can select $$$2$$$ non-intersecting substrings consisting of letter 'a': "(aa)ac(aa)bb", so the level is $$$2$$$.In the second example, we can select either substring "a" or "b" to get the answer $$$1$$$.

n, k = gets.split.map(&:to_i)
s = gets.chop
arr = [0] * 1000
cur = [0, '0']
s.split('').each do |c|
  if (c == cur[1])
    cur[0] += 1
  else
    cur[0] = 1
    cur[1] = c
  end
  if (cur[0] == k)
    arr[c.ord] += 1
    cur[0] = 0
  end
end
puts arr.max

DBG = true
n,k = gets.split.map{|z| z.to_i}
s = gets.chomp
alpha = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
          'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
           'w', 'x', 'y', 'z' ]
lv = 0
for c in alpha
  cnt = 0
  len = 0
  for i in 0...n
    if s[i] == c
      len += 1
      if len == k
        len = 0
        cnt += 1
      end
    else
      len = 0
    end
  end
  lv = cnt if cnt > lv
end
puts "#{lv}"

require 'set'

if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

nk = gets.chomp.split(" ").map(&:to_i)
n = nk[0]
k = nk[1]

hash = Hash.new(0)
last = Hash.new(-1)
str = gets.chomp

breakpoints = Set.new
(0..n-1).each do |i|
	if str[i]!=str[i+1]
		breakpoints.add(i)
	end
end

toskip = Set.new
breakpoints.each do |br|
	(br-k+2..br).each do |x|
		toskip.add(x)
	end
end

(0..n-k).each do |st|
	next if toskip.include?(st)
	char = str[st]
#	thestr = str[st..st+k-1]
#	next if thestr.each_char.to_a.uniq.length>1
	itslast = last[char]
	next if itslast>=st

	hash[char]+=1
	last[char] = st+k-1
end
#p hash
#p toskip
if hash.empty?
	puts 0
else
	puts hash.values.max
end

#for 1 to k starting index, take steps of k


One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.

The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.

Print a single integer — the number of problems the friends will implement on the contest.

NoteIn the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution.

p gets.to_i.times.map{gets}.count{|x| x.count('1') >= 2}

n = gets.to_i
count = 0
for i in 1..n
  buf = gets.split(' ').map(&:to_i)
  a, b, c = buf[0], buf[1], buf[2]
  count += 1 if a + b + c >= 2
end
puts count

b = gets.chomp
a = 0
array = []
while a < b.to_i
  n = STDIN.gets.split(" ")
  if (n[0].to_i + n[1].to_i + n[2].to_i) > 1
    array << 1
  end
  a += 1
end

puts array.size

res = 0
gets.to_i.times do
  input = gets.split.map(&:to_i)
  res += 1 if input.select { |item| item == 1 }.size >= 2
end
puts res

count = 0

gets.strip.to_i.times do
  p, v, t = gets.strip.split(' ').map(&:to_i)
  count +=1 if p + v + t >= 2
end

puts count

#!/usr/bin/env ruby

count = gets.to_i
sum = 0

(0..count-1).each do |i|
	row = gets.split(" ")
	row_sum = 0
	row.each do |r|
		row_sum += r.to_i
	end
	if row_sum > 1 then
		sum+=1
	end
end

puts sum

n = gets.to_i

peta = []
counter = 0
for i in 0..n-1
  peta[i] = gets.split.map(&:to_i)
  counter+=1 if peta[i].count(1)>=2
end

puts counter

num = gets.chomp.to_i
array = []
i = 0
while (i < num)
	array.push gets.chomp
	i = i+1
end
aux = 0
array.each do |leng|
	line = leng.split
	if (line[0].to_i + line[1].to_i + line[2].to_i >= 2)
		aux = aux + 1
	end
end
puts aux.to_s

n = gets.to_i
m = 0;
n.times do
  x, y, z = gets.split.map(&:to_i)
  m += 1 if x + y + z >= 2
end
puts m

problems_count = gets.chomp.to_i

counter = 0
problems_count.times.each do
  submission_string = gets.chomp
  submission = submission_string.split(' ').map(&:to_i)
  el_counter = 0
  submission.each do |el|
    el_counter += 1 if el.eql?(1)
  end
  counter += 1 if el_counter >= 2
end

puts counter

count = gets.to_i

res = 0
count.times do |i|
    res += 1 if gets.split(" ").map(&:to_i).inject(:+) > 1
end

p res

T = gets.chomp.to_i
ans = 0
for i in (1..T)
  a = gets.chomp.split(' ')
  ans += (a.count("1") > 1) ? 1 : 0
end
puts ans

number = gets.strip.to_i

count = 0
number.times do
  input = gets.strip
  count += 1 if input.split(' ').count('1') >= 2
end

puts count

n = gets.chomp.to_i
puts n.times.select {|i|gets.chomp.split(' ').map(&:to_i).select{|i| i > 0}.count > 1 }.count

n = gets.to_i
ans = 0
n.times do
  if gets.split.map(&:to_i).inject(:+) >= 2
    ans += 1
  end
end
puts ans

$res = 0
$cnt = 0

gets.to_i.times{|x| x = gets.split.map(&:to_i)
    x.each do |num|
        if num == 1
            $cnt += 1
        end
    end
    if $cnt >= 2
        $res += 1
    end
    $cnt = 0
}

puts $res

require 'scanf'
n = $stdin.readline.to_i

counter = 0
n.times do
  a, b, c = $stdin.readline.scanf("%d%d%d")
  counter += 1 if a + b + c >=2
end

puts counter

def get_num
    input = gets.chomp.split
    x = 0
    for i in 0..input.length - 1
        x = x + input[i].to_i
    end
    if x >= 2
        return 1
    else
        return 0
    end
end

$n = gets.chomp.to_i
ans = 0
for i in 1..$n
    ans += get_num
end

puts ans

n = gets.chomp.to_i
ans = 0
n.times{
  num = gets.chomp.split.map{|x| x.to_i }
  ans += 1 if num.inject{ |sum,x| sum + x } >= 2
}
puts ans

n =  gets.to_i
f = []
s = []
l = []
arrs = []
implements  = 0

n.times do
  q = gets.strip.split(" ").map(&:to_i)
  f << q[0]
  s << q[1]
  l << q[2]
  arrs << q
end

arrs.each do |arr|
  implements += 1 if arr.count{|one| one == 1}  > 1
end
puts implements

n, count = gets.chomp.to_i, 0
n.times do
  count += 1 if (gets.chomp.split(' ').map(&:to_i).reduce(:+) > 1)
end
puts count

def chk(ans)
	n=0
	for i in ans
		if i==1
			n+=1
		end
	end
	return n
end
n = gets.to_i()
problem =0
while n>0
	n-=1
	ans = gets.split().map{|x| x.to_i}
	if chk(ans)>1
		problem+=1
	end
end
puts problem

n = gets.chomp.to_i
c = 0
while n > 0
    s1, s2, s3= gets.chomp.split.map(&:to_i)
    if s1+s2+s3 >= 2
         c = c + 1
    end
        n -=1
end
puts c

def answers ()
  n = gets.chomp
  n = n.to_i
  final = 0

  for i in 0...n
    count = 0
    test = Array.new
    test = gets.split(' ').map(&:to_i)
    test.each { |x|
      if x == 1
      count+=1
      end
    }
      if count >= 2 then
        final +=1
      end
  end
  puts final
end

answers

x=0
gets.chomp.to_i.times {
	a,b,c=gets.split.map &:to_i
	x+=1 unless a+b+c < 2
}
puts x

N = gets.to_i
as = N.times.map{gets.split.count{|bb| bb.to_i.zero? }}

puts as.count{|a| a < 2 }

n = gets.strip.to_i
count = 0
n.times do |i|
  arr = gets.strip.split(" ").map(&:to_i)
  count += 1 if arr.count{|elem| elem == 1} > 1
end
puts count

N = gets.to_i
as = N.times.map{gets.split.count{|bb| bb == '0' }}

puts as.count{|a| a < 2 }

res=0
gets.to_i.times{(gets.count(?1))>=2?res+=1:""}
puts res

N = gets.to_i
as = N.times.map{gets.chomp.gsub('0','')}
puts as.count{|a| a.size > 3 }

n = gets.to_i
puts n.times.map{gets.split.map(&:to_i).inject(:+)}.select{|x| x >= 2}.size

n = gets.chomp.to_i

count = 0

while n > 0
   a = gets.chomp
   if a[0].to_i + a[2].to_i + a[-1].to_i >= 2
      count += 1
   end
   n -= 1
end

puts count

amountOfProblems = gets.chomp#get input on first line
amountOfProblems = amountOfProblems.to_i
willWorkSolution = 0
secondCounter = 0

amountOfProblems.times do
    willWorkSolution = gets.chomp # 1 0 1 - space separated other input
    willWorkSolution = willWorkSolution.split(" ") # array is: ["1", "0", "1"]
    counter = 0

    willWorkSolution.each do |one_or_zero|
        if (one_or_zero == "1")
           counter = counter + 1
            if (counter == 2)
                secondCounter = secondCounter + 1
            end
        end

    end
end

puts secondCounter

puts STDIN.readlines[1..-1].map(&:strip).map(&:split).inject(0) { |memo, w| memo + (w.find_all { |x| x=="1"}.size >= 2 ? 1 : 0) }

#my code goes here
a = []
k = 0
n = gets.to_i
for c in 1..n
s = 0
a = gets.chomp.split().map { |e| e.to_i }
a.each do |x|
  s += x
end
if s >= 2
k = k + 1
else
k = k + 0
end
end
puts "#{k}"

n = gets.to_i
m = 0;
n.times do
  x, y, z = gets.split.map(&:to_i)
  m += 1 if x + y + z >= 2
end
puts m

#!/usr/bin/env ruby
input = gets.to_i

answer = 0
input.times do
  inp = gets.split(' ').map(&:to_i).inject(0, :+)
  answer += 1 if inp >= 2
end

puts answer

n = gets.to_i
a =[]
j = 0

for i in 1..n do
	a = gets.split.map(&:to_i)
	if a.count(1) > 1
		j = j+1
	end
end

puts j

i = gets.to_i
counter = 0
(1..i).each do |x|
  counter += gets.split(' ').map(&:to_i).reduce(:+) >= 2 ? 1 : 0
end
print counter

cnt = 0
n = gets.chomp.to_i
n.times{cnt += 1 if gets.chomp.split.map(&:to_i).reduce(:+) > 1}
puts cnt

ans=0
a=[]
gets.to_i.times{|i|
	a<<gets.chomp.delete(' ').delete('0')
}
a.each {|i|
	if i[/11/]=="11" then ans+=1 end	}
p ans

x=0
gets.chomp.to_i.times {
	a,b,c=gets.split.map &:to_i
	x+=1 unless a+b+c < 2
}
puts x

n = gets.to_i
ans = 0
n.times do
	f, s, t = gets.split.map{|x| x.to_i}
	ans += 1 if f + s + t >= 2
end
p ans

n = gets.to_i

problems = []
1.upto(n) do |idx|
    problem = gets.gsub("\n", "")
    problem = problem.split(" ").map(&:to_i)
    problems.push(problem)
end

problems_implemented = 0
problems.each do |problem|
    sureness = 0
    problem.each do |friend|
        sureness += friend
    end
    if sureness >= 2
        problems_implemented += 1
    end
end

puts problems_implemented

n = gets.chomp.to_i
cnt = 0
n.times do
	cnt += 1 if gets.chomp.split.map(&:to_i).count(1) >= 2
end
puts cnt

a=0
STDIN.read.split("\n").drop(1).each do |w|
  a += 1 if w.chomp.split(' ').map{|n| n.to_i}.inject(:+) >= 2
end
puts a

n = gets.to_i
problems_solved = 0
n.times {
    arr = gets.split(" ").map(&:to_i)
    if arr.select{|a| a==1 }.count >=2
        problems_solved+=1
    end
}
puts problems_solved

p = 0
gets.chomp.to_i.times do |variable|
	c = gets.chomp.count("1")
	(p = p + 1) if c > 1
end
puts p

a=gets.chomp.to_i
ans=0
a.times do
b=gets.chomp
if b.count("1")>=2
ans+=1
end
end
puts "#{ans}"

puts gets.to_i.times.map{gets}.count{|x| x.count("1") >= 2}

n, *s = STDIN.read.split("\n") #gets.sFile.readlines('inp.txt')
ans = 0
s.each do |i|
	ans += 1 if i.count('1') > 1
end
p ans

number_of_problems =  gets.chomp.to_i
number_of_solved = 0
(0...number_of_problems).each do |iteration|
  arr = gets.split(" ").map(&:to_i)
  number_of_solved+=1 if  arr.count(1) >= 2
end
puts number_of_solved

problemNum = gets.chomp.to_i

result = 0

(0...problemNum).each do |iter|
	input = gets.chomp.split(' ').map {|item| item.to_i}
	result += 1 if input.count(1) > 1
end

puts result

going_to_solve = 0
gets.to_i.times { going_to_solve += 1 if gets.gsub(" ", "").count("1") >= 2 }
puts going_to_solve

line = gets.chomp
string_value = []
line.to_i.times do |i|
	value = gets.chomp
	string_value << value
end

count = 0
string_value.each do |value|
	if value.split.count{|x| x.to_i == 1} >= 2
		count += 1
	end

end
puts count

d=0
gets.to_i.times{
	a,b,c=gets.split.map{|e| e.to_i}
	d=d+(a+b+c>1?1:0)
}
puts d

#my code goes here
a = []
k = 0
n = gets.to_i
for c in 1..n
for b in 0...3
s = 0
a[b] = gets.to_i
a.each do |x|
  s += x
end
end
if s >= 2
k = k + 1
else
k = k + 0
end
end
puts "#{k}"

gets.to_i.times.map{gets.split.map(&:to_i).inject(:+)}.select{|x| x >= 2}.size

n = gets.to_i
ans = 0

(1..n).each do |i|
  res = 0
  (1..3).each do |j|
    tmp = gets.to_i
    res += tmp
  end

  if res >= 2
    ans += 1
  end
end

puts ans

ans=0
a=[]
gets.to_i.times{|i|
	a<<gets.chomp.delete(' ')
}
a.each {|i|
	if i[/11/]=="11" then ans+=1 end	}
p ans

a = gets.to_i
count = 0
index = 0
loop do
	break if index > a -1
	b = gets.chomp(" ")
	temp = 0
	#puts b[0].to_s + " - This is it!"
	if b[0].to_i == 1
		temp = temp + 1
	end
	if b[1].to_i == 1
		temp = temp + 1
	end
	if b[2].to_i == 1
		temp = temp + 1
	end
	if temp>=2
		count = count + 1
	end
	index = index + 1
end
puts count

n = gets.to_i
l = []
(1..n).each { l << gets.split.map(&:to_i) }
puts l.transpose.map { |x| x.reduce(:+) }.reduce(0) { |res, x| res + (x > 1 ? 1 : 0) }

p = gets.chomp.to_i
s = 0

for i in 1..p do
    a = gets.chomp.split(" ").sort.join("")
    if a.to_i != 1
        s += 1
    end
end

puts s

gets.to_i.times do
    a = gets.split.map(&:to_i).inject(:+)
    a += a
end

n, *s = STDIN.read.split("\n") #gets.sFile.readlines('inp.txt')
puts s.length
ans = 0
s.each do |i|
	if i[0].to_i + i[2].to_i + i[4].to_i >= 2
		ans += 1
	end
end
puts ans

n, *s = gets.split('/n') #File.readlines('inp.txt')
ans = 0
s.each do |i|
	if i[0].to_i + i[2].to_i + i[4].to_i >= 2
		ans += 1
	end
end
puts ans

amountOfProblems = gets.chomp#get input on first line
amountOfProblems = amountOfProblems.to_i
willWorkSolution = 0
solutionsTeamWillWork = []

amountOfProblems.times do
    willWorkSolution = gets.chomp # 1 0 1 - space separated other input
    willWorkSolution = willWorkSolution.split(" ") # array is: ["1", "0", "1"]

    willWorkSolution.each do |one_or_zero|
        if (one_or_zero == "1")
           solutionsTeamWillWork.push(one_or_zero)
        end
    end
end

puts solutionsTeamWillWork.size / amountOfProblems

amountOfProblems = gets.chomp#get input on first line
amountOfProblems = amountOfProblems.to_i
willWorkSolution = 0
solutionsTeamWillWork = []

amountOfProblems.times do
    willWorkSolution = gets.chomp # 1 0 1 - space separated other input
    willWorkSolution = willWorkSolution.split(" ") # array is: ["1", "0", "1"]

    counter = 0

    willWorkSolution.each do |one_or_zero|

        if (one_or_zero == "1")
           counter = counter + 1
           if (counter >= 2)
              solutionsTeamWillWork.push(1)
           end
        end
    end
end

puts solutionsTeamWillWork.size

n = gets.chomp.to_i
a = []
res = 0
for i in 0...n
    a[i] = gets.chomp
    if a.count('1')>=2
        res+=1
    end
end
puts res


Nick's company employed n people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are m applications written in the following form: «employee ai is ready to become a supervisor of employee bi at extra cost ci». The qualification qj of each employee is known, and for each application the following is true: qai > qbi. Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.

The first input line contains integer n (1 ≤ n ≤ 1000) — amount of employees in the company. The following line contains n space-separated numbers qj (0 ≤ qj ≤ 106)— the employees' qualifications. The following line contains number m (0 ≤ m ≤ 10000) — amount of received applications. The following m lines contain the applications themselves, each of them in the form of three space-separated numbers: ai, bi and ci (1 ≤ ai, bi ≤ n, 0 ≤ ci ≤ 106). Different applications can be similar, i.e. they can come from one and the same employee who offered to become a supervisor of the same person but at a different cost. For each application qai > qbi.

Output the only line — the minimum cost of building such a hierarchy, or -1 if it is impossible to build it.

NoteIn the first sample one of the possible ways for building a hierarchy is to take applications with indexes 1, 2 and 4, which give 11 as the minimum total cost. In the second sample it is impossible to build the required hierarchy, so the answer is -1.

INF = 10 ** 20
n = gets.to_i
gets
d = [INF] * (n + 1)
gets.to_i.times do
	a, b, c = gets.split.map(&:to_i)
	d[b] = [d[b], c].min
end
s = d.inject(&:+) - 2 * INF
p s < INF ? s : -1

n = gets.chomp.to_i
q = gets.chomp.split(' ').map &:to_i; q.unshift nil
m = gets.chomp.to_i
result = {}
m.times do
  a, b, c = gets.chomp.split(' ').map &:to_i
  next if q[a] <= q[b]
  result[b] = result[b] ? [result[b], c].min : c
end
puts result.length == n - 1 ? result.values.inject(:+).to_i : -1

n=gets.chomp.to_i
gets
m=gets.chomp.to_i
max=100000000
memo=Array.new
n.times{memo << max}
m.times{
  tmp=gets.chomp.split()
  b=tmp[1].to_i()-1
  c=tmp[2].to_i
  if memo[b] > c
    memo[b]=c
  end
}
sum=0
cnt=0
n.times{|i|
  if memo[i]<max
    sum+=memo[i]
  else
    cnt+=1
  end
}
if cnt==1
  print(sum)
else
  print(-1)
end

#!/usr/bin/ruby

n = gets.to_i
qs = gets.chomp.split.map{|e| e.to_i}
m = gets.to_i

UNSET = 9999999

employees = Array.new(n){Array.new(n, UNSET)} # start from 0!

m.times do
  a, b, c = gets.chomp.split.map{|e| e.to_i}
  if (employees[b - 1][a - 1] > c)
    employees[b - 1][a - 1] = c
  end
end

acc = 0
root = 0

n.times {|i|
  min = employees[i].min
  if (min == UNSET)
    root += 1
    if (root > 1)
      puts -1
      exit
    end
  else
    acc += min
  end
}

puts acc

n = gets.chomp.to_i
q = gets.chomp.split(' ').map &:to_i; q.unshift nil
m = gets.chomp.to_i
result = {}
m.times do
  a, b, c = gets.chomp.split(' ').map &:to_i
  next if q[a] <= q[b]
  result[b] = result[b] ? [result[b], c].min : c
end
puts result.length == n - 1 ? result.values.inject(:+) : -1

n = gets.chomp.to_i
q = gets.chomp.split(' ').map &:to_i
m = gets.chomp.to_i
result = {}
m.times do
  a, b, c = gets.chomp.split(' ').map &:to_i
  result[b] = result[b] ? [result[b], c].min : c
end
puts result.length == n - 1 ? result.values.inject(:+) : -1


Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.First Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position p1, the glass from the second position to position p2 and so on. That is, a glass goes from position i to position pi. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.After all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t.

The first line contains three integers: n, s, t (1 ≤ n ≤ 105; 1 ≤ s, t ≤ n) — the number of glasses, the ball's initial and final position. The second line contains n space-separated integers: p1, p2, ..., pn (1 ≤ pi ≤ n) — the shuffling operation parameters. It is guaranteed that all pi's are distinct. Note that s can equal t.

If the marble can move from position s to position t, then print on a single line a non-negative integer — the minimum number of shuffling operations, needed to get the marble to position t. If it is impossible, print number -1.

n, s, t = gets.split.map &:to_i
p = [0] + gets.split.map(&:to_i)

visited = {s => true}

shuffle_count = 0
current_s = s
until current_s == t do
  if visited.has_key? p[current_s]
    puts -1
    exit
  end
  current_s = p[current_s]
  shuffle_count += 1
  visited[current_s] = true
end

puts shuffle_count

n, s, t = gets.split.map &:to_i
p = gets.split.map &:to_i

visited = {s => true}

shuffle_count = 0
current_s = s
until current_s == t do
  if visited.has_key? p[current_s - 1]
    puts -1
    exit
  end
  current_s = p[current_s - 1]
  shuffle_count += 1
  visited[current_s] = true
end

puts shuffle_count

I =->{gets.split.map &:to_i}
def gao
	n, s, t = I[]; return 0 if s==t
	s -= 1; t -= 1; a = I[]; vis = Array.new(n, 0); s = a[s] - 1; res = 1; while (s != t) do
		vis[s] = 1; s = a[s]-1; res += 1
		return -1 if !vis[s].zero?
	end
	res
end
puts gao()

st = gets.split
n=st[0].to_i
s=st[1].to_i
t=st[2].to_i

mas = gets.split

count=0
path_exists=false
if s==t
  puts 0
else
  cur=s
  (n+1).times do
    cur=mas[cur-1].to_i
    count+=1
    if cur==t
      path_exists = true
      break
    end
  end
  if path_exists
    print(count)
  else
    print(-1)
  end
end

#!/usr/bin/env ruby -w

require 'set'

n_glasses, ball_start, ball_end = gets.split(' ').map(&:to_i)
ball_start -= 1
ball_end   -= 1

marbles = gets.split(' ').map(&:to_i).map(&:pred)

iterations   = 0

visited = Set.new

actual_index = ball_start
until actual_index == ball_end || iterations == -1
  if visited.include? actual_index
    iterations = -1
  else
    visited << actual_index
    actual_index = marbles[actual_index]
    iterations += 1
  end
end

print iterations

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

p = [0] + gets.split.map(&:to_i)

a = s;
count = 0
until a == t
  a = p[a]
  count += 1
  if a == s
    count = -1
	break
  end
end

puts count

#!/usr/bin/ruby1.9

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

move = [0] + STDIN.readline.split.collect {|s| s.to_i }

curr = s
steps = 0

while true
	break if curr == t
	steps += 1
	curr = move[curr]
	if curr == s
		steps = -1
		break
	end
end

puts steps

n,s,t=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i).unshift('a')
d,k=s,0
while d!=t
	d=a[d]
	k+=1
	if k>n
		k=-1
		break
	end
end
puts k

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    n.times do |turn|
      if s == t
        puts turn
        exit
      elsif s == operation[s-1]
        puts -1
        exit
      else
        s = operation[s-1]
      end
    end
    puts -1
  end
end

b = B.new

n,s,t=gets.split.map(&:to_i)
p=gets.split.map(&:to_i)
p.unshift(0)
v=s
res=-1
0.upto(n){|x|
	if v == t then
		res=x
		break
	end
	v=p[v];
}
puts res

n,s,t = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
visited = Array.new(n,false)
ans = -1
i = s - 1
count = 0
if s == t
	ans = 0
else
	while true
		visited[i] = true
		if !visited[arr[i]-1]
			i = arr[i] - 1
			count += 1
		else
			# puts "breaking here #{arr[i]} #{visited}"
			break
		end
		if i == t - 1
			ans = count
			break
		end

	end
end
# puts "#{visited} #{i}"
puts ans

n,s,t = gets.chomp.split(" ").collect {|x| x.to_i}

arr = gets.chomp.split(" ").collect {|x| (x.to_i-1)}

aux = [0]*n

(0...n).each{ |v|
  aux[arr[v]] = v
}

q = 0
s-=1
t-=1

while s!=t and q<n
	t = aux[t]
	q += 1
end

if q==n
	puts -1
else
	puts q
end

n, s, t = gets.split.map(&:to_i)
p = gets.split.map(&:to_i)

k = 0

while s!=t do
    k+=1

    m = p[s-1]
    p[s-1] = -1
    s = m

    if s==-1
        k = -1
        break
    end
end

puts k

require 'set'

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

_, s, t = read_next_line
p = read_next_line
w = Set.new << s
c = 0
while s != t
  s = p[s - 1]
  if w.include? s
    puts -1
    exit
  end
  w << s
  c += 1
end
puts c

#!/usr/bin/env ruby

n, s, t = gets.split.collect{ |i| i.to_i }
p = gets.split.collect{ |i| i.to_i - 1 }

s = s - 1
t = t - 1
n.times do |i|
	if s == t
		puts i
		exit
	end
	s = p[s]
end

puts -1

n, s, t = gets.strip.split.map(&:to_i)
ps = gets.strip.split.map(&:to_i)

# find cycles
cycles = []
#seq = (1..n).to_a.map{|x| [x,false]}
free = [true]*n
i = 0
while i < n
  j = i
  i += 1
  next unless free[j]

  cycle = []
  while free[j]
    free[j] = false
    cycle << (j + 1)
    j = ps[j] - 1
  end
  cycles << cycle
end

#p cycles

cycle = cycles.find{|c| c.include?(s)}
if cycle.include?(t)
  si = cycle.index s
  ti = cycle.index t
  result = (ti - si) % cycle.length
else
  result = -1
end

puts result

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    n.times do |turn|
      if s == operation[s-1]
        puts -1
        break
      elsif s == t
        puts turn
        break
      else
        s = operation[s-1]
      end
    end
  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    if s == t
      puts 0
      return 0
    end

    diff = 0

    turn = 0
    operation.each do |pos|
      turn += 1
      if s == pos
        diff += 1
      else
        s = pos
      end
      break if t == s
    end

    if t == s && n > turn
      puts turn - diff
    elsif diff > 0 && t == s
      puts n - diff
    else
      puts -1
    end
  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    n.times do |turn|
      if s == t
        puts turn
        break
      elsif s == operation[s-1]
        puts -1
        break
      else
        s = operation[s-1]
      end
    end
  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    if s == t
      puts 0
      return 0
    end

    diff = 0

    turn = 0
    operation.each do |pos|
      turn += 1
      if s == pos
        diff += 1
      else
        s = pos
      end
      break if t == s
    end

    if t == s && n >= turn
      if diff > 0
        puts "#{turn - diff}"
      else
        puts -1
      end
    else
      puts -1
    end
  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    if s == t
      puts 0
      return 0
    end

    diff = 0

    turn = 0
    operation.each do |pos|
      turn += 1
      if s == pos
        diff += 1
        s = pos
      else
        s = pos
      end
      break if t == s
    end

    if t == s && n > turn
      puts turn - diff
    elsif diff > 0 && t == s
      puts n - diff
    else
      puts -1
    end
  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    if s == t
      puts 0
      return 0
    end

    diff = 0

    list = []

    turn = 0
    operation.each do |pos|
      turn += 1
      if list.include?(pos)
        diff += 1
      else
        s = pos
        list << pos
      end
      break if t == s
    end

    if t == s && n >= turn
      if diff > 0
        puts "#{turn - diff}"
      else
        puts -1
      end
    else
      puts -1
    end
  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    if s == t
      puts 0
      return 0
    end

    diff = 0

    operation.each do |pos|
      if s == pos
        diff += 1
        s = pos
      else
        s = pos
      end
    end

    if diff > 0
      puts n-diff
    else
      puts -1
    end
  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    if s == t
      puts 0
      return 0
    end

    diff = 0

    turn = 0
    operation.each do |pos|
      turn += 1
      if s == pos
        diff += 1
        s = pos
      else
        s = pos
      end
      break if t == s
    end

    if diff > 0 && t == s && n > turn
      puts turn - diff
    elsif diff > 0 && t == s
      puts n - diff
    else
      puts -1
    end
  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    n.times do |turn|
      if s == t
        puts turn
        break
      elsif s == operation[s-1]
        puts -1
        break
      else
        s = operation[s-1]
      end
    end
    puts -1
  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    if s == t
      puts 0
      return 0
    end

    diff = 0

    turn = 0
    operation.each do |pos|
      turn += 1
      if s == pos
        diff += 1
      else
        s = pos
      end
    end

    if t == s && n >= turn
      if diff > 0
        puts "#{turn - diff}"
      else
        puts -1
      end
    else
      puts -1
    end
  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    if s == t
      puts 0
      return 0
    end

    diff = 0

    operation.each do |pos|
      if s == pos
        diff += 1
        s = pos
      else
        s = pos
      end
    end

    if diff > 0 && t == s
      puts n-diff
    else
      puts -1
    end
  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    if s == t
      puts 0
      return 0
    elsif s == operation[0]
      puts n-1
    else
      puts -1
    end

  end
end

b = B.new

class B
  def initialize
    n, s, t = $stdin.gets.split(' ').map(&:to_i)
    operation = $stdin.gets.split(' ').map(&:to_i)

    if s == t
      puts 0
      return 0
    end

    diff = 0

    turn = 0
    operation.each do |pos|
      turn += 1
      if s == pos
        diff += 1
      else
        s = pos
      end
      break if t == s
    end

    if t == s && n > turn
      puts "#{turn - diff}"
    elsif diff > 0 && t == s
      puts "#{n - diff}"
    else
      puts -1
    end
  end
end

b = B.new


Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed.    Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally:   if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$);  if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots:   1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.

For each test case print:   YES if there is a sequence of shots leading to a given matrix;  NO if such a sequence does not exist.  The letters in the words YES and NO can be printed in any case.

NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.

def in_range(i, j, n)
  i < n && j < n
end

gets.strip.to_i.times do |t|
  n = gets.strip.to_i
  board = []
  n.times do
    board << gets.strip
  end
  res = true
  (0..n-1).to_a.each do |i|
    (0..n-1).to_a.each do |j|
      if board[i][j] == '1'
        if in_range(i+1, j, n) && board[i+1][j] == '0' && in_range(i, j+1, n) && board[i][j+1] == '0'
          res = false
          break
        end
      end
    end
    break if res == false
  end

  puts res ? "YES" : "NO"
end

t = gets.chomp.to_i
t.times do |testcase|
  n = gets.chomp.to_i
  grid = []
  n.times do |i|
    grid << gets.chomp
  end
  flag = true
  n.times do |i|
    n.times do |j|
      if grid[i][j] == "1"
        if !(i==n-1 || j==n-1 || grid[i+1][j]=="1" || grid[i][j+1]=="1")
          flag = false
          break
        end
      end
    end
    if !flag
      break
    end
  end
  if flag
    puts "YES"
  else
    puts "NO"
  end
end

t = gets.to_i
t.times do
  n = gets.to_i
  s = n.times.map { gets.chomp }
  ok = true
  (n - 2).downto(0) do |i|
    (n - 2).downto(0) do |j|
      if s[i][j] == "1"
        if !(s[i][j + 1] == "1" || s[i + 1][j] == "1")
          ok = false
          break
        end
      end
    end
    break if !ok
  end
  puts ok ? "YES" : "NO"
end

def func(a)
    a.map{|e| e.join.sub(/([o1]*)[o1]$/){|s|s=?o*$1.size+?o}.split('')}
end

def func2(a)
    a.map{|e| e.join.sub(/^(1+)o/){|s|s=?o*$1.size+?o}.split('')}
end

gets.to_i.times{
    n=gets.to_i
    a=(1..n).map{gets.chomp.chars}
    a=func(a)
    a=func(a.transpose)
    a=func2(a)
    a=func2(a.transpose.map(&:reverse))
    #a.map{|e|puts e.join}
    puts (a.flatten.none?{|e|e==?1} ? :YES : :NO)
}

def func(a)
    a.map{|e| e.join.sub(/([o1]*)[o1]$/){|s|s=?o*$1.size+?o}.split('')}
end

def func2(a)
    a.map{|e| e.join.sub(/(1+)o/){|s|s=?o*$1.size+?o}.split('')}
end

gets.to_i.times{
    n=gets.to_i
    a=(1..n).map{gets.chomp.chars}
    a=func(a)
    a=func(a.transpose)
    a=func2(a)
    a=func2(a.transpose)
    puts (a.flatten.none?{|e|e==?1} ? :YES : :NO)
    #a.map{|e|puts e.join}
}

def func(a)
    n=a.size
    q=[]
    (0...n).each do |i|
        if a[i][-1]==?1
            q << [i, n-1]
        elsif a[-1][i]==?1
            q << [n-1, i]
        end
    end

    while q[0]
        r, c=q.pop
        a[r][c]=?*
        [[0, -1], [-1, 0]].each do |dr, dc|
            nr=r+dr
            nc=c+dc
            next if nr<0 or nr>=n or nc<0 or nc>=n
            next if a[nr][nc]!=?1
            q << [nr, nc]
        end
    end
end

gets.to_i.times do
    n=gets.to_i
    a=(1..n).map{gets.chomp}
    func(a)

    puts (a.none?{|e|e[?1]} ? :YES : :NO)
    #a.map{|e|puts e}; puts
end

def func(a)
    n=a.size
    q=[]
    (0...n).each do |i|
        if a[i][-1]==?1
            q << [i, n-1]
        elsif a[-1][i]==?1
            q << [n-1, i]
        end
    end

    while q[0]
        r, c=q.shift
        a[r][c]=?*
        [[0, -1], [-1, 0]].each do |dr, dc|
            nr=r+dr
            nc=c+dc
            next if nr<0 or nr>=n or nc<0 or nc>=n
            next if a[nr][nc]!=?1
            q << [nr, nc]
        end
    end
end

gets.to_i.times do
    n=gets.to_i
    a=(1..n).map{gets.chomp}
    func(a)

    puts (a.none?{|e|e[?1]} ? :YES : :NO)
    #a.map{|e|puts e}; puts
end

def func(a)
    a.map{|e| e.join.sub(/([#1]*)[#1]$/){|s|s=?#*$1.size+?#}.split('')}
end

def func2(a)
    a.map{|e| e.join.gsub(/(1+)#/){|s|s=?#*$1.size+?#}.split('')}
end

gets.to_i.times{
    n=gets.to_i
    a=(1..n).map{gets.chomp.chars}
    a=func(a)
    a=func(a.transpose)
    a=func2(a)
    a=func2(a.transpose)
    puts (a.flatten.none?{|e|e==?1} ? :YES : :NO)
    #a.map{|e|puts e.join}; puts
}

def func(a)
    a.map{|e| e.join.sub(/([#1]*)[#1]$/){|s|s=?#*$1.size+?#}.split('')}
end

def func2(a)
    a.map{|e| e.join.gsub(/(1+)#/){|s|s=?#*$1.size+?#}.split('')}
end

gets.to_i.times{
    n=gets.to_i
    a=(1..n).map{gets.chomp.chars}
    a=func(a)
    a=func(a.transpose)
    b=[]
    while a!=b
        b=func2(a)
        b=func2(b.transpose)
        a=b.dup
    end
    puts (a.flatten.none?{|e|e==?1} ? :YES : :NO)
    #a.map{|e|puts e.join}; puts
}


Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.

The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.  It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).

In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.

n = gets.to_i

a = gets.split(" ").collect{|x| x.to_i}
signs = ""

s=0
a.reverse_each{|x|
	if s > 0
		s -= x
		signs << '-'
	else
		s+=x
		signs << '+'
	end
}

result = ""

signs.reverse.each_char{|c|
	if s >= 0
		result << c
	else
		result << (c == '+' ? '-' : '+')
	end
}

puts result

n = gets.to_i

a = gets.split(" ").collect{|x| x.to_i}
a.sort!{|x,y| y <=> x}
signs = ""

s=0
a.each{|x|
	if s > 0
		s -= x
		signs += '-'
	else
		s+=x
		signs +='+'
	end
}

result = ""
signs.each_char{|c|
	if s >= 0
		result+= c
	else
		result += c == '+' ? '-' : '+'
	end
}

puts result