The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order:  She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$).  She collects all mushrooms on point $$$y$$$.  A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.

For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.

NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.

gets.to_i.times do
    n,k=gets.split.map(&:to_i)
    arr=gets.split.map(&:to_i)
    if k<n
        sum=0
        max=0
        for i in (0...n) do
            if i<k
                sum+=arr[i]
            else
                max=[max,sum].max
                sum+=arr[i]-arr[i-k]
            end
        end
        max=[max,sum].max
        puts max + k*(k-1)/2
    else
        puts k*(k-1)/2-(k-n)*(k-n-1)/2+arr.sum
    end
end


You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$ and an integer $$$k$$$, such that $$$1 \leq k \leq n$$$. A permutation means that every number from $$$1$$$ to $$$n$$$ is contained in $$$p$$$ exactly once.Let's consider all partitions of this permutation into $$$k$$$ disjoint segments. Formally, a partition is a set of segments $$$\{[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]\}$$$, such that:  $$$1 \leq l_i \leq r_i \leq n$$$ for all $$$1 \leq i \leq k$$$;  For all $$$1 \leq j \leq n$$$ there exists exactly one segment $$$[l_i, r_i]$$$, such that $$$l_i \leq j \leq r_i$$$. Two partitions are different if there exists a segment that lies in one partition but not the other.Let's calculate the partition value, defined as $$$\sum\limits_{i=1}^{k} {\max\limits_{l_i \leq j \leq r_i} {p_j}}$$$, for all possible partitions of the permutation into $$$k$$$ disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by $$$998\,244\,353$$$.

The first line contains two integers, $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 200\,000$$$) — the size of the given permutation and the number of segments in a partition. The second line contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the given permutation.

Print two integers — the maximum possible partition value over all partitions of the permutation into $$$k$$$ disjoint segments and the number of such partitions for which the partition value is equal to the maximum possible value, modulo $$$998\,244\,353$$$. Please note that you should only find the second value modulo $$$998\,244\,353$$$.

NoteIn the first test, for $$$k = 2$$$, there exists only two valid partitions: $$$\{[1, 1], [2, 3]\}$$$ and $$$\{[1, 2], [3, 3]\}$$$. For each partition, the partition value is equal to $$$2 + 3 = 5$$$. So, the maximum possible value is $$$5$$$ and the number of partitions is $$$2$$$.In the third test, for $$$k = 3$$$, the partitions with the maximum possible partition value are $$$\{[1, 2], [3, 5], [6, 7]\}$$$, $$$\{[1, 3], [4, 5], [6, 7]\}$$$, $$$\{[1, 4], [5, 5], [6, 7]\}$$$, $$$\{[1, 2], [3, 6], [7, 7]\}$$$, $$$\{[1, 3], [4, 6], [7, 7]\}$$$, $$$\{[1, 4], [5, 6], [7, 7]\}$$$. For all of them, the partition value is equal to $$$7 + 5 + 6 = 18$$$. The partition $$$\{[1, 2], [3, 4], [5, 7]\}$$$, however, has the partition value $$$7 + 3 + 6 = 16$$$. This is not the maximum possible value, so we don't count it.

MOD = 998244353
N, K = gets.split.map(&:to_i)
P = gets.split.map(&:to_i)

order = Hash.new

P.each_with_index do |v, idx|
  order[v] = idx
end

v1 = (N - K + 1..N).inject(:+)

points = (N - K + 1..N).map { |n| order[n] }.sort
dp = Array.new(N + 10, 0)
v2 = 1

(K - 1).times do |i|
  po = points[i]
  np = points[i + 1]

  v2 *= np - po
  v2 %= MOD
end

puts [v1, v2].join(' ')

MOD = 998244353
N, K = gets.split.map(&:to_i)
P = gets.split.map(&:to_i)

order = Hash.new

P.each_with_index do |v, idx|
  order[v] = idx
end

v1 = (N - K + 1..N).inject(:+)

points = (N - K + 1..N).map { |n| order[n] }.sort
dp = Array.new(N + 10, 0)
v2 = 1

K.times do |i|
  po = points[i]
  np = points[i + 1] || N

  if i == 0
    v2 *= np - po
  else
    v2 *= np - po
  end

  v2 %= MOD
end

puts [v1, v2].join(' ')


Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.

The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.

Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.

TEST_MODE = ARGV[0] == 't'

def evaluate(actual, expected); actual == expected ? "OK" : "**NG**"; end
def tests(); yield if TEST_MODE; end
def to_array(val); val.kind_of?(Array) ? val : [val]; end
def parse_int_array(str); str.split(" ").collect{|s| s.to_i}; end

def t(input, expected_output)
  input = to_array(input)
  expected_output = to_array(expected_output)
  output = []
  solve(input, output)
  puts "#{evaluate(output, expected_output)} : input=#{input.to_s}, expected=#{expected_output.to_s}, actual=#{output.to_s}"
end

def gen_tree(input, n)
  tree = {}
  (1..n-1).each {|i|
    a, b = parse_int_array(input[i])
    if tree.include?(a) then tree[a].push(b) else tree[a] = [b] end
    if tree.include?(b) then tree[b].push(a) else tree[b] = [a] end
  }
  return tree
end

def find_edge(tree)
  tree.find{|k, v|
    v.size == 1
  }[0]
end

def find_roots(tree, edge, colors)
  c = colors[edge]
  done = {}
  queue = [edge]
  while queue.size > 0
    node = queue.pop
    done[node] = true
    for n in tree[node]
      return [node, n] if colors[n] != c
      queue.push(n) unless done[n]
    end
  end
  return [edge]
end

def eval_branch(tree, parent, root, colors)
  c = colors[root]
  done = {parent => true}
  queue = [root]
#  puts "root:#{root}, parent: #{parent}"
  while queue.size > 0
    node = queue.pop
    done[node] = true
    for n in tree[node]
      next if done[n]
#      puts "node:#{n}, color: #{colors[n]}"
      return false if colors[n] != c
      queue.push(n)
    end
  end
  return true
end

def solve(input, output)
  n = input[0].to_i
  tree = gen_tree(input, n)
  colors = parse_int_array("0 " + input[n])
  edge = find_edge(tree)
#  puts edge
  roots = find_roots(tree, edge, colors)
#  puts root
  if tree[roots[0]].all? {|e| eval_branch(tree, roots[0], e, colors) }
    output << "YES"
    output << roots[0].to_s
  elsif tree[roots[1]].all? {|e| eval_branch(tree, roots[1], e, colors) }
    output << "YES"
    output << roots[1].to_s
  else
    output << "NO"
  end
end

tests do
  # test cases
  t(["4",
    "1 2",
    "2 3",
    "3 4",
    "1 2 1 1"],
    ["YES", "2"])
  t(["3",
      "1 2",
      "2 3",
      "1 2 3"],
      ["YES", "2"])
  t(["4",
    "1 2",
    "2 3",
    "3 4",
    "1 2 1 2"],
    ["NO"])
  t(["2",
      "1 2",
      "1 1"],
      ["YES", "1"])
  t(["4",
    "1 4",
    "2 4",
    "3 4",
    "1 2 3 1"],
    ["YES", "4"])
end

puts solve(STDIN.read.split("\n"), []) unless TEST_MODE

TEST_MODE = ARGV[0] == 't'

def evaluate(actual, expected); actual == expected ? "OK" : "**NG**"; end
def tests(); yield if TEST_MODE; end
def to_array(val); val.kind_of?(Array) ? val : [val]; end
def parse_int_array(str); str.split(" ").collect{|s| s.to_i}; end

def t(input, expected_output)
  input = to_array(input)
  expected_output = to_array(expected_output)
  output = []
  solve(input, output)
  puts "#{evaluate(output, expected_output)} : input=#{input.to_s}, expected=#{expected_output.to_s}, actual=#{output.to_s}"
end

def gen_tree(input, n)
  tree = {}
  (1..n-1).each {|i|
    a, b = parse_int_array(input[i])
    if tree.include?(a) then tree[a].push(b) else tree[a] = [b] end
    if tree.include?(b) then tree[b].push(a) else tree[b] = [a] end
  }
  return tree
end

def find_edge(tree)
  tree.find{|k, v|
    v.size == 1
  }[0]
end

def find_root(tree, edge, colors)
  c = colors[edge]
  done = {}
  queue = [edge]
  while queue.size > 0
    node = queue.pop
    done[node] = true
    for n in tree[node]
      return n if colors[n] != c
      queue.push(n) unless done[n]
    end
  end
  return edge
end

def eval_branch(tree, parent, root, colors)
  c = colors[root]
  done = {parent => true}
  queue = [root]
#  puts "root:#{root}, parent: #{parent}"
  while queue.size > 0
    node = queue.pop
    done[node] = true
    for n in tree[node]
      next if done[n]
#      puts "node:#{n}, color: #{colors[n]}"
      return false if colors[n] != c
      queue.push(n)
    end
  end
  return true
end

def solve(input, output)
  n = input[0].to_i
  tree = gen_tree(input, n)
  colors = parse_int_array("0 " + input[n])
  edge = find_edge(tree)
#  puts edge
  root = find_root(tree, edge, colors)
#  puts root
  if tree[root].all? {|e| eval_branch(tree, root, e, colors) }
    output << "YES"
    output << root.to_s
  else
    output << "NO"
  end
end

tests do
  # test cases
  t(["4",
    "1 2",
    "2 3",
    "3 4",
    "1 2 1 1"],
    ["YES", "2"])
  t(["3",
      "1 2",
      "2 3",
      "1 2 3"],
      ["YES", "2"])
  t(["4",
    "1 2",
    "2 3",
    "3 4",
    "1 2 1 2"],
    ["NO"])
  t(["2",
      "1 2",
      "1 1"],
      ["YES", "1"])
end

puts solve(STDIN.read.split("\n"), []) unless TEST_MODE


Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li.You are given lengths of the claws. You need to find the total number of alive people after the bell rings.

The first line contains one integer n (1 ≤ n ≤ 106) — the number of guilty people. Second line contains n space-separated integers L1, L2, ..., Ln (0 ≤ Li ≤ 109), where Li is the length of the i-th person's claw.

Print one integer — the total number of alive people after the bell rings.

NoteIn first sample the last person kills everyone in front of him.

n = gets.chomp.to_i
l = gets.chomp.split.map(&:to_i)
ans, cmp = 0, n
(n - 1).downto(0) do |i|
  ans += (i < cmp) ? 1 : 0
  cmp = [cmp, i - l[i]].min
end
print ans

gets
ar = gets.split.map(&:to_i)

ptr = ar.length
ans = 0

(ar.length-1).downto(0).each do |i|
  ans += 1  if ptr > i
  ptr = [ptr, i-ar[i]].min
end

puts ans

gets
ar = gets.split.map(&:to_i)

ptr = ar.length
ans = 0

(ar.length-1).downto(0).each do |i|
  if ptr > i
    ans += 1
  end
  ptr = [ptr, i-ar[i]].min
end

puts ans


Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are $$$T$$$ rooms there. Every room has a door into it, each door can be described by the number $$$n$$$ of seals on it and their integer energies $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. All energies $$$a_i$$$ are nonzero and do not exceed $$$100$$$ by absolute value. Also, $$$n$$$ is even.In order to open a door, Naruto must find such $$$n$$$ seals with integer energies $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ that the following equality holds: $$$a_{1} \cdot b_{1} + a_{2} \cdot b_{2} + ... + a_{n} \cdot b_{n} = 0$$$. All $$$b_i$$$ must be nonzero as well as $$$a_i$$$ are, and also must not exceed $$$100$$$ by absolute value. Please find required seals for every room there.

The first line contains the only integer $$$T$$$ ($$$1 \leq T \leq 1000$$$) standing for the number of rooms in the Orochimaru's lair. The other lines contain descriptions of the doors. Each description starts with the line containing the only even integer $$$n$$$ ($$$2 \leq n \leq 100$$$) denoting the number of seals. The following line contains the space separated sequence of nonzero integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$|a_{i}| \leq 100$$$, $$$a_{i} \neq 0$$$) denoting the energies of seals.

For each door print a space separated sequence of nonzero integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$|b_{i}| \leq 100$$$, $$$b_{i} \neq 0$$$) denoting the seals that can open the door. If there are multiple valid answers, print any. It can be proven that at least one answer always exists.

NoteFor the first door Naruto can use energies $$$[-100, 1]$$$. The required equality does indeed hold: $$$1 \cdot (-100) + 100 \cdot 1 = 0$$$.For the second door Naruto can use, for example, energies $$$[1, 1, 1, -1]$$$. The required equality also holds: $$$1 \cdot 1 + 2 \cdot 1 + 3 \cdot 1 + 6 \cdot (-1) = 0$$$.

T = gets.to_i

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

  (n / 2).times do |i|
    b[2 * i] = -a[2 * i + 1]
    b[2 * i + 1] = a[2 * i]
  end

  puts b.join(' ')
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  brr = arr.reverse
  brr.each_with_index do |_, i|
    brr[i] *= -1 if i % 2 == 0
  end
  puts brr.join ' '
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  arr = []
  (n/2).times do |i|
    lcm = a[i*2].lcm(a[i*2+1])
    arr << lcm / a[i*2]
    arr << -(lcm / a[i*2+1])
  end
  ans << arr
end
ans.each do |ar|
  ar.each do |v|
    print "#{v} "
  end
  puts ""
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  b = []
  (n / 2).times do |i|
    b.push(-a[i * 2 + 1])
    b.push(a[i * 2])
  end
  puts b.join(" ")
end


There is a robot staying at $$$X=0$$$ on the $$$Ox$$$ axis. He has to walk to $$$X=n$$$. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.The $$$i$$$-th segment of the path (from $$$X=i-1$$$ to $$$X=i$$$) can be exposed to sunlight or not. The array $$$s$$$ denotes which segments are exposed to sunlight: if segment $$$i$$$ is exposed, then $$$s_i = 1$$$, otherwise $$$s_i = 0$$$.The robot has one battery of capacity $$$b$$$ and one accumulator of capacity $$$a$$$. For each segment, you should choose which type of energy storage robot will use to go to the next point (it can be either battery or accumulator). If the robot goes using the battery, the current charge of the battery is decreased by one (the robot can't use the battery if its charge is zero). And if the robot goes using the accumulator, the current charge of the accumulator is decreased by one (and the robot also can't use the accumulator if its charge is zero).If the current segment is exposed to sunlight and the robot goes through it using the battery, the charge of the accumulator increases by one (of course, its charge can't become higher than it's maximum capacity).If accumulator is used to pass some segment, its charge decreases by 1 no matter if the segment is exposed or not.You understand that it is not always possible to walk to $$$X=n$$$. You want your robot to go as far as possible. Find the maximum number of segments of distance the robot can pass if you control him optimally.

The first line of the input contains three integers $$$n, b, a$$$ ($$$1 \le n, b, a \le 2 \cdot 10^5$$$) — the robot's destination point, the battery capacity and the accumulator capacity, respectively. The second line of the input contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$0 \le s_i \le 1$$$), where $$$s_i$$$ is $$$1$$$ if the $$$i$$$-th segment of distance is exposed to sunlight, and $$$0$$$ otherwise.

Print one integer — the maximum number of segments the robot can pass if you control him optimally.

NoteIn the first example the robot can go through the first segment using the accumulator, and charge levels become $$$b=2$$$ and $$$a=0$$$. The second segment can be passed using the battery, and charge levels become $$$b=1$$$ and $$$a=1$$$. The third segment can be passed using the accumulator, and charge levels become $$$b=1$$$ and $$$a=0$$$. The fourth segment can be passed using the battery, and charge levels become $$$b=0$$$ and $$$a=1$$$. And the fifth segment can be passed using the accumulator.In the second example the robot can go through the maximum number of segments using battery two times and accumulator one time in any order.

N, B, A = gets.split.map(&:to_i)
S = gets.chomp.split

ans = 0

b = B
a = A

S.each do |s|
  case s
  when '0'
    if a > 0
      a -= 1
    elsif b > 0
      b -= 1
    else
      break
    end
  when '1'
    if b > 0 && a < A
      b -= 1
      a += 1
    elsif a > 0
      a -= 1
    elsif b > 0
      b -= 1
    else
      break
    end
  end

  ans += 1
end

puts ans

n,a,b = gets.split.map(&:to_i)
s = gets.split.map(&:to_i)
c = b*1
n.times do |i|
    if s[i] == 0
        if c > 0
            c -= 1
        elsif a > 0
            a -= 1
        else
            puts i
            exit
        end
    else
        if a > 0 && c < b
            a -= 1
            c += 1
        elsif c > 0
            c -= 1
        else
            puts i
            exit
        end
    end
end
puts n

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


A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $$$k$$$-balanced if every substring of size $$$k$$$ of this bitstring has an equal amount of 0 and 1 characters ($$$\frac{k}{2}$$$ of each).You are given an integer $$$k$$$ and a string $$$s$$$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $$$k$$$-balanced bitstring by replacing every ? characters in $$$s$$$ with either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 3 \cdot 10^5$$$, $$$k$$$ is even)  — the length of the string and the parameter for a balanced bitstring. The next line contains the string $$$s$$$ ($$$|s| = n$$$). It is given that $$$s$$$ consists of only 0, 1, and ?. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print YES if we can replace every ? in $$$s$$$ with 0 or 1 such that the resulting bitstring is $$$k$$$-balanced, or NO if it is not possible.

NoteFor the first test case, the string is already a $$$4$$$-balanced bitstring.For the second test case, the string can be transformed into 101.For the fourth test case, the string can be transformed into 0110.For the fifth test case, the string can be transformed into 1100110.

gets.to_i.times{k=gets.split[1].to_i
a=[nil]*k
puts gets.chop.chars.zip(0..).map{|x,i|i%=k;x==??||a[i]==x||!a[i]&&a[i]=x}.all?&&[?0,?1].map{|x|a.take(k).count x}.max<=k/2 ?"YES":"NO"}


There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one.  At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints.

The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists.

Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them.

NoteThe first test sample is the one in the picture.

n = gets.to_i
path = gets.chomp.split('')
s = nil
r = nil
t = nil
l = nil
0.upto(n-1) do |i|
	s = i+1 if(path[i]=='R')&&(s.nil?)
       	r = i+1 if(path[i]!='R')&&(!s.nil?)&&(r.nil?)
	t = i if(path[i]=='L')&&(t.nil?)
	l = i if(path[i]!='L')&&(!t.nil?)&&(l.nil?)
end
s = l if s.nil?
t = r if t.nil?
puts "#{s} #{t}"

n = gets.chomp.to_i
path = gets.chomp
ls = []
rs = []
n.times do |i|
    c = path[i]
    ls << i + 1 if c == 'L'
    rs << i + 1 if c == 'R'
end
s = t = 0
if ls.length == 0
    s = rs.min
    t = rs.max + 1
elsif rs.length == 0
    s = ls.max
    t = ls.min - 1
else
    s = rs.min
    t = rs.max + 1
end
puts "#{s} #{t}"

gets.to_i
s = gets
if s.index('R').nil?
  b = s.index('L')
  a = s.index('.', b)
elsif s.index('L').nil?
  a = s.index('R') + 1
  b = s.index('.', a - 1) + 1
else
  a = s.index('R') + 1
  b = s.index('L')
end
puts "#{a} #{b}"

n=gets.to_i
a=gets.chomp.split('')
s,t=a.rindex('R'),a.index('L')
puts s ? "#{s+1} #{s+2}" : "#{t+1} #{t}"

n = gets.to_i
arr = gets.split("")
l_index = arr.index("L")
r_index = arr.index("R")
l_last_index = arr.rindex("L")
r_last_index = arr.rindex("R")

ans = false

unless l_index
	s,t = r_index,r_last_index+1
	ans = true
end

unless r_index
	s,t = l_last_index,l_index - 1
	ans = true
end

if !ans
	s,t = r_index,r_last_index
end

puts "#{s+1} #{t+1}"

#!/usr/bin/ruby -w
n = gets
s = gets
i = 0
while s[i] == '.' do
    i = i + 1
end
print i + 1
print " "
while s[i] != 'L' && s[i] != '.' do
    i = i + 1
end
if(s[i] == '.')
print i + 1
else
    print i
end
puts

n = gets.to_i
blocks = gets.chomp
s = blocks.index("R")
if s
    puts [s+1, n-blocks.reverse.index("R")+1].join(" ")
    exit
end
t = blocks.index("L")
if t
    puts [n-blocks.reverse.index("L"),t].join(" ")
end

l=gets.to_i
s=gets.split(//)
i=0
x=-1
y=-1
while (i<l) do
  if (s[i]=='R') then y=i; end
  i+=1
end
i=l-1
while (i>=0) do
  if (s[i]=='L') then x=i; end
  i-=1
end
if (x==-1) then print(y+1," ",y+2,"\n");
else
  if (y==-1) then print(x+1," ",x,"\n");
  else print(x+1," ",x+1,"\n");
  end
end

gets # Skip the first line
fp = gets.chomp
if fp.include?('R')
  if fp.include?('L')
    puts "#{fp.index('R') + 1} #{fp.rindex('R') + 1}"
  else
    puts "#{fp.index('R') + 1} #{fp.rindex('R') + 2}"
  end
else
  puts "#{fp.rindex('L') + 1} #{fp.index('L')}"
end

n=gets.to_i
a=gets.chomp.split('')
en,st=0,0
for i in 0...a.length
	break if a[i]!='.'
end
if a[i]=='R'
	st=i
	i+=1 while a[i]=='R'
	en = (a[i]=='L')? i-1 : i
else
	en=i-1
	i+=1 while a[i]=='L'
	st=i-1
end
puts "#{st+1} #{en+1}"

n = gets.to_i
moves = gets
strs = moves.index 'R'
ends = moves.rindex 'R'
if strs.nil?
    strs = moves.rindex 'L'
    ends = moves.index 'L'
    ends -= 1
else
    ends += 1
end
puts "#{strs + 1} #{ends + 1}"

def run
  n = $stdin.gets.to_i
  str = $stdin.gets.split(//)

  s = str.rindex('R')
  t = str.index('L')

  if s != nil
    puts "#{s + 1} #{s + 2}"
  else
    puts "#{t + 1} #{t}"
  end
end

run if $0 == __FILE__

class A
  def initialize
    n = $stdin.gets.chomp.to_i
    step = $stdin.gets.chomp.split('')

    s = t = 0
    s_flag = true
    t_flag = true
    r_max = 0
    l_max = 0

    step.each_with_index do |ch, index|
      if ch == 'R' && s_flag
        s = index+1
        s_flag = false
      elsif ch == 'L' && t_flag
        t = index
        t_flag = false
      end

      if ch == 'R'
        r_max = index+1
      elsif ch == 'L'
        l_max = index+1
      end
    end

    if s_flag
      s = l_max
    end

    if t_flag
      t = r_max + 1
    end

    puts "#{s} #{t}"
  end
end

a = A.new

n = gets.chomp.to_i
path = gets.chomp
s = t = 0
dir = nil
n.times do |c|
    s = c + 1 if path[c] != '.' && s == 0
    dir = path[c] if dir.nil? && path[c] != '.'
    t = c - 1 if !dir.nil? && path[c] != '.' && dir != path[c]
end
puts "#{s} #{t}"

gets.chomp.to_i
path = gets.chomp
index = 0
pos = []
finish = false
while !finish
    c = path[index]
    if c != '.'
        if c == 'R'
            index += 1
            if !pos.include?( index )
                pos << index
            else
                finish = true
            end
        else
            index -= 1
            if !pos.include?( index )
                pos << index
            else
                finish = true
            end
        end
        next
    end
    index += 1
end
s = pos.min
t = pos.max
puts "#{s} #{t}"

n = gets.chomp.to_i
path = gets.chomp
ls = []
rs = []
n.times do |i|
    c = path[i]
    ls << i + 1 if c == 'L'
    rs << i + 1 if c == 'R'
end
s = t = 0
if ls.length == 0
    s = rs.min
    t = rs.max
elsif rs.length == 0
    s = ls.max
    t = ls.min
else
    s = rs.min
    t = rs.max
end
puts "#{s} #{t}"

n = gets.to_i
arr = gets.split("")
l_index = arr.index("L")
r_index = arr.index("R")
l_last_index = arr.rindex("L")
r_last_index = arr.rindex("R")

ans = false

unless l_index
	s,t = r_index,r_last_index
	ans = true
end

unless r_index
	s,t = l_last_index,l_index
	ans = true
end

if !ans
	s,t = r_index,r_last_index
end

puts "#{s+1} #{t+1}"

n = gets.to_i
arr = gets.split("")
l_index = arr.index("L")
r_index = arr.index("R")
l_last_index = arr.rindex("L")
r_last_index = arr.rindex("R")

ans = false

unless l_index
	s,t = r_index,r_last_index+1
	ans = true
end

unless r_index
	s,t = l_last_index-1,l_index
	ans = true
end

if !ans
	s,t = r_index,r_last_index
end

puts "#{s+1} #{t+1}"

n = gets.to_i
arr = gets.split("")
l_index = arr.index("L")
r_index = arr.index("R")
l_last_index = arr.rindex("L")
r_last_index = arr.rindex("R")

ans = false

unless l_index
	s,t = r_index,r_last_index+1
	ans = true
end

unless r_index
	s,t = l_last_index,l_index
	ans = true
end

if !ans
	s,t = r_index,r_last_index
end

puts "#{s+1} #{t+1}"

l=gets.to_i
s=gets.split(//)
i=0
x=-1
y=-1
while (i<l) do
  if (s[i]=='R') then y=i; end
  i+=1
end
i=l-1
while (i>=0) do
  if (s[i]=='L') then x=i; end
  i-=1
end
if (x==-1) then print(y+1," ",y+1,"\n");
else print(x+1," ",x+1,"\n");end

l=gets.to_i
s=gets.split(//)
i=0
x=-1
y=-1
while (i<l) do
  if (s[i]=='R') then y=i; end
  i+=1
end
i=l-1
while (i>=0) do
  if (s[i]=='L') then x=i; end
  i-=1
end
if (x==-1) then print(y+1," ",y,"\n");
else
  if (y==-1) then print(x+1," ",x+2,"\n");
  else print(x+1," ",x+1,"\n");
  end
end

n=gets.to_i
a=gets.chomp.split('')
b=[]
a.each do |i|
	b<<i if i!='.'
end
if b.uniq.count==1
	if b.first=='R'
		puts "#{a.index('R')+1} #{a.rindex('R')+1}"
	elsif b.first=='L'
		puts "#{a.rindex('L')+1} #{a.index('L')+1}"
	end
else
	puts "#{a.index('R')+1} #{a.index('L')+1}"
end

n = gets.to_i
moves = gets
if moves.index 'L'
    strs = moves.index 'R'
    ends = moves.rindex 'R'
else
    strs = moves.rindex 'R'
    ends = moves.index 'R'
end
if strs.nil?
    strs = moves.index 'L'
    ends = moves.rindex 'L'
end
puts "#{strs + 1} #{ends + 1}"

n = gets.to_i
moves = gets
strs = moves.index 'R'
ends = moves.rindex 'R'
if strs.nil?
    strs = moves.index 'L'
    ends = moves.rindex 'L'
end
puts "#{strs + 1} #{ends + 1}"

n = gets.to_i
moves = gets
strs = moves.index 'R'
ends = moves.rindex 'R'
if strs.nil?
    strs = moves.index 'L'
    ends = moves.rindex 'L'
    ends -= 1
else
    ends += 1
end
puts "#{strs + 1} #{ends + 1}"

def run
  n = $stdin.gets.to_i
  str = $stdin.gets.split(//)

  s = 0, t = -1
  str.each_with_index do |item, index|
    s = index if item == 'R'
    t = index if item == 'L' and t == -1
  end

  puts "#{s} #{t}"
end

run if $0 == __FILE__

class A
  def initialize
    n = $stdin.gets.chomp.to_i
    step = $stdin.gets.chomp.split('')

    s = t = 0
    s_flag = true
    t_flag = true

    step.each_with_index do |ch, index|
      if ch == 'R' && s_flag
        s = index+1
        s_flag = false
      elsif ch == 'L' && t_flag
        t = index
        t_flag = false
      end
    end

    puts "#{s} #{t}"
  end
end

a = A.new

n = gets.to_i
path = gets.chomp.split('')
s = nil
r = nil
t = nil
l = nil
0.upto(n-1) do |i|
	s = i+1 if(path[i]=='R')&&(s.nil?)
       	r = i+1 if(path[i]!='R')&&(!s.nil?)
	t = i if(path[i]=='L')&&(t.nil?)
	l = i if(path[i]!='L')&&(!t.nil?)
end
s = l if s.nil?
t = r if t.nil?
puts "#{s} #{t}"


You are given a pair of integers $$$(a, b)$$$ and an integer $$$x$$$.You can change the pair in two different ways:   set (assign) $$$a := |a - b|$$$;  set (assign) $$$b := |a - b|$$$,  where $$$|a - b|$$$ is the absolute difference between $$$a$$$ and $$$b$$$.The pair $$$(a, b)$$$ is called $$$x$$$-magic if $$$x$$$ is obtainable either as $$$a$$$ or as $$$b$$$ using only the given operations (i.e. the pair $$$(a, b)$$$ is $$$x$$$-magic if $$$a = x$$$ or $$$b = x$$$ after some number of operations applied). You can apply the operations any number of times (even zero).Your task is to find out if the pair $$$(a, b)$$$ is $$$x$$$-magic or not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains three integers $$$a$$$, $$$b$$$ and $$$x$$$ ($$$1 \le a, b, x \le 10^{18}$$$).

For the $$$i$$$-th test case, print YES if the corresponding pair $$$(a, b)$$$ is $$$x$$$-magic and NO otherwise.

main = -> {
  t = int
  t.times do
    a, b, x = ints
    a, b = [a, b].minmax
    yesno solve(a, b, x)
  end
}

def solve(a, b, x)
  # STDERR.puts "(%d, %d, %d)" % [a, b, x]
  return true if a == x or b == x
  return false if a == 0 or b == 0
  a, b = [a, b].minmax
  c = b % a
  return true if (b - x) % a == 0 and b >= x
  solve(a, c, x)
end

# def solve(a, b, x)
#   return false if x > a and x > b
#   return true if a == x or b == x
#   return false if a == 0 or b == 0
#   a, b = [a, b].minmax
#   return true if (b - x) % a == 0
#   c = b % a
#   solve(a, c, x) or solve(b, c, x)
# end

DEBUG = true
MOD = 10**9+7
YESNO = %w(NO YES)
INF = 10**9

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]

main = -> {
  t = int
  t.times do
    a, b, x = ints
    a, b = [a, b].minmax
    yesno solve(a, b, x)
  end
}

def solve(a, b, x)
  return false if x > a and x > b
  return true if a == x or b == x
  return false if a == 0 or b == 0
  a, b = [a, b].minmax
  return true if (b - x) % a == 0
  c = b % a
  solve(a, c, x) or solve(b, c, x)
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(NO YES)
INF = 10**9

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]

main = -> {
  t = int
  t.times do
    a, b, x = ints
    yesno solve(a, b, x)
  end
}

def solve(a, b, x)
  return false if x > a and x > b
  return true if a == x or b == x
  a, b = [a, b].minmax
  while a > 0 and b > 0
    return true if (b - x) % a == 0
    c = b - a
    return true if c == x
    a, b = [a, c].minmax
  end
  false
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(NO YES)
INF = 10**9

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]


Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.

The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.

In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.

class Solution
  def initialize
    @n = gets.to_i
    @a = gets.split.map(&:to_i)
    @b = gets.split.map(&:to_i)
    @m = []
  end

  def move(i)
    return if @a[i] == @b[i]
    j = i
    j += 1 while @b[j] != @a[i]
    j.downto(i+1).each do |k|
      @m << k-1
      @b[k-1], @b[k] = @b[k], @b[k-1]
    end
  end

  def solve
    (0...@n).each {|i| move(i)}
    puts @m.size
    @m.each {|x| printf("%d %d\n", x+1, x+2)}
  end
end

solution = Solution.new
solution.solve

n=gets.to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
z=[]
n.times{|i|
	j=i;
	j+=1 while a[i]!=b[j];
	j.downto(i+1){|k|
		b[k],b[k-1]=b[k-1],b[k]
		z<<[k,k+1]
	}
}
p z.size
z.each{|x,y|
	print "#{x} #{y}\n"
}


One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated – it consists of n brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly:   It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains).  There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false. If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid.

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n, a ≠ b).

The output consists of one line, containing either yes or no depending on whether the nervous system is valid.

nodes, edges = gets.split(' ').map(&:to_i)
g = {}
edges.times do
  from, to = gets.split(' ').map(&:to_i)
  g[from] ||= []
  g[from].push(to)
  g[to] ||= []
  g[to].push(from)
end

$g = g
$visited = {}

def dfs(node, prev)
  $visited[node] = true

  ($g[node] || []).each do |nxt|
    next if nxt == prev

    if $visited[nxt]
      puts 'no'
      exit
    else
      dfs(nxt, node)
    end
  end
end

dfs($g.first.first, 0)

if $visited.size == $g.size
  puts 'yes'
else
  puts 'no'
end


The Bitlandians are quite weird people. They have very peculiar customs.As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000.Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500.Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.

The first line contains integer n (1 ≤ n ≤ 106) — the number of eggs. Next n lines contain two integers ai and gi each (0 ≤ ai, gi ≤ 1000; ai + gi = 1000): ai is the price said by A. for the i-th egg and gi is the price said by G. for the i-th egg.

If it is impossible to assign the painting, print "-1" (without quotes). Otherwise print a string, consisting of n letters "G" and "A". The i-th letter of this string should represent the child who will get the i-th egg in the required distribution. Letter "A" represents A. and letter "G" represents G. If we denote the money Uncle J. must pay A. for the painting as Sa, and the money Uncle J. must pay G. for the painting as Sg, then this inequality must hold: |Sa  -  Sg|  ≤  500.  If there are several solutions, you are allowed to print any of them.

s=0
n=gets.to_i
n.times do
	a,b=gets.chomp.split.map(&:to_i)
	s+=a
end
i=n-(s+499)/1000
puts "A"*i + "G"*(n-i)

n = gets.to_i
ta = tb = 0
n.times do
    a, b = gets.split.map{|i| i.to_i}
    ta += a
    tb += b
end
if ta % 1000 <= 500
    n.times do |i|
       if i < ta / 1000 then  print 'G'
       else print 'A'
       end
    end
elsif tb % 1000 <= 500
    n.times do |i|
        if i < tb / 1000 then print 'A'
        else print 'G'
        end
    end
else
    puts -1
end

def run
  n = $stdin.gets.to_i
  sum = 0
  $stdin.readlines.each do |line|
    a, g = line.split.map(&:to_i)
    sum += a
  end

  i = n - (sum + 499) / 1000
  puts "A" * i + "G" * (n - i)
end

run if $0 == __FILE__

n = gets.to_i

# a = []
# g = []

answer = ''
a_cur = 0
g_cur = 0

n.times do |i|
	a, g = gets.split(' ').collect!{|i| i.to_i}
	if (a_cur + a - g_cur).abs <= 500
		answer << "A"
		a_cur += a
	else
		answer << "G"
		g_cur += g
	end
end

# answer = -1  if (a_cur - g_cur).abs > 500

print answer

n = gets.to_i
s_a = 0
s_g = 0
A = "A"
ans = ""
# ans = A*n
# if n < 1000
G = "G"
n.times do |i|
	a,b = gets.split(" ")
	a = a.to_i
	b = b.to_i

	x = s_a + a
	if (x - s_g) <= 500
		s_a = x
		ans << A
	else
		s_g += b
		ans << G
	end
end

if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s = 0
(1..n).each {
	a,g = gets.chomp.split(" ").collect! {|x| x.to_i}
	s += a
}

p = s/1000.0
if p>=p.floor+0.5
	k = p.floor+1
else
	k = p.floor
end

res = "G"*k+"A"*(n-k)

puts res

n = gets.to_i
sa = 0
sg = 0
(0...n).each do |i|
    a, g = gets.split.collect{|i| i.to_i}
    if (sa+a-sg).abs <= 500
        sa += a
        print "A"
    else
        sg += g
        print "G"
    end
end
print "\n"

def run
  n = $stdin.gets
  sa = 0
  sg = 0
  ret = ""
  $stdin.readlines.each do |line|
    a, g = line.split.map(&:to_i)
    if sa <= sg + 500
      sa += a
      ret += "A"
    else
      sg += g
      ret += "G"
    end
  end

  if (sa - sg).abs <= 500
    puts ret
  else
    puts "-1"
  end
end

run if $0 == __FILE__

def run
  n = $stdin.gets.to_i
  sum = 0
  $stdin.readlines.each do |line|
    a, g = line.split.map(&:to_i)
    sum += a
  end

  i = n - (sum + 499) / 1000
  puts "A" * i + "G" * (n - 1)
end

run if $0 == __FILE__

def run
  n = $stdin.gets
  sa = 0
  sg = 0
  ret = ""
  $stdin.readlines.each do |line|
    a, g = line.split.map(&:to_i)
    if sa < sg
      sa += a
      ret += "A"
    else
      sg += g
      ret += "G"
    end
  end

  if (sa - sg).abs <= 500
    puts ret
  else
    puts "-1"
  end
end

run if $0 == __FILE__

def run
  n = $stdin.gets
  sa = 0
  sg = 0
  ret = ""
  $stdin.readlines.each do |line|
    a, g = line.split.map(&:to_i)
    if sa <= sg
      sa += a
      ret += "A"
    else
      sg += g
      ret += "G"
    end
  end

  if (sa - sg).abs <= 500
    puts ret
  else
    puts "-1"
  end
end

run if $0 == __FILE__

n = gets.to_i

a = []
g = []

a_sum = 0
g_sum = 0

n.times do |i|
	a[i], g[i] = gets.split(' ').collect!{|i| i.to_i}
	a_sum += a[i]
	g_sum += g[i]
end

# a_sr = a_sum / n
# g_sr = g_sum / n

answer = ''
a_cur = 0
g_cur = 0

# n.times do |i|
# 	if a_cur + a[i] < g_sr
# 		answer << "A"
# 		a_cur += a[i]
# 	elsif g_cur + g[i] < a_sr
# 		answer << "G"
# 		g_cur += g[i]
# 	elsif (a_cur + a_sum - g_cur - g_sum + g[i]).abs <= 500
# 		answer << "A"
# 		a_cur += a[i]
# 	elsif (g_cur + g_sum - a_cur -a_sum + a[i]).abs <= 500
# 		answer << "G"
# 		g_cur += g[i]
# 	else
# 		answer = -1
# 		break
# 	end

# 	a_sum -= a[i]
# 	g_sum -= g[i]
# end

n.times do |i|
	a_sum -= a[i]
	g_sum -= g[i]
	if (a_cur + a[i] + a_sum - g_cur - g_sum).abs <= 500
		answer << "A"
		a_cur += a[i]
	else
		answer << "G"
		g_cur += g[i]
	end
end
# print answer
answer = -1  if (a_cur - g_cur).abs > 500

print answer

n = gets.to_i

a = []
g = []

# a_sum = 0
# g_sum = 0

answer = ''
a_cur = 0
g_cur = 0

n.times do |i|
	a[i], g[i] = gets.split(' ').collect!{|i| i.to_i}
	# a_sum += a[i]
	# g_sum += g[i]

	if g_cur >= a_cur
		answer << "A"
		a_cur += a[i]
	else
		answer << "G"
		g_cur += g[i]
	end
end

answer = -1  if (a_cur - g_cur).abs > 500

print answer

n = gets.to_i

a = []
g = []

a_sum = 0
g_sum = 0
n.times do |i|
	a[i], g[i] = gets.split(' ').collect!{|i| i.to_i}
	a_sum += a[i]
	g_sum += g[i]
end

answer = -1

if (a_sum/n - g_sum/n).abs <= 500
	answer = ''
	a.sort!.reverse!
	g.sort!.reverse!
	a_cur = 0
	g_cur = 0

	n.times do |i|
		if g_cur >= a_cur
			answer << "A"
			a_cur += a[i]
		else
			answer << "G"
			g_cur += g[i]
		end
	end
end

print answer

n = gets.to_i

a = []
g = []

a_sum = 0
g_sum = 0

n.times do |i|
	a[i], g[i] = gets.split(' ').collect!{|i| i.to_i}
	a_sum += a[i]
	g_sum += g[i]
end

a_sr = a_sum / n
g_sr = g_sum / n

answer = ''
a_cur = 0
g_cur = 0

n.times do |i|
	if a_cur + a[i] < g_sr
		answer << "A"
		a_cur += a[i]
	elsif g_cur + g[i] < a_sr
		answer << "G"
		g_cur += g[i]
	elsif (a_cur + a_sum - g_cur - g_sum + g[i]).abs <= 500
		answer << "A"
		a_cur += a[i]
	elsif (g_cur + g_sum - a_cur -a_sum + a[i]).abs <= 500
		answer << "G"
		g_cur += g[i]
	else
		answer = -1
		break
	end

	a_sum -= a[i]
	g_sum -= g[i]
end

answer = -1  if (a_cur - g_cur).abs > 500

print answer

n = gets.to_i
s_a = 0
s_g = 0
ans = ""
if n < 1000
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		ans << "A"
	else
		s_g += b
		ans << "G"
	end
end
else
	n.times do
		a,b = gets.split(" ").map(&:to_i)
		(s_a + a - s_g) <= 500
	end

end
if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s_a = 0
s_g = 0
ans = "A"*n
if n < 1000
n.times do |i|
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		# ans << "A"
	else
		s_g += b
		ans[i] = "G"
	end
end
else
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		# ans << "A"
	else
		s_g += b
		ans << "G"
	end
end

end
if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s_a = 0
s_g = 0
ans = ""
if n < 1000
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		ans << "A"
	else
		s_g += b
		ans << "G"
	end
end
else
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		# ans << "A"
	else
		s_g += b
		ans << "G"
	end
end

end
if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s_a = 0
s_g = 0
ans = ""
if n < 1000
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		ans << "A"
	else
		s_g += b
		ans << "G"
	end
end
else
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		# ans << "A"
	else
		s_g += b
		# ans << "G"
	end
end

end
if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s_a = 0
s_g = 0
ans = ""
if n < 1000
n.times do
	a,b = gets.split(" ").map(&:to_i)
	if (s_a + a - s_g) <= 500
		s_a += a
		ans << "A"
	else
		s_g += b
		ans << "G"
	end
end
else
	n.times do
		a,b = gets.split(" ").map(&:to_i)
	end

end
if (s_a - s_g).abs <= 500
	puts ans
else
	puts "-1"
end

n = gets.to_i
s = 0
(1..n).each {
	a,g = gets.chomp.split(" ").collect! {|x| x.to_i}
	s += a
}

p = s/1000.0
if p>=p.floor+0.5
	k = p.floor+1
else
	k = p.floor
end

res = "A"*k+"G"*(n-k)

puts res

n = gets.to_i
a = Array.new
b = Array.new
ans = Array.new(n)
(1..n).each do
    tmp = gets.split.collect{|i| i.to_i}
    a.push(tmp[0])
    b.push(tmp[1])
end
diff = (0...n).collect{|i| [a[i]-b[i],i]}.sort
tmp = 0
diff.each do |i|
    if (tmp+i[0]).abs <= (tmp-i[0]).abs
        if i[0] <= 0
            ans[i[1]] = "A"
        else
            ans[i[1]] = "G"
        end
        tmp += i[0]
    else
        if i[0] <= 0
            ans[i[1]] = "G"
        else
            ans[i[1]] = "A"
        end
        tmp -= i[0]
    end
end
if tmp.abs <= 500
    puts ans.join
else
    puts "-1"
end


As it has been found out recently, all the Berland's current economical state can be described using a simple table n × m in size. n — the number of days in each Berland month, m — the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information — the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p.

The first line contains integers n and m (1 ≤ n, m ≤ 1000). The second line contains the integer k (0 ≤ k < max(n, m)) — the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 ≤ a ≤ n) — the number of the table row, b (1 ≤ b ≤ m) — the number of the column, c — the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 ≤ p ≤ 109 + 7).

Print the number of different tables that could conform to the preserved data modulo p.

# 2**n % p
def remainder(n, p)
  return 1 if n == 0
  m = n / 2
  r = (remainder(m, p) * remainder(m, p)) % p
  return (n % 2 == 0 ? r: (r * 2) % p)
end

n, m = gets.split.map(&:to_i)
# for simplicity, assume n >= m
transpose = false
if n < m
  n, m = m, n
  transpose = true
end

plus_one = Array.new(n, 0)
minus_one = Array.new(n, 0)

k = gets.to_i
(1..k).each do
  a, b, c = gets.split.map(&:to_i)
  a, b = b, a if transpose
  if c > 0
    plus_one[a-1] += 1
  else
    minus_one[a-1] += 1
  end
end
p = gets.to_i

if (n + m) % 2 == 1
  puts 0
  exit
end

exponent = - m + 1
(0...n).each do |i|
  if (plus_one[i] + minus_one[i] == m and minus_one[i] % 2 == 0)
    puts 0
    exit
  else
    exponent += [m - plus_one[i] - minus_one[i] - 1, 0].max
  end
end

puts(remainder(exponent, p))

# 2**n % p
def remainder(n, p)
  return 1 if n == 0
  m = n / 2
  r = (remainder(m, p) * remainder(m, p)) % p
  return (n % 2 == 0 ? r: (r * 2) % p)
end

n, m = gets.split.map(&:to_i)
k = gets.to_i
has_one = false
(1..k).each do
  a, b, c = gets.split.map(&:to_i)
  has_one = true if c == 1
end
p = gets.to_i
if n > 1 and m > 1
  puts(remainder((n-1)*(m-1)-k, p))
else
  if has_one
    result = 0
  else
    result = ((n + m - 1) % 2 == 0 ? 0 : 1)
  end
  puts result
end


Nastia has received an array of $$$n$$$ positive integers as a gift.She calls such an array $$$a$$$ good that for all $$$i$$$ ($$$2 \le i \le n$$$) takes place $$$gcd(a_{i - 1}, a_{i}) = 1$$$, where $$$gcd(u, v)$$$ denotes the greatest common divisor (GCD) of integers $$$u$$$ and $$$v$$$.You can perform the operation: select two different indices $$$i, j$$$ ($$$1 \le i, j \le n$$$, $$$i \neq j$$$) and two integers $$$x, y$$$ ($$$1 \le x, y \le 2 \cdot 10^9$$$) so that $$$\min{(a_i, a_j)} = \min{(x, y)}$$$. Then change $$$a_i$$$ to $$$x$$$ and $$$a_j$$$ to $$$y$$$.The girl asks you to make the array good using at most $$$n$$$ operations.It can be proven that this is always possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_{n}$$$ ($$$1 \le a_i \le 10^9$$$) — the array which Nastia has received as a gift. It's guaranteed that the sum of $$$n$$$ in one test doesn't exceed $$$2 \cdot 10^5$$$.

For each of $$$t$$$ test cases print a single integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of operations. You don't need to minimize this number. In each of the next $$$k$$$ lines print $$$4$$$ integers $$$i$$$, $$$j$$$, $$$x$$$, $$$y$$$ ($$$1 \le i \neq j \le n$$$, $$$1 \le x, y \le 2 \cdot 10^9$$$) so that $$$\min{(a_i, a_j)} = \min{(x, y)}$$$ — in this manner you replace $$$a_i$$$ with $$$x$$$ and $$$a_j$$$ with $$$y$$$. If there are multiple answers, print any.

NoteConsider the first test case.Initially $$$a = [9, 6, 3, 11, 15]$$$.In the first operation replace $$$a_1$$$ with $$$11$$$ and $$$a_5$$$ with $$$9$$$. It's valid, because $$$\min{(a_1, a_5)} = \min{(11, 9)} = 9$$$.After this $$$a = [11, 6, 3, 11, 9]$$$.In the second operation replace $$$a_2$$$ with $$$7$$$ and $$$a_5$$$ with $$$6$$$. It's valid, because $$$\min{(a_2, a_5)} = \min{(7, 6)} = 6$$$.After this $$$a = [11, 7, 3, 11, 6]$$$ — a good array.In the second test case, the initial array is already good.

$, = " "
gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    mn, pos = 1E9.to_i + 7, -1
    n.times do |i|
        if a[i] < mn
            mn = a[i]
            pos = i
        end
    end
    puts n - 1
    n.times do |i|
        next if i == pos
        print pos + 1, i + 1, mn, mn + (i - pos).abs, "\n"
    end
end

$, = " "
gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    mn, pos = 1E9.to_i + 7, -1
    n.times do |i|
        if a[i] < mn
            mn = a[i]
            pos = i
        end
    end
    puts(n - 1)
    n.times do |i|
        next if i == pos
        print pos + 1, i + 1, mn, mn + (i - pos).abs, "\n"
    end
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.strip.split.map {|x| x.to_i }

  minv = a.min
  minv_i = a.find_index(minv)

  x = minv + 1
  while minv.gcd(x) != 1
    x += 1
  end

  printf("%d\n", n - 1)
  0.upto(n - 1) do |i|
    next if i == minv_i
    if (i % 2) != (minv_i) % 2
      printf("%d %d %d %d\n", i + 1, minv_i + 1, x, minv)
    else
      printf("%d %d %d %d\n", i + 1, minv_i + 1, minv, minv)
    end
  end
end

$, = " "
gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    mn, pos = 1E9.to_i + 7, -1
    n.times do |i|
        if a[i] < mn
            mn = a[i]
            pos = i
        end
    end
    n.times do |i|
        next if i == pos
        print pos + 1, i + 1, mn, mn + (i - pos).abs, "\n"
    end
end


Vasya is a Greencode wildlife preservation society proponent. One day he found an empty field nobody owned, divided it into n × m squares and decided to plant a forest there. Vasya will plant nm trees of all different heights from 1 to nm. For his forest to look more natural he wants any two trees growing in the side neighbouring squares to have the absolute value of difference in heights to be strictly more than 1. Help Vasya: make the plan of the forest planting for which this condition is fulfilled.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — the number of rows and columns on Vasya's field

If there's no solution, print -1. Otherwise, print n lines containing m numbers each — the trees' planting plan. In every square of the plan the height of a tree that should be planted on this square should be written. If there are several solutions to that problem, print any of them.


Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns — from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (xk, yk).The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like.  Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!

The first line of the input contains fix integers n, m, x, y, z, p (1 ≤ n, m ≤ 109; 0 ≤ x, y, z ≤ 109; 1 ≤ p ≤ 105). Each of the following p lines contains two integers xk, yk (1 ≤ xk ≤ n; 1 ≤ yk ≤ m) — the initial coordinates of the k-th candy. Two candies can lie on the same cell.

For each of the p candies, print on a single line its space-separated new coordinates.

NoteJust for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix:QWER      REWQ ASDF  ->  FDSAZXCV      VCXZ

def ans(i,j,n,m,c,r,a)
    c.times{ i,j,n,m = j,n+1-i,m,n }
    if r!=0
        j = m+1-j
    end
    a.times { i,j,n,m = m+1-j,i,m,n }
    puts "#{i} #{j}"
end
n,m,x,y,z,p = gets.split.map(&:to_i)
p.times do | t |
    i,j = gets.split.map(&:to_i)
    ans(i,j,n,m,x%4,y%2,z%4)
end

def ans(i,j,n,m,c,r,a)

    while c>0
        t = i
        i = j
        j = n+1-t

        t = m
        m = n
        n = t

        c = c-1
    end

    if r!=0
        j = m+1-j
    end

    while a>0
        t = j
        j = i
        i = m+1-t

        t = m
        m = n
        n = t

        a = a-1
    end
    print i.to_s+' '+j.to_s+"\n"
end

n,m,x,y,z,p = gets.split.map(&:to_i)

p.times do | t |
    i,j = gets.split.map(&:to_i)
    ans(i,j,n,m,x%4,y%2,z%4)
end

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

n, m, k1, k2, k3, t = read_ints
k1 %= 4
k3 %= 4
k2 %= 2
t.times do
  x, y = read_ints
  h, w = n, m
  k1.times do
    x, y = y, h - x + 1
    h, w = w, h
  end
  k2.times { y = w - y + 1 }
  k3.times do
    x, y = w - y + 1, x
    h, w = w, h
  end
  puts "#{x} #{y}"
end

n,m,x,y,z,p=gets.split.map(&:to_i)
a=[]
b=[]
p.times{
	tx,ty=gets.split.map(&:to_i)
	a<<tx
	b<<ty
}
x%=4
x.times{
	p.times{ |i|
		a[i],b[i]=b[i],n-a[i]+1
	}
	n,m=m,n
}
y%=2
if y>0
	p.times{ |i|
		b[i]=m-b[i]+1
	}
end
z%=4
z.times{
	p.times{ |i|
		a[i],b[i]=m-b[i]+1,a[i]
	}
	n,m=m,n
}
p.times{ |i|
		puts "#{a[i]} #{b[i]}"
	}

def ans(i,j,n,m,c,r,a)

    while c>0
        t = j
        j = n+1-i
        i = t

        t = m
        m = n
        n = t

        c = c-1
    end

    if r
        j = m+1-j
    end

    while a>0
        t = i
        i = m+1-j
        j = t

        t = m
        m = n
        n = t

        a = a-1
    end
    puts i.to_s+' '+j.to_s
end

n,m,x,y,z,p = gets.split.map(&:to_i)

p.times do | t |
    i,j = gets.split.map(&:to_i)
    ans(i,j,n,m,x%4,y%2,z%4)
end

def ans(i,j,n,m,c,r,a)
    c.times{ i,j = j,n+1-i }
    if r!=0
        j = m+1-j
    end
    a.times{ i,j = m+1-j,i }
    puts "#{i} #{j}"
end
n,m,x,y,z,p = gets.split.map(&:to_i)
p.times do | t |
    i,j = gets.split.map(&:to_i)
    ans(i,j,n,m,x%4,y%2,z%4)
end

def ans(i,j,n,m,c,r,a)

    while c>0
        t = i
        i = m+1-j
        j = t

        t = m
        m = n
        n = t

        c = c-1
    end

    if r!=0
        j = m+1-j
    end

    while a>0
        t = j
        j = n+1-i
        i = t

        t = m
        m = n
        n = t

        a = a-1
    end
    print i.to_s+' '+j.to_s+"\n"
end

n,m,x,y,z,p = gets.split.map(&:to_i)

p.times do | t |
    i,j = gets.split.map(&:to_i)
    ans(i,j,n,m,x%4,y%2,z%4)
end

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

n, m, k1, k2, k3, t = read_ints
k1 %= 4
k3 %= 4
k2 %= 2
t.times do
  x, y = read_ints
  h, w = n, m
  k1.times do
    x, y = y, n - x + 1
    h, w = w, h
  end
  k2.times { y = m - y + 1 }
  k3.times do
    x, y = m - y + 1, x
    h, w = w, h
  end
  puts "#{x} #{y}"
end

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

n, m, k1, k2, k3, t = read_ints
k1 %= 4
k3 %= 4
k2 %= 2
t.times do
  x, y = read_ints
  h, w = n, m
  k3.times do
    x, y = y, n - x + 1
    h, w = w, h
  end
  k2.times { y = m - y + 1 }
  k1.times do
    x, y = m - y + 1, x
    h, w = w, h
  end
  puts "#{x} #{y}"
end


Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare. Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.

The first line contain integer t (1 ≤ t ≤ 20), where t is the number of races. After that all races are described one by one. Every race description start with an integer n (1 ≤ n ≤ 50) on a line of itself, where n is the number of clasified drivers in the given race. After that n lines follow with the classification for the race, each containing the name of a driver. The names of drivers are given in order from the first to the last place. The name of the driver consists of lowercase and uppercase English letters and has length at most 50 characters. Comparing of names should be case-sensetive.

Your output should contain exactly two line. On the first line is the name of the champion according to the original rule, and on the second line the name of the champion according to the alternative rule.

3
3
Hamilton
Vettel
Webber
2
Webber
Vettel
2
Hamilton
Vettel

2
7
Prost
Surtees
Nakajima
Schumacher
Button
DeLaRosa
Buemi
8
Alonso
Prost
NinoFarina
JimClark
DeLaRosa
Nakajima
Patrese
Surtees

NoteIt is not guaranteed that the same drivers participate in all races. For the championship consider every driver that has participated in at least one race. The total number of drivers during the whole season is not more then 50.

class Racer
  N, POINTS = 50, [ 25, 18, 15, 12, 10, 8, 6, 4, 2, 1 ]

  attr_reader :score, :places, :name

  def initialize(name)
    @name = name
    @score = 0
    @places = Array.new(N, 0)
  end

  def add_place(place)
    @score += POINTS[place] if not POINTS[place].nil?
    @places[place] += 1
  end
end

def compare_a(alpha, beta)
  a = alpha.score <=> beta.score
  b = alpha.places <=> beta.places
  return 2 * a + b
end

def compare_b(alpha, beta)
  a = alpha.places.first <=> beta.places.first
  b = alpha.score <=> beta.score
  c = alpha.places[1 .. -1] <=> beta.places[1 .. -1]
  return 4 * a + 2 * b + c
end

def read_race(racers)
  gets.to_i.times do |place|
    name = gets.strip
    racers[name] ||= Racer.new(name)
    racers[name].add_place(place)
  end
end

def read_races(racers)
  gets.to_i.times { read_race(racers) }
end

racers = {}
read_races(racers)

puts racers.values.sort { |x, y| compare_a(x, y) }[-1].name
puts racers.values.sort { |x, y| compare_b(x, y) }[-1].name

t = gets.to_i
pts = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1]
$h = {}
$places = {}
(0...t).each do |i|
    n = gets.to_i
    (0...n).each do |j|
        name = gets.strip
        if $h.key? name
            $h[name] += pts[j] if j < 10
        else
            $h[name] = pts[j] if j < 10
        end
        if $places.key? name
            $places[name][j] += 1
        else
            $places[name] = [0]*100
            $places[name][j] += 1
        end
    end
end
#puts $h.inspect
#puts $places.inspect
def better1 x,y
    return $h[x] <=> $h[y] if $h[x] != $h[y]
    idx = 0
    while $places[x][idx] == $places[y][idx]
        idx += 1
    end
    return $places[x][idx] <=> $places[y][idx]
end

def better2 x,y
    return $places[x][0] <=> $places[y][0] if $places[x][0] != $places[y][0]
    return $h[x] <=> $h[y] if $h[x] != $h[y]
    idx = 1
    while $places[x][idx] == $places[y][idx]
        idx += 1
    end
    return $places[x][idx] <=> $places[y][idx]
end
x = $h.keys
y = $h.keys
xi  = 0
#puts "Is it #{better1 x[2], x[0]}"
(1...x.size).each do |ti|
    xi = ti if better1(x[ti], x[xi]) > 0
end
yi  = 0
(1...y.size).each do |ti|
    yi = ti if better2(y[ti], y[yi]) > 0
end
puts x[xi]
puts y[yi]

#!/usr/bin/ruby

T = gets.to_i

Drivers = Hash.new
Points = [nil, 25, 18, 15, 12, 10, 8, 6, 4, 2 ,1]

T.times do
  n = gets.to_i
  place = 1
  n.times do
    name = gets.chomp
    Drivers[name] = Array.new(51, 0) if (!Drivers[name])
    Drivers[name][0] += Points[place] if place <= 10
    Drivers[name][place] += 1
    place += 1
  end
end

#p Drivers

original_rank = Drivers.to_a.sort {|l, r|
  i = 0
  while (l[1][i] == r[1][i] && i < 52)
    i += 1
  end
  if (i == 52)
    1
  else
    r[1][i] <=> l[1][i]
  end
}

#puts "==="
puts original_rank[0][0]

new_rank = Drivers.to_a
new_rank.each {|e|
  (e[1][1], e[1][0]) = [e[1][0], e[1][1]]
}
#p new_rank
new_rank.sort! {|l, r|
  i = 0
  while (l[1][i] == r[1][i] && i < 52)
    i += 1
  end
  if (i == 52)
    1
  else
    r[1][i] <=> l[1][i]
  end
}

puts new_rank[0][0]


There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai.The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.The airport manager asked you to count for each of n walruses in the queue his displeasure.

The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one.

Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus.

n = gets.to_i
seq = gets.split.map &:to_i
seq.reverse!
ans = []
list = []
pos = []

def bin_search(list, x)
	b = 0
	e = list.size - 1
	p = -1
	while b <= e
		m = (b+e)/2
		if list[m] >= x
			b = m + 1
		else
			e = m - 1
			p = m
		end
	end
	p
end

seq.each_with_index do |x, i|
	p = bin_search list, x
	ans[i] = -1
	if p != -1
		ans[i] = i - pos[p] - 1
	end
	if list.size > 0 && x < list.last
		list << x
		pos << i
	elsif list.size == 0
		list << x
		pos << i
	end
end

ans.reverse!
ans.each do |a|
	p a
end

def findX(a)
  x0 = 0
  x1 = a.size()-1

  return a[x0] if yield(a[x0])
  while x1-x0 > 1
    x2 = (x0+x1)/2
    if yield(a[x2])
      x1 = x2
    else
      x0 = x2
    end
  end
  a[x1]
end

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

b = []
mdx = 0
lst = []
0.upto(a.size-1) do |i|
  if lst.empty? || a[mdx] >= a[i]
    lst << [a[i], (mdx = i)]
    b[i] = -1
  else
    y = findX(lst){|aa,ii| aa<a[i] }[1]
    b[i] = i-y-1
  end
end

puts b.reverse*" "


You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:  Write parity(a) to the end of a. For example, .  Remove the first character of a. For example, . You cannot perform this operation if a is empty. You can use as many operations as you want. The problem is, is it possible to turn a into b?The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.

The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.

Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.

NoteIn the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110

A = gets.chomp.count('1')
B = gets.chomp.count('1')
A += 1 if A&1 == 1
# puts "#{A} #{B}"
if A >= B
	puts "YES"
else
	puts "NO"
end

s = gets.chomp
e = gets.chomp
si = s.count('1')
ei = e.count('1')
si += 1 if si % 2 != 0
puts "YES" if si >= ei
puts "NO" if si < ei

s = gets.chomp
e = gets.chomp
si = ei = 0
for i in 0...s.size
    si += 1 if s[i] == '1'
end
for i in 0...e.size
    ei += 1 if e[i] == '1'
end
if si % 2 == 0
    puts "NO" if si < ei
    puts "YES" if si >= ei
else
    if ei > si && si + 1 != ei
        puts "NO"
    else
        puts "YES"
    end
end

s = gets.chomp
e = gets.chomp
si = s.count('1')
ei = e.count('1')
if si % 2 == 0
    puts "NO" if si < ei
    puts "YES" if si >= ei
else
    if ei > si && si + 1 != ei
        puts "NO"
    else
        puts "YES"
    end
end

a = gets.chomp
b = gets.chomp

onesA = a.count('1')
onesB = b.count('1')

onesA += onesA & 1

 if onesA >= onesB
   puts "YES"
 else
   puts "NO"
 end

def ones(s)
  s.split(//).count("1")
end

def parity?(i)
  i % 2 == 1
end

def run(args)
  a = args[0]
  b = args[1]

  a1 = ones(a)
  b1 = ones(b)

  ap = parity?(a1)
  bp = parity?(b1)

  if a1 >= b1
    return "YES"
  else
    if b1 - a1 == 1 and ap
      return "YES"
    else
      return "NO"
    end
  end
  return "sabugo"
end

buffer = []

STDIN.read.split("\n").each do |line|
  buffer << line
  if buffer.size == 2
    puts run(buffer)
    buffer = []
  end
end

s=gets.split(//)
l=s.size
i=0
n=0
while (i<l) do
  if (s[i]=='1') then
    n+=1
  end
  i+=1
end
if (n%2==1) then
  n+=1
end
s=gets.split(//)
l=s.size
i=0
m=0
while (i<l) do
  if (s[i]=='1') then
    m+=1
  end
  i+=1
end
if (n>=m) then puts "YES"
else puts "NO"
end

a = gets.scan('1').size
b = gets.scan('1').size
a += 1 if a.odd?
puts a >= b ? :YES : :NO

def run
  a1 = $stdin.gets.split(//).map(&:to_i).reduce(:+)
  b1 = $stdin.gets.split(//).map(&:to_i).reduce(:+)

  a1 += 1 if a1 % 2 == 1
  $stdout.puts a1 >= b1 ? "YES" : "NO"
end

run if $0 == __FILE__

z=gets
puts z.count('1')+z.count('1')%2>=gets.count('1') ? 'YES' : 'NO'

as = gets
bs = gets
a = as.count('1')
b = bs.count('1')

if a >= b-1 && b%2 == 0 || b%2 == 1 && a >= b || as == bs
  puts "YES"
else
  puts "NO"
end

count = gets.scan('1').size
count += 1 if count % 2 == 1
puts count >= gets.scan('1').size ? "YES" : "NO"

A = gets.chomp
B = gets.chomp
for c in 1..A.length
	# puts A[-c..A.length]
	if B.start_with?A[-c..A.length] and A[0..-c-1].count('1') >= B[c..B.length].count('1')
		puts "YES"
		exit
	end
end
puts "NO"

s = gets.chomp
e = gets.chomp
si = s.count('1')
ei = e.count('1')
si += 1 if si & 1
puts "YES" if si >= ei
puts "NO" if si < ei

s = gets.chomp
e = gets.chomp
si = ei = 0
for i in 0...s.size
    si += 1 if s[i] == '1'
end
for i in 0...e.size
    ei += 1 if e[i] == '1'
end
if si % 2 == 0
    puts "NO" if si < ei
else
    if ei > si && si + 1 != ei
        puts "NO"
    else
        puts "YES"
    end
end

s = gets.chomp
e = gets.chomp
si = ei = 0
for i in 0...s.size
    si += 1 if s[i] == '1'
end
for i in 0...e.size
    ei += 1 if e[i] == '1'
end
if si % 2 == 0
    puts "NO" if si < ei
    puts "YES" if si == ei
else
    if ei > si && si + 1 != ei
        puts "NO"
    else
        puts "YES"
    end
end

def ones(s)
  s.split(//).count("1")
end

def parity?(i)
  i % 2 == 1
end

def run(args)
  a = args[0]
  b = args[1]

  a1 = ones(a)
  b1 = ones(b)

  ap = parity?(a1)
  bp = parity?(b1)

  if a1 == b1
    return "YES"
  else
    if b1 - a1 == 1 and ap
      return "YES"
    else
      return "NO"
    end
  end
  return "sabugo"
end

buffer = []

STDIN.read.split("\n").each do |line|
  buffer << line
  if buffer.size == 2
    puts run(buffer)
    buffer = []
  end
end

def run
  a1 = $stdin.gets.split(//).map(&:to_i).reduce(:+)
  b1 = $stdin.gets.split(//).map(&:to_i).reduce(:+)
  $stdout.puts a1 >= b1 ? "YES" : "NO"
end

run if $0 == __FILE__

as = gets
bs = gets
a = as.count('1')
b = bs.count('1')

if a >= b-1 && b%2 == 0 || b%2 == 1 && a > b || as == bs
  puts "YES"
else
  puts "NO"
end


Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if   the sequence consists of at least two elements  f0 and f1 are arbitrary  fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.

The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).

Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.

NoteIn the first sample, if we rearrange elements of the sequence as  - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28.

# Discard input count
gets

# Get numbers as a unique array of ints.
nums_list = gets.split.map { |a| a.to_i }
nums_list_uniq = nums_list.uniq

# Get numbers as another array of ints, but with duplicates tacked on to the end.
nums_list_append = nums_list_uniq + nums_list.group_by{ |e| e }.select { |k, v| v.size > 1 }.map(&:first)

# Now we can compare the unique list against the duplicates list to get every set of fibonacci bases without repetition.

# Also, count how many of each number there are.
num_count = {}
num_count.default = 0
nums_list.each { |num| num_count[num] += 1 }

longest_sequence = 2
nums_list_uniq.each_with_index do |a,a_index|
  nums_list_append.each_with_index do |b,b_index|
    # Skip if the two numbers have the same index
    next if (a_index == b_index)
    i = a
    j = b
    k = a+b
    sequence_length = 2
    # Set up a hash to keep track of the numbers I've already used.
    already_used = {}
    already_used.default = 0
    already_used[a] += 1
    already_used[b] += 1

    # If the count of K's used thus far is less than the total count of K's in the sequence
    while (already_used[k] < num_count[k]) do
      # Add the K
      already_used[k] += 1
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets

# Get numbers as a unique array of ints.
nums_list = gets.split.map { |a| a.to_i }
nums_list_uniq = nums_list.uniq

# Get numbers as another array of ints, but with duplicates tacked on to the end.
nums_list_append = nums_list_uniq + nums_list.group_by{ |e| e }.select { |k, v| v.size > 1 }.map(&:first)

# Hash for quick lookup
nums_index = {}
nums_list_uniq.each {|num| nums_index[num] = true}

longest_sequence = 2

nums_list_uniq.each_with_index do |a,a_index|
  nums_list_append.each_with_index do |b,b_index|
    # Skip if the two numbers have the same index
    next if (a_index == b_index)
    i = a
    j = b
    k = a+b
    sequence_length = 2
    already_used = {}

    while (!nums_index[k].nil? && already_used[k].nil?) do
      already_used[k] = true
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets
# Get numbers as an array of ints.
nums_list = gets.split.map { |a| a.to_i }

# Also hashify them, pointing to their index.
nums_index = {}
nums_list.each_with_index {|num,index| nums_index[num] = index}

longest_sequence = 2

nums_list.each do |a|
  nums_list.each do |b|
    # Skip if the two numbers have the same index
    next if (nums_index[a] == nums_index[b])
    i = a
    j = b
    k = a+b
    sequence_length = 2
    # See how long the longest sequence is
    while (!nums_index[k].nil?) do
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets
# Get numbers as an array of ints.
nums_list = gets.split.map { |a| a.to_i }

# Also hashify them, pointing to their index.
nums_index = {}
nums_list.each_with_index {|num,index| nums_index[num] = index}

longest_sequence = 2

nums_list.each_with_index do |a,a_index|
  nums_list.each_with_index do |b,a_index|
    # Skip if the two numbers have the same index
    next if (nums_index[a] == nums_index[b])
    i = a
    j = b
    k = a+b
    sequence_length = 2
    # See how long the longest sequence is
    while (!nums_index[k].nil?) do
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets
# Get numbers as an array of ints.
nums_list = gets.split.map { |a| a.to_i }

# Also hashify them, pointing to their index.
nums_index = {}
nums_list.each_with_index {|num,index| nums_index[num] = index}

longest_sequence = 2

nums_list.each do |a,a_index|
  nums_list.each do |b,a_index|
    # Skip if the two numbers have the same index
    next if (nums_index[a] == nums_index[b])
    i = a
    j = b
    k = a+b
    sequence_length = 2
    # See how long the longest sequence is
    while (!nums_index[k].nil?) do
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets
# Get numbers as an array of ints.
nums_list = gets.split.map { |a| a.to_i }

# Also hashify them.
nums_index = {}
nums_list.each {|num| nums_index[num] = true}
longest_sequence = 2

# List of A's we have already tested.
a_tested = {}

nums_list.each do |a|

  # Skip this set of b's if we have seen this a before.
  next if (!a_tested[a].nil?)
  a_tested[a] = true

  nums_list.each do |b|
    # Skip if the two numbers have the same index.
    # next if (a_index == b_index)
    i = a
    j = b
    k = a+b
    sequence_length = 2
    # See how long the longest sequence is
    while (!nums_index[k].nil?) do
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets
# Get numbers as a unique array of ints.
nums_list = gets.split.map { |a| a.to_i }
nums_list_uniq = nums_list.uniq
# Get numbers as another array of ints, but with duplicates tacked on to the end.
nums_list_append = nums_list_uniq + nums_list.group_by{ |e| e }.select { |k, v| v.size > 1 }.map(&:first)

puts nums_list_uniq.to_s
puts nums_list_append.to_s

nums_index = {}
nums_list_uniq.each {|num| nums_index[num] = true}

longest_sequence = 2

nums_list_uniq.each_with_index do |a,a_index|
  nums_list_append.each_with_index do |b,b_index|
    # Skip if the two numbers have the same index
    next if (a_index == b_index)
    i = a
    j = b
    k = a+b
    sequence_length = 2
    already_used = {}

    while (!nums_index[k].nil? && already_used[k].nil?) do
      already_used[k] = true
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s


A median of an array of integers of length $$$n$$$ is the number standing on the $$$\lceil {\frac{n}{2}} \rceil$$$ (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with $$$1$$$. For example, a median of the array $$$[2, 6, 4, 1, 3, 5]$$$ is equal to $$$3$$$. There exist some other definitions of the median, but in this problem, we will use the described one.Given two integers $$$n$$$ and $$$k$$$ and non-decreasing array of $$$nk$$$ integers. Divide all numbers into $$$k$$$ arrays of size $$$n$$$, such that each number belongs to exactly one array.You want the sum of medians of all $$$k$$$ arrays to be the maximum possible. Find this maximum possible sum.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of test cases. The first line of the description of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 1000$$$). The second line of the description of each test case contains $$$nk$$$ integers $$$a_1, a_2, \ldots, a_{nk}$$$ ($$$0 \leq a_i \leq 10^9$$$) — given array. It is guaranteed that the array is non-decreasing: $$$a_1 \leq a_2 \leq \ldots \leq a_{nk}$$$. It is guaranteed that the sum of $$$nk$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer — the maximum possible sum of medians of all $$$k$$$ arrays.

t = gets.chomp.to_i
t.times do
  n, k = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  # puts arr.to_s
  t = n / 2
  ind = arr.size - 1 - t
  # puts "ind = " + ind.to_s
  res = 0
  while k > 0 do
    res += arr[ind]
    # puts "el = " + arr[ind].to_s
    k -= 1
    ind -= t + 1
  end
  puts res
end

# 1 -> 0
# 2 -> 1
# 3 -> 1
# 4 -> 2
# 5 -> 2

t=gets.to_i
t.times{
    n,k=gets.split.map &:to_i
    tab=gets.split.map &:to_i
    time = (n.to_f/2).ceil-1
    tab = tab.drop(k*time)
    p tab.each_slice(n - time).map{|x|x[0]}.sum
}


Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.

The first line of the input contains one integer, n (1 ≤ n ≤ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 109, inclusive.

Print the maximum possible even sum that can be obtained if we use some of the given integers.

NoteIn the first sample, we can simply take all three integers for a total sum of 6.In the second sample Wet Shark should take any four out of five integers 999 999 999.

gets
x,y=gets.split.map(&:to_i).sort.reverse.partition{|e|e%2==0}
p x.reduce(0,:+)+y[0,y.size/2*2].reduce(0,:+)

def function
b=gets.chomp
a=gets.chomp
a=a.split(' ').map(&:to_i).sort
sum=0
a.each do |i|
sum+=i
end
if sum%2!=0
a.each do |i|
if i%2!=0
sum-=i
puts sum
break
end
end
else
puts sum
end
end
function

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

min_odd = numbers.find(&:odd?)
sum = numbers.inject(0, :+)
puts sum.even? ? sum : sum - min_odd

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

evens = arr.select(&:even?)
odds = arr.select(&:odd?).sort

odds_sum = odds.size.even? ? odds.inject(0, :+) : odds.drop(1).inject(0, :+)

puts evens.inject(0, :+) + odds_sum

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

par = []
nep = []
sum = a.reduce(:+)
a.each { |x| x.even? ? par.push(x) : nep.push(x) }

puts sum.even? ? sum : sum - nep[0]

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

par, nep = [], []
a.each do |x|
  x.even? ? par.push(x) : nep.push(x)
end
sum = a.reduce(:+)

puts sum.even? ? sum : sum - nep[0]

def sum_all(arr)
	sum =0
	arr.each do |i|
		sum+=i
	end
	return sum
end

n = gets.chomp
arr = gets.split.map(&:to_i)
odd_count =0
even_count =0
arr.each do|i|
	if i.even?
		even_count +=1
	else
		odd_count +=1
	end
end
sum=0

if odd_count.even?
	puts sum_all(arr)
else
	odd_count -=1
arr.sort!.reverse!

sum =0
arr.each do |i|
	if i.odd? and odd_count>0
		sum+=i
		odd_count -=1
	elsif i.even?
		sum+=i
	end
end
puts sum
end

gets
e1=0
o1=-1
x=gets.split.map{|e| e.to_i}
x.each{|e|
	d=e%2
	if d==0 then
		e1+=e
		if o1!=-1 then
			o1+=e
		end
	else
		o2=e1+e
		if o1!=-1 then
			e1=[e1,o1+e].max
		end
		o1=[o1,o2].max
	end
}
puts e1

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

a.sort!{|x, y| y <=> x }
ans = 0
odd = []
a.each do |v|
  if v % 2 == 0
    ans += v
  else
    if odd.size == 0
      odd.push(v)
    else
      ans += v + odd.shift
    end
  end
end
puts ans

# coding: utf-8

n = gets.to_i
a = []
sum = 0
odds = 0
gets.split.each { |i|
    i = i.to_i

    if i.even?
        sum += i
    else
        odds += 1 if i.odd?
        a << i
    end
}
a.sort!
if odds.odd?
    a.shift
end
a << 0

puts a.reduce(:+) + sum

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

s = xs.inject(&:+)
if s % 2 == 0
  puts s
else
  puts s - xs.select { |x| x % 2 == 1 }.min
end

def solve(a)
  s = a.inject(0, :+)
  return s if s.even?
  x = a.lazy.select(&:odd?).min
  return s - x if x
  0
end

gets
puts solve(gets.split.map(&:to_i))

n = gets.to_i
a = gets.split(' ').map &:to_i
s = a.reduce(&:+)
if s%2 == 0
  puts s
else
  mn = Float::INFINITY
  for i in a
    mn = [mn, i].min if i%2 == 1
  end
  puts s - mn
end

n = gets.to_i
a = gets.split.map(&:to_i)
sum = a.inject(:+)
puts sum.even? ? sum : sum - a.select(&:odd?).min

n = gets.to_i
a = gets.split.map(&:to_i).sort
sum = a.inject(:+)
puts sum.even? ? sum : sum - a.find{|x| x.odd?}

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

aoddmin = a.select{|x| x.odd?}.min

asum = a.inject(:+)
if asum.even? then
  puts asum
else
  puts asum - aoddmin
end

gets
a = gets.split.map{|x| x.to_i}
odds = a.select{|x| x%2 == 1}
puts(a.inject(0){|s, x| s + x} - (odds.size%2 != 0 ? odds.min : 0))

gets
x,y=gets.split.map(&:to_i).sort.reverse.partition{|e|e==0}
p x.reduce(0,:+)+y[0,y.size/2*2].reduce(0,:+)

def function
a=gets.chomp
a=a.split(' ').map(&:to_i).sort
sum=0
a.each do |i|
sum+=i
end
a.each do |i|
if i%2!=0
sum-=i
break
end
end
puts sum
end
function

n = gets.chomp
arr = gets.split.map(&:to_i)
odd_count =0
even_count =0
arr.each do |i|
	if i.odd?
		odd_count+=1
	else
		even_count +=1
	end
end

if odd_count.odd?
	odd_count = odd_count -1
end
sum = 0
arr.each do |i|
	if i.odd? and not odd_count.zero?
		sum +=i
		odd_count= odd_count -1
	elsif i.even?
		sum +=i
	end
end
puts sum

gets
e1=0
o1=-1
x=gets.split.map{|e| e.to_i}
x.each{|e|
	d=e%2
	if d==0 then
		e1+=e
		if o1!=-1 then
			o1+=e
		end
	else
		o2=e1+e
		if o1!=-1 then
			e1=o1+e
		end
		o1=o2
	end
}
puts e1

# coding: utf-8

n = gets.to_i
a = []
sum = 0
odds = 0
gets.split.each { |i|
    i = i.to_i

    if i.even?
        sum += i
    else
        odds += 1 if i.odd?
        a << i
    end
}

if odds.odd?
    a.shift
    a << 0
end

puts a.reduce(:+) + sum

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

aoddmax = a.select{|x| x.odd?}.max

asum = a.inject(:+)
if asum.even? then
  puts asum
else
  puts asum - aoddmax
end