Recently, Masha was presented with a chessboard with a height of $$$n$$$ and a width of $$$m$$$.The rows on the chessboard are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right. Therefore, each cell can be specified with the coordinates $$$(x,y)$$$, where $$$x$$$ is the column number, and $$$y$$$ is the row number (do not mix up).Let us call a rectangle with coordinates $$$(a,b,c,d)$$$ a rectangle lower left point of which has coordinates $$$(a,b)$$$, and the upper right one — $$$(c,d)$$$.The chessboard is painted black and white as follows:   An example of a chessboard. Masha was very happy with the gift and, therefore, invited her friends Maxim and Denis to show off. The guys decided to make her a treat — they bought her a can of white and a can of black paint, so that if the old board deteriorates, it can be repainted. When they came to Masha, something unpleasant happened: first, Maxim went over the threshold and spilled white paint on the rectangle $$$(x_1,y_1,x_2,y_2)$$$. Then after him Denis spilled black paint on the rectangle $$$(x_3,y_3,x_4,y_4)$$$.To spill paint of color $$$color$$$ onto a certain rectangle means that all the cells that belong to the given rectangle become $$$color$$$. The cell dyeing is superimposed on each other (if at first some cell is spilled with white paint and then with black one, then its color will be black).Masha was shocked! She drove away from the guests and decided to find out how spoiled the gift was. For this, she needs to know the number of cells of white and black color. Help her find these numbers!

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. Each of them is described in the following format: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^9$$$) — the size of the board. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \le x_1 \le x_2 \le m, 1 \le y_1 \le y_2 \le n$$$) — the coordinates of the rectangle, the white paint was spilled on. The third line contains four integers $$$x_3$$$, $$$y_3$$$, $$$x_4$$$, $$$y_4$$$ ($$$1 \le x_3 \le x_4 \le m, 1 \le y_3 \le y_4 \le n$$$) — the coordinates of the rectangle, the black paint was spilled on.

Output $$$t$$$ lines, each of which contains two numbers — the number of white and black cells after spilling paint, respectively.

NoteExplanation for examples:The first picture of each illustration shows how the field looked before the dyes were spilled. The second picture of each illustration shows how the field looked after Maxim spoiled white dye (the rectangle on which the dye was spilled is highlighted with red). The third picture in each illustration shows how the field looked after Denis spoiled black dye (the rectangle on which the dye was spilled is highlighted with red).In the first test, the paint on the field changed as follows:  In the second test, the paint on the field changed as follows:  In the third test, the paint on the field changed as follows:  In the fourth test, the paint on the field changed as follows:  In the fifth test, the paint on the field changed as follows:

def is_white?(x, y)
    (x + y)%2 == 0
end

def is_black?(x, y)
    (x + y)%2 != 0
end

def white(x1, y1, x2, y2)
    return 0 if x2 < x1 || y2 < y1
    o = 1 + (x2 - x1)/2
    e = (x2 - x1 + 1)/2
    no = 1 + (y2 - y1)/2
    ne = (y2 - y1 + 1)/2

    if is_white?(x1, y1)
        no*o + ne*e
    else
        ne*o + no*e
    end
end

def black(x1, y1, x2, y2)
    return 0 if x2 < x1 || y2 < y1
    o = 1 + (x2 - x1)/2
    e = (x2 - x1 + 1)/2
    no = 1 + (y2 - y1)/2
    ne = (y2 - y1 + 1)/2

    if is_black?(x1, y1)
        no*o + ne*e
    else
        ne*o + no*e
    end
end

def intersect(x1, y1, x2, y2, x3, y3, x4, y4)
    f, s = [x1, y1, x2, y2], [x3, y3, x4, y4]
    f, s = s, f if x3 < x1
    return nil if s[1] > f[3] || s[0] > f[2] || s[3] < f[1]
    xi1, yi1 = [f[2], s[0]].min, [f[1], s[1]].max
    xi2, yi2 = [s[2], f[2]].min, [s[3], f[3]].min
    [xi1, yi1, xi2, yi2]
end

t = gets.to_i
t.times do
    n, m = gets.split.map{|x| x.to_i}
    x1, y1, x2, y2 = gets.split.map{|x| x.to_i}
    x3, y3, x4, y4 = gets.split.map{|x| x.to_i}
    nwhite = white(1, 1, m, n)
    nblack = black(1, 1, m, n)
    #p [nwhite, nblack]
    nwhite += black(x1, y1, x2, y2)
    nblack -= black(x1, y1, x2, y2)
    #p [nwhite, nblack]
    inter = intersect(x1, y1, x2, y2, x3, y3, x4, y4)
    #p inter
    if inter
        ab = black(inter[0], inter[1], inter[2], inter[3])
    else
        ab = 0
    end
    nwhite -= white(x3, y3, x4, y4) + ab
    nblack += white(x3, y3, x4, y4) + ab
    puts nwhite.to_s + ' ' + nblack.to_s
end

t = gets.to_i

def colorsin(a,b,n,m)

  squares = (n-a+1)*(m-b+1)
  if (a+b)%2 == 0 #bottom left square is white (more whites)
    black = squares/2
    white = squares-black
  else
    white = squares/2
    black = squares-white
  end

  return [white,black]
end

t.times do
  nm = gets.chomp.split(" ").map(&:to_i)
  rec1 = gets.chomp.split(" ").map(&:to_i)
  rec2 = gets.chomp.split(" ").map(&:to_i)

  n = nm[0]
  m = nm[1]

  x1 = rec1[0]
  y1 = rec1[1]
  x2 = rec1[2]
  y2 = rec1[3]

  x3 = rec2[0]
  y3 = rec2[1]
  x4 = rec2[2]
  y4 = rec2[3]

  squares = n*m
  blacks = (squares)/2
  whites = squares-blacks

  overlap = true
  if (x3>x2 || x4<x1 || y3>y2 || y4<y1)
    overlap = false
  end

  if overlap
    if (x3<=x1)
      x5 = x1
      if (x4<=x2)
        x6 = x4
      else
        x6 = x2
      end
    else
      x5 = x3
      if (x4<=x2)
        x6 = x4
      else
        x6 = x2
      end
    end

    if (y3<=y1)
      y5 = y1
      if (y4<=y2)
        y6 = y4
      else
        y6 = y2
      end
    else
      y5 = y3
      if (y4<=y2)
        y6 = y4
      else
        y6 = y2
      end
    end
  end

  #do for white paint
  colorone = colorsin(x1,y1,x2,y2)
  whites += colorone[1]
  blacks -= colorone[1]

  #do for black paint

  colortwo = colorsin(x3,y3,x4,y4)
  blacks += colortwo[0]
  whites -= colortwo[0]

  if overlap
    colorthree = colorsin(x5,y5,x6,y6)
    blacks += colorthree[1]
    whites -= colorthree[1]
  end

  puts "#{whites} #{blacks}"
end


There are $$$n$$$ piranhas with sizes $$$a_1, a_2, \ldots, a_n$$$ in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the aquarium (except itself, of course). Other piranhas will do nothing while the dominant piranha will eat them.Because the aquarium is pretty narrow and long, the piranha can eat only one of the adjacent piranhas during one move. Piranha can do as many moves as it needs (or as it can). More precisely:   The piranha $$$i$$$ can eat the piranha $$$i-1$$$ if the piranha $$$i-1$$$ exists and $$$a_{i - 1} < a_i$$$.  The piranha $$$i$$$ can eat the piranha $$$i+1$$$ if the piranha $$$i+1$$$ exists and $$$a_{i + 1} < a_i$$$. When the piranha $$$i$$$ eats some piranha, its size increases by one ($$$a_i$$$ becomes $$$a_i + 1$$$).Your task is to find any dominant piranha in the aquarium or determine if there are no such piranhas.Note that you have to find any (exactly one) dominant piranha, you don't have to find all of them.For example, if $$$a = [5, 3, 4, 4, 5]$$$, then the third piranha can be dominant. Consider the sequence of its moves:   The piranha eats the second piranha and $$$a$$$ becomes $$$[5, \underline{5}, 4, 5]$$$ (the underlined piranha is our candidate).  The piranha eats the third piranha and $$$a$$$ becomes $$$[5, \underline{6}, 5]$$$.  The piranha eats the first piranha and $$$a$$$ becomes $$$[\underline{7}, 5]$$$.  The piranha eats the second piranha and $$$a$$$ becomes $$$[\underline{8}]$$$. You have to answer $$$t$$$ independent test cases.

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

For each test case, print the answer: -1 if there are no dominant piranhas in the aquarium or index of any dominant piranha otherwise. If there are several answers, you can print any.

NoteThe first test case of the example is described in the problem statement.In the second test case of the example, there are no dominant piranhas in the aquarium.In the third test case of the example, the fourth piranha can firstly eat the piranha to the left and the aquarium becomes $$$[4, 4, 5, 4]$$$, then it can eat any other piranha in the aquarium.

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  m = a.max

  ans = -1

  n.times do |i|
    next if a[i] != m

    if i - 1 >= 0 && a[i - 1] < m
      ans = i + 1
    end

    if i + 1 < n && a[i + 1] < m
      ans = i + 1
    end
  end

  puts ans
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i)
    max = 0
    arr = []
    count = 0
    a.each_with_index do |i,j|
        max = [max,i].max
        if n >= 3
            if i >= max && j >= 1 && j <= n - 2
                if i != a[j-1] || i != a[j+1]
                    arr << j
                end
            elsif i >= max && j == 0
                # p i
                # puts "I"
                if i != a[j+1]
                    # p i
                    # p j
                    # puts "Iiiii"
                    arr << j
                end
            elsif i >= max && j == n - 1
                if i != a[j-1]
                    arr << j
                end
            #max = [max,i].max
            #arr << j
            #count += 1
            end
        end
        # puts "OOOOO"
        # p max
        # puts "IIIIIIIII"
    end
    if n == 2
        big = a.max
        a.each_with_index do |i,j|
            if i == big
                arr << j
            end
        end
    end
    a = a.map(&:to_s)
    a = a.uniq
    if a.size == 1
        puts "-1"
    else
        ans = arr.pop + 1
        puts ans
    end
end

gets.to_i.times do
  n = gets.to_i
  v = gets.split.map(&:to_i)
  max = v.max
  r = (0...n).find do |i|
    v[i] == max && ((i > 0 && v[i] > v[i-1]) || (i+1 < n && v[i] > v[i+1]))
  end
  puts r.nil? ? -1 : r+1
end

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

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  max = a.max
  index = -1
  n.times do |i|
    if a[i] == max
      if (i-1 >= 0 && a[i-1] != max) || (i+1 < n && a[i+1] != max)
        index = i+1
      end
    end
  end
  ans << index
end
puts ans

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  ma = a.max
  next puts(-1) if a.count(ma) == a.length
  puts (n.times do |i|
    break i + 1 if i > 0 and a[i] == ma and a[i] > a[i - 1]
    break i + 1 if a[i] == ma and a[i] > a[i + 1]
    end
  )
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  ma = a.max
  if a.count(ma) == a.length
    puts(-1)
  else
    puts (n.times do |i|
      break i + 1 if i > 0 and a[i] == ma and a[i] > a[i - 1]
      break i + 1 if a[i] == ma and a[i] > a[i + 1]
      end
    )
  end
end

t=gets.to_i
t.times do
  n=gets.to_i
  if n==1
    p 1
    next
  end
  an=gets.chomp.split(' ').map(&:to_i)
  maxi = an.max
  flag = false
  catch(:break_loop) do
    n.times do |i|
      if an[i]==maxi && (i!=0 && an[i-1]<maxi || i!=n-1 && an[i+1]<maxi)
        p i+1
        flag=true
        throw :break_loop
      end
    end
  end
  p -1 unless flag
end


A tree is an undirected connected graph in which there are no cycles. This problem is about non-rooted trees. A leaf of a tree is a vertex that is connected to at most one vertex.The gardener Vitaly grew a tree from $$$n$$$ vertices. He decided to trim the tree. To do this, he performs a number of operations. In one operation, he removes all leaves of the tree.  Example of a tree. For example, consider the tree shown in the figure above. The figure below shows the result of applying exactly one operation to the tree.  The result of applying the operation "remove all leaves" to the tree. Note the special cases of the operation:  applying an operation to an empty tree (of $$$0$$$ vertices) does not change it;  applying an operation to a tree of one vertex removes this vertex (this vertex is treated as a leaf);  applying an operation to a tree of two vertices removes both vertices (both vertices are treated as leaves). Vitaly applied $$$k$$$ operations sequentially to the tree. How many vertices remain?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is preceded by an empty line. Each test case consists of several lines. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 4 \cdot 10^5$$$, $$$1 \le k \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of operations, respectively. Then $$$n - 1$$$ lines follow, each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) which describe a pair of vertices connected by an edge. It is guaranteed that the given graph is a tree and has no loops or multiple edges. It is guaranteed that the sum of $$$n$$$ from all test cases does not exceed $$$4 \cdot 10^5$$$.

For each test case output on a separate line a single integer — the number of vertices that remain in the tree after applying $$$k$$$ operations.

NoteThe first test case is considered in the statement.The second test case contains a tree of two vertices. $$$200000$$$ operations are applied to it. The first one removes all two vertices, the other operations do not change the tree.In the third test case, a tree of three vertices is given. As a result of the first operation, only $$$1$$$ vertex remains in it (with the index $$$2$$$), the second operation makes the tree empty.

require 'set'

def f(a)
    d = Array.new(a.size)
    q = []
    a.each_with_index do |j, i|
        next if j.size > 1
        q << i
        d[i] = 1
    end
    q.each { |v| a[v].delete(v) }
    while (v = q.shift)
        dv = d[v]
        a[v].each do |u|
            a[u].delete(v)
            next if a[u].size > 1
            next if d[u]
            d[u] = dv + 1
            q << u
        end
    end
    d[0] = 0
    d
end

gets.to_i.times do
    gets
    n, k = gets.split.map!(&:to_i)
    a = Array.new(n + 1) { Set.new }
    n.pred.times do
        u, v = gets.split.map!(&:to_i)
        a[u] << v
        a[v] << u
    end
    d = f(a)
    puts d.count { |di| di > k }
end

require 'set'

def f(nbrs)
  d = Array.new(nbrs.size)

  q = []
  nbrs.each_with_index do |nbr, i|
    next if nbr.size > 1
    q << i
    d[i] = 1
  end
  q.each { |v| nbrs[v].delete(v) }

  while (v = q.shift)
    dv = d[v]
    nbrs[v].each do |u|
      nbrs[u].delete(v)
      next if nbrs[u].size > 1
      next if d[u]
      d[u] = dv + 1
      q << u
    end
  end

  d[0] = 0
  d
end

gets.to_i.times do

gets  # empty line
n, k = gets.split.map!(&:to_i)
nbrs = Array.new(n + 1) { Set.new }
n.pred.times do
  u, v = gets.split.map!(&:to_i)
  nbrs[u] << v
  nbrs[v] << u
end

d = f(nbrs)
puts d.count { |di| di > k }

end

require 'set'

def f(nbrs)
  d = Array.new(nbrs.size)

  q = []
  nbrs.each_with_index do |nbr, i|
    next if nbr.size > 1
    q << i
    d[i] = 1
  end
  q.each { |v| nbrs[v].delete(v) }

  while (v = q.shift)
    dv = d[v]
    nbrs[v].each do |u|
      nbrs[u].delete(v)
      next if nbrs[u].size > 1
      d[u] = dv + 1
      q << u
    end
  end

  d[0] = 0
  d
end

gets.to_i.times do

gets  # empty line
n, k = gets.split.map!(&:to_i)
nbrs = Array.new(n + 1) { Set.new }
n.pred.times do
  u, v = gets.split.map!(&:to_i)
  nbrs[u] << v
  nbrs[v] << u
end

d = f(nbrs)
puts d.count { |di| di > k }

end


The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.

The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999).

Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes).

def min(x, lim)
  (lim.."2011").each do |s|
    d = 0
    for i in 0..3
       d += (s[i] == x[i]) ? 0 : 1
    end
    next if d > 1

    return s
  end

  return false
end

lim = "1000"
o = []
gets.to_i.times do
  s = gets.chomp
  r = min(s, lim)
  unless r
    puts "No solution"
    exit
  end
  o << r
  lim = r
end
puts o

N = gets.to_i
years = []
ans = []

N.times {
  tmp = []
  year = gets.chomp
  0.upto(3) { |i|
    0.upto(9) {|j|
      changed = year.dup
      changed[i, 1] = j.to_s
      changed = changed.to_i
      if (changed >= 1000 && changed <= 2011)
        tmp.push changed
      end
    }
  }
  tmp.sort!
  years.push tmp
}

failed = false
ans.push years[0][0]

1.upto(N - 1) {|i|
  ans[i] = -1
  years[i].each {|e|
    if (e >= ans[i - 1])
      ans[i] = e
      break
    end
  }
  if (ans[i] == -1)
    puts "No solution"
    exit
  end
}

ans.each {|e| puts e}

def find_min(x, lim)
  return false if lim > "2011"

  (lim.."2011").each do |s|
    sum = (s[0] == x[0]) ? 0 : 1
    sum += (s[1] == x[1]) ? 0 : 1
    next if sum > 1
    sum += (s[2] == x[2]) ? 0 : 1
    next if sum > 1
    sum += (s[3] == x[3]) ? 0 : 1
    next if sum > 1

    return s
  end

  return false
end

n = gets.to_i
lim = "1000"
o = []
n.times do
  s = gets.chomp
  r = find_min(s, lim)
  unless r
    puts "No solution"
    exit
  end
  o << r
  lim = r
end

puts o


Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.On that night, Sengoku constructed a permutation p1, p2, ..., pn of integers from 1 to n inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with n meteorids, colours of which being integer sequences a1, a2, ..., an and b1, b2, ..., bn respectively. Meteoroids' colours were also between 1 and n inclusive, and the two sequences were not identical, that is, at least one i (1 ≤ i ≤ n) exists, such that ai ≠ bi holds.Well, she almost had it all — each of the sequences a and b matched exactly n - 1 elements in Sengoku's permutation. In other words, there is exactly one i (1 ≤ i ≤ n) such that ai ≠ pi, and exactly one j (1 ≤ j ≤ n) such that bj ≠ pj.For now, Sengoku is able to recover the actual colour sequences a and b through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.

The first line of input contains a positive integer n (2 ≤ n ≤ 1 000) — the length of Sengoku's permutation, being the length of both meteor outbursts at the same time. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the sequence of colours in the first meteor outburst. The third line contains n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ n) — the sequence of colours in the second meteor outburst. At least one i (1 ≤ i ≤ n) exists, such that ai ≠ bi holds.

Output n space-separated integers p1, p2, ..., pn, denoting a possible permutation Sengoku could have had. If there are more than one possible answer, output any one of them. Input guarantees that such permutation exists.

NoteIn the first sample, both 1, 2, 5, 4, 3 and 1, 2, 3, 4, 5 are acceptable outputs.In the second sample, 5, 4, 2, 3, 1 is the only permutation to satisfy the constraints.

n = gets.chomp.to_i

ax = ay = missing = -1
a = gets.chomp.split.map &:to_i
for i in 0...n
  for j in 0...i
    if a[i] == a[j]
      ax = i
      ay = j
    end
  end
end
for i in 1..n
  has = false
  for j in 0...n
    if a[j] == i
      has = true
    end
  end
  if !has
    missing = i
  end
end

b = gets.chomp.split.map &:to_i

if a[ax] == b[ax] || b[ay] == missing
  a[ay] = missing
else
  a[ax] = missing
end
puts a.join " "

n = Integer(gets.chomp)
a = []
a = gets.chomp.split.map &:to_i
b = []
b = gets.chomp.split.map &:to_i

x = Array.new(n) { |i| i + 1}
position = 0
position_other = 0
for i in 0...n
    if x.include?(a[i])
        x.delete(a[i])
    else
        position = i
    end
end
left = x[0]

for i in 0...n
    if a[i] == a[position]
        position_other = i
        break
    end
end
output1 = []
output1.replace(a)
output1[position_other] = left
output2 = []
output2.replace(a)
output2[position] = left
count = 0
for i in 0...n
    if b[i] != output1[i]
        count += 1
    end
end
if count == 1
    print output1.join(" ")
else
    print output2.join(" ")
end

def ok(a, b, p)
  n = p.length
  x = 0
  y = 0
  for i in 0...n
    x += 1 if a[i] == p[i]
    y += 1 if b[i] == p[i]
  end
  return x == n - 1 && y == n - 1
end

def solve(a, b)
  x = -1
  y = -1
  n = a.length

  mrk = Hash.new(0)

  p = []
  for i in 0...n
    if a[i] != b[i]
      if x == -1
        x = i
        p.push(-1)
      else
        y = i
        p.push(-1)
      end
    else
      mrk[a[i]] = 1
      p.push(a[i])
    end
  end

  if y == -1
    for i in 1..n
      if mrk[i] == 0
        p[x] = i
      end
    end

    return p
  end

  lst = []
  for i in 1..n
    if mrk[i] == 0
      lst.push(i)
    end
  end

  p[x] = lst[0]
  p[y] = lst[1]

  return p if ok(a, b, p)

  p[x] = lst[1]
  p[y] = lst[0]

  return p
end

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

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

line = gets.chomp
b = line.split.map(&:to_i)

p = solve(a, b)
p.each { |x| print x.to_s + " " }
puts

n = gets.chomp.to_i

ax = ay = missing = -1
a = gets.chomp.split.map &:to_i
for i in 0...n
  for j in 0...i
    if a[i] == a[j]
      ax = i
      ay = j
    end
  end
end
for i in 1..n
  has = false
  for j in 0...n
    if a[j] == i
      has = true
    end
  end
  if !has
    missing = i
  end
end

b = gets.chomp.split.map &:to_i

if a[ax] == b[ax]
  a[ay] = missing
else
  a[ax] = missing
end
puts a.join " "

n = gets.chomp.to_i

ax = ay = missing = -1
a = gets.chomp.split.map &:to_i
for i in 0...n
  for j in 0...i
    if a[i] == a[j]
      ax = i
      ay = j
    end
  end
end
for i in 1..n
  has = false
  for j in 0...n
    if a[j] == i
      has = true
    end
  end
  if !has
    missing = i
  end
end

bx = by = -1
b = gets.chomp.split.map &:to_i
for i in 0...n
  for j in 0...i
    if b[i] == b[j]
      bx = i
      by = j
    end
  end
end

if ax == bx || ax == by
  a[ax] = missing
elsif
  a[ay] = missing
end

puts a.join " "

n = Integer(gets.chomp)
a = []
a = gets.chomp.split.map &:to_i
b = []
b = gets.chomp.split.map &:to_i

x = Array.new(n) { |i| i + 1}
position = 0
position_other = 0
for i in 0...n
    if x.include?(a[i])
        x.delete(a[i])
    else
        position = i
    end
end
left = x[0]

for i in 0...n
    if a[i] == a[position]
        position_other = i
        break
    end
end
output1 = []
output1.replace(a)
output1[position_other] = left
output2 = []
output2.replace(a)
output2[position] = left
count = 0
for i in 0...n
    if b[i] != output1[i]
        count += 1
    end
end
if count == 1
    print output1
else
    print output2
end

def solve(a, b)
  x = -1
  y = -1
  n = a.length

  mrk = Hash.new(0)

  p = []
  i = 0

  while i < n
    if a[i] != b[i]
      if x == -1
        x = i
        p.push(-1)
      else
        y = i
        p.push(-1)
      end
    else
      mrk[a[i]] = 1
      p.push(a[i])
    end
    i += 1
  end

  if y == -1
    for i in 1..n
      if mrk[i] == 0
        p[x] = i
      end
    end

    return p
  end

  for i in 1..n
    if mrk[i] == 0
      if (a[x] == i || b[x] == i) && x != -1
        p[x] = i
        x = -1
      else
        p[y] = i
      end
    end
  end

  return p
end

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

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

line = gets.chomp
b = line.split.map(&:to_i)

p = solve(a, b)
p.each { |x| print x.to_s + " " }
puts


Circular land is an $$$2n \times 2n$$$ grid. Rows of this grid are numbered by integers from $$$1$$$ to $$$2n$$$ from top to bottom and columns of this grid are numbered by integers from $$$1$$$ to $$$2n$$$ from left to right. The cell $$$(x, y)$$$ is the cell on the intersection of row $$$x$$$ and column $$$y$$$ for $$$1 \leq x \leq 2n$$$ and $$$1 \leq y \leq 2n$$$.There are $$$n^2$$$ of your friends in the top left corner of the grid. That is, in each cell $$$(x, y)$$$ with $$$1 \leq x, y \leq n$$$ there is exactly one friend. Some of the other cells are covered with snow.Your friends want to get to the bottom right corner of the grid. For this in each cell $$$(x, y)$$$ with $$$n+1 \leq x, y \leq 2n$$$ there should be exactly one friend. It doesn't matter in what cell each of friends will be.You have decided to help your friends to get to the bottom right corner of the grid.For this, you can give instructions of the following types:   You select a row $$$x$$$. All friends in this row should move to the next cell in this row. That is, friend from the cell $$$(x, y)$$$ with $$$1 \leq y < 2n$$$ will move to the cell $$$(x, y + 1)$$$ and friend from the cell $$$(x, 2n)$$$ will move to the cell $$$(x, 1)$$$.  You select a row $$$x$$$. All friends in this row should move to the previous cell in this row. That is, friend from the cell $$$(x, y)$$$ with $$$1 < y \leq 2n$$$ will move to the cell $$$(x, y - 1)$$$ and friend from the cell $$$(x, 1)$$$ will move to the cell $$$(x, 2n)$$$.  You select a column $$$y$$$. All friends in this column should move to the next cell in this column. That is, friend from the cell $$$(x, y)$$$ with $$$1 \leq x < 2n$$$ will move to the cell $$$(x + 1, y)$$$ and friend from the cell $$$(2n, y)$$$ will move to the cell $$$(1, y)$$$.  You select a column $$$y$$$. All friends in this column should move to the previous cell in this column. That is, friend from the cell $$$(x, y)$$$ with $$$1 < x \leq 2n$$$ will move to the cell $$$(x - 1, y)$$$ and friend from the cell $$$(1, y)$$$ will move to the cell $$$(2n, y)$$$. Note how friends on the grid border behave in these instructions.  Example of applying the third operation to the second column. Here, colorful circles denote your friends and blue cells are covered with snow. You can give such instructions any number of times. You can give instructions of different types. If after any instruction one of your friends is in the cell covered with snow he becomes ill.In order to save your friends you can remove snow from some cells before giving the first instruction:   You can select the cell $$$(x, y)$$$ that is covered with snow now and remove snow from this cell for $$$c_{x, y}$$$ coins. You can do this operation any number of times.You want to spend the minimal number of coins and give some instructions to your friends. After this, all your friends should be in the bottom right corner of the grid and none of them should be ill.Please, find how many coins you will spend.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \leq n \leq 250$$$). Each of the next $$$2n$$$ lines contains $$$2n$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, 2n}$$$ ($$$0 \leq c_{i, j} \leq 10^9$$$) — costs of removing snow from cells. If $$$c_{i, j} = 0$$$ for some $$$i, j$$$ than there is no snow in cell $$$(i, j)$$$. Otherwise, cell $$$(i, j)$$$ is covered with snow. It is guaranteed that $$$c_{i, j} = 0$$$ for $$$1 \leq i, j \leq n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$250$$$.

For each test case output one integer — the minimal number of coins you should spend.

NoteIn the first test case you can remove snow from the cells $$$(2, 1)$$$ and $$$(2, 2)$$$ for $$$100$$$ coins. Then you can give instructions   All friends in the first collum should move to the previous cell. After this, your friend will be in the cell $$$(2, 1)$$$.  All friends in the second row should move to the next cell. After this, your friend will be in the cell $$$(2, 2)$$$. In the second test case you can remove all snow from the columns $$$3$$$ and $$$4$$$ for $$$22$$$ coins. Then you can give instructions   All friends in the first row should move to the next cell.  All friends in the first row should move to the next cell.  All friends in the second row should move to the next cell.  All friends in the second row should move to the next cell.  All friends in the third column should move to the next cell.  All friends in the third column should move to the next cell.  All friends in the fourth column should move to the next cell.  All friends in the fourth column should move to the next cell. It can be shown that none of the friends will become ill and that it is impossible to spend less coins.

gets.to_i.times do
  n = gets.to_i
  nn = 2 * n
  c = Array.new(nn) { gets.split.map(&:to_i) }

  ans = 0
  (n...nn).each { |i|
    (n...nn).each { |j|
      ans += c[i][j]
      c[i][j] = 0
    }
  }

  ans += [
    c[0][-1],
    c[0][ n],
    c[-1][0],
    c[-1][n - 1]
  ].min

  p ans
end

gets.to_i.times do
  n = gets.to_i
  nn = 2 * n
  c = Array.new(nn) { gets.split.map(&:to_i) }

  ans = 0
  (n...nn).each { |i|
    (n...nn).each { |j|
      ans += c[i][j]
    }
  }

  ans += [
    c[ 0][-1],
    c[ 0][ n],
    c[-1][ 0],
    c[-1][ n]
  ].min

  p ans
end


You are given a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters.A substring of string $$$s$$$ is a continuous segment of letters from $$$s$$$. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it.Let's call some string of length $$$n$$$ diverse if and only if there is no letter to appear strictly more than $$$\frac n 2$$$ times. For example, strings "abc" and "iltlml" are diverse and strings "aab" and "zz" are not.Your task is to find any diverse substring of string $$$s$$$ or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the length of string $$$s$$$. The second line is the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.

Print "NO" if there is no diverse substring in the string $$$s$$$. Otherwise the first line should contain "YES". The second line should contain any diverse substring of string $$$s$$$.

NoteThe first example has lots of correct answers. Please, restrain yourself from asking if some specific answer is correct for some specific test or not, these questions always lead to "No comments" answer.

gets;s=gets.chomp.chars.uniq
puts s.size<2 ? :NO : "YES\n%s%s"%s[0,2]

# http://codeforces.com/contest/1073/problem/A

n = gets.chomp.to_i
s = gets.chomp

A_ORD = 'a'.ord

def solve(n, s)
  results = []

  s.each_char.each_with_index do |char, i|
    new_result = Array.new(26, 0)
    new_ord = char.ord - A_ORD
    new_result[new_ord] = 1

    results.each_with_index do |(result, total, max), j|
      result[new_ord] += 1
      if result[new_ord] > max
        max = result[new_ord]
      end

      return [i, j] if max <= (total + 1) / 2

      results[j] = [result, total + 1, max]
    end

    results << [new_result, 1, 1]
  end

  nil
end

result = solve(n, s)

if result.nil?
  puts 'NO'
else
  puts 'YES'
  i, j = result
  puts s[j..i]
end

len = gets.strip.to_i
str = gets.strip

diff = false

last_char = str[0]
skip = true
out = nil
str.each_char do |c|
    if skip
        skip = false
        next
    end
    if c != last_char
        out = last_char + c
        break
    end
end

if out.nil?
    puts "NO"
else
    puts "YES"
    puts out
end

s=gets.chomp.chars.uniq
puts s.size<2 ? :NO : "YES\n%s %s"%[s,2]

gets;s=gets.chomp.chars.uniq
puts s.size<2 ? :NO : "YES\n%s %s"%s[0,2]

# http://codeforces.com/contest/1073/problem/A

n = gets.chomp.to_i
s = gets.chomp

def solve(n, s)
  last_result = {}
  results = [last_result]

  s.each_char do |char|
    new_result = last_result.dup
    new_result[char] ||= 0
    new_result[char] += 1
    last_result = new_result
    results << new_result
  end

  length = results.length

  length.times do |i|
    (i - 1).times do |j|
      differences = results[i].inject({}) do |result, (char, count)|
        j_count = results[j][char] || 0
        result.merge(char => count - j_count)
      end

      total_count = differences.inject(0) { |sum, (_, count)| sum + count }

      differences.each do |char, count|
        if count <= total_count / 2
          return [i-1, j]
        end
      end
    end
  end

  nil
end

result = solve(n, s)

if result.nil?
  puts 'NO'
else
  puts 'YES'
  i, j = result
  puts s[j..i]
end


ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1.When ZS the Coder is at level k, he can :  Press the ' + ' button. This increases the number on the screen by exactly k. So, if the number on the screen was x, it becomes x + k. Press the '' button. Let the number on the screen be x. After pressing this button, the number becomes . After that, ZS the Coder levels up, so his current level becomes k + 1. This button can only be pressed when x is a perfect square, i.e. x = m2 for some positive integer m. Additionally, after each move, if ZS the Coder is at level k, and the number on the screen is m, then m must be a multiple of k. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5.ZS the Coder needs your help in beating the game — he wants to reach level n + 1. In other words, he needs to press the '' button n times. Help him determine the number of times he should press the ' + ' button before pressing the '' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level n + 1, but not necessarily a sequence minimizing the number of presses.

The first and only line of the input contains a single integer n (1 ≤ n ≤ 100 000), denoting that ZS the Coder wants to reach level n + 1.

Print n non-negative integers, one per line. i-th of them should be equal to the number of times that ZS the Coder needs to press the ' + ' button before pressing the '' button at level i.  Each number in the output should not exceed 1018. However, the number on the screen can be greater than 1018. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them.

NoteIn the first sample case:On the first level, ZS the Coder pressed the ' + ' button 14 times (and the number on screen is initially 2), so the number became 2 + 14·1 = 16. Then, ZS the Coder pressed the '' button, and the number became . After that, on the second level, ZS pressed the ' + ' button 16 times, so the number becomes 4 + 16·2 = 36. Then, ZS pressed the '' button, levelling up and changing the number into .After that, on the third level, ZS pressed the ' + ' button 46 times, so the number becomes 6 + 46·3 = 144. Then, ZS pressed the '' button, levelling up and changing the number into . Note that 12 is indeed divisible by 4, so ZS the Coder can reach level 4.Also, note that pressing the ' + ' button 10 times on the third level before levelling up does not work, because the number becomes 6 + 10·3 = 36, and when the '' button is pressed, the number becomes  and ZS the Coder is at Level 4. However, 6 is not divisible by 4 now, so this is not a valid solution.In the second sample case:On the first level, ZS the Coder pressed the ' + ' button 999999999999999998 times (and the number on screen is initially 2), so the number became 2 + 999999999999999998·1 = 1018. Then, ZS the Coder pressed the '' button, and the number became . After that, on the second level, ZS pressed the ' + ' button 44500000000 times, so the number becomes 109 + 44500000000·2 = 9·1010. Then, ZS pressed the '' button, levelling up and changing the number into . Note that 300000 is a multiple of 3, so ZS the Coder can reach level 3.

$vis = Array.new(100005,0)
def cal
	pre = 2
    sim = 2
    for i in 1...100002
        pre /= i
        n = i
        while true
            cur = i * n * n + 2 * n * n + (n * n / i)
            if cur >= pre
                $vis[i] = cur - pre
                pre = (i+1) * n
                break
            end
        end
        sim = (sim + ($vis[i] * i))
        temp = Math.sqrt(sim).to_i
        if (temp * temp != sim || temp % (i+1) != 0)
            puts temp
        end
        sim = temp
	end
end

cal()

N = gets.to_i
for i in 1..N
	puts $vis[i]
end

n = gets.to_i

puts 2

(2..n).each do |k|
  puts k*(k+1)*(k+1) - (k-1)
end

n = gets.chomp.to_i

ans = [2]
for k in 2..n
  x = (k - 1) * k
  y = k * (k + 1)
  ans << (y**2 - x) / k
end
puts ans.*"\n"

n = gets.to_i
sr = 2
x = 2
ans = [2]
2.upto(n) do |m|
  sr = sr + 2 * m
  ans << (sr * sr - x) / m
  x = sr
end
ans.each{|x| puts x}

level = gets.chomp.to_i

(1..level).each do |l|
    puts 2 if l == 1
    puts l * (l + 1) * (l + 1) - (l - 1) if l != 1
end

def gcd(a, b)
  return a if b == 0
  return gcd(b, a % b)
end

def lcm(a, b)
  return a * b / gcd(a, b)
end

n = gets.to_i

cur = 2
1.upto(n) do |ni|
  nxt = lcm(ni, ni + 1)
  k = (nxt * nxt - cur) / ni
  puts k
  cur = nxt
end

n=gets.to_i()
m=2
(1..n).each{|k|
	b=k*k+k
	puts (b*b-m)/k
	m=b
}

n = gets.chomp.to_i

x = 2
for k in 1..n
  x = k * (k + 1)
  y = k * (k + 1) * (k + 2)
  puts (y**2 - x) / k
end

n = gets.to_i
sr = 2
x = 2
ans = []
2.upto(n) do |m|
  sr = sr + 2 * m
  ans << (sr * sr - x) / m
  x = sr
end
ans.each{|x| puts x}

level = gets.chomp.to_i
level += 1

target = level ** 2
current = 1
number = 2

until current == level
hit = target - number * current

number = target ** 0.5

current += 1
until number % current == 0
	current += 1
end

puts hit
#puts "Number = #{number}"
#puts "Hit = #{hit}"
#puts "Curr = #{current}"
end

level = gets.chomp.to_i
level += 1

target = level ** 2
current = 1
number = 2

until current == level
hit = target - number * current

number = target ** 0.5

current += 1
until number % current == 0
	current += 1
end

puts hit.to_i
#puts "Number = #{number}"
#puts "Hit = #{hit}"
#puts "Curr = #{current}"
end

level = gets.chomp.to_i
level += 1

target = (level ** 2) * 4
current = 1
number = 2

until current == level
hit = (target - number) / current

number = target ** 0.5

current += 1
until number % current == 0
	current += 1
end

puts hit.to_i
#puts "Number = #{number}"
#puts "Hit = #{hit}"
#puts "Curr = #{current}"
end

level = gets.chomp.to_i
level += 1

target = level ** 2
current = 1
number = 2

until current == level
hit = (target - number) / current

number = target ** 0.5

current += 1
until number % current == 0
	current += 1
end

puts hit.to_i
#puts "Number = #{number}"
#puts "Hit = #{hit}"
#puts "Curr = #{current}"
end


There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights.    Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1] Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly k consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such k consecutive planks that the sum of their heights is minimal possible.Write the program that finds the indexes of k consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).

The first line of the input contains integers n and k (1 ≤ n ≤ 1.5·105, 1 ≤ k ≤ n) — the number of planks in the fence and the width of the hole for the piano. The second line contains the sequence of integers h1, h2, ..., hn (1 ≤ hi ≤ 100), where hi is the height of the i-th plank of the fence.

Print such integer j that the sum of the heights of planks j, j + 1, ..., j + k - 1 is the minimum possible. If there are multiple such j's, print any of them.

NoteIn the sample, your task is to find three consecutive planks with the minimum sum of heights. In the given case three planks with indexes 3, 4 and 5 have the required attribute, their total height is 8.

INF =  1.5 * 10 * 10 * 10 * 10 * 10  * 1000

tmp = gets.chomp.split(" ")
n, k = tmp[0].to_i, tmp[1].to_i
fence = gets.chomp.split(" ").map!{|v| v.to_i}
for i in 1...fence.size do
  fence[i] += fence[i - 1]
end
fence = [0] + fence
ans, max = 0, INF
for i in 0...(fence.size - k) do
  if (max > fence[i + k] - fence[i])
    ans = i + 1
    max = fence[i + k] - fence[i]
  end
end
puts ans

n,w=gets.split.map{|e| e.to_i}
a=gets.split.map{|e| e.to_i}

s=0
ans=1
w.times{|i|
	s+=a[i]
}
t=s
1.upto(n-w){|i|
	s=s+a[i+w-1]-a[i-1]
	if t>s then
		t=s
		ans=i+1
	end
}
puts ans

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

min = h[0...k].inject(0) {|sum, i| sum += i}
min_index = 0
last_sum = min
(k...n).each do |i|
  last_sum = last_sum + h[i] - h[i-k]
  if min > last_sum
    min_index = i - k + 1
    min = last_sum
  end
end

puts min_index + 1

# coding: utf-8

# if __FILE__ == $0
# end

n, k = gets.split.map(&:to_i)
hs = gets.split.map(&:to_i)
hsum = hs[0...k].reduce(:+)
minimum_hsum = hsum
minimum_idx = 1 #zero-based
(0...(n-k)).each { |idx|
    hsum -= hs[idx]
    hsum += hs[idx + k]

    if hsum < minimum_hsum
        minimum_hsum = hsum
        minimum_idx = idx + 1 + 1 # one-based, exact index
    end
}

puts minimum_idx

def solution(fence, take)
  cost = Array.new(fence.size, Float::INFINITY)
  cost[0] = fence[0...take].reduce(:+)

  for i in 1...fence.size-take+1 do
    cost[i] = cost[i-1] - fence[i-1] + fence[i + take - 1]
  end

  remove = 0
  min_cost = Float::INFINITY
  cost.each_with_index do |c, index|
    if min_cost > c
      min_cost = c
      remove = index
    end
  end
  remove + 1
end

tables, take = gets.split.map(&:to_i)
fence = gets.split.map(&:to_i)

puts solution(fence, take)

def solution(fence, take)
  prefix_sum = fence.inject([0]) { |v, i| v << v.last + i }

  min_cost = Float::INFINITY
  for i in 0...prefix_sum.size-take do
    if min_cost > prefix_sum[i+take] - prefix_sum[i]
      min_cost = prefix_sum[i+take] - prefix_sum[i]
      index = i + 1
    end
  end
  index
end

tables, take = gets.split.map(&:to_i)
fence = gets.split.map(&:to_i)

puts solution(fence, take)

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = []
c = 0
n.times do |i|
  c += a[i]
  if i >= k - 1
    b << c
    c -= a[i - k + 1]
  end
end
puts b.index(b.min) + 1

s = gets.split.map(&:to_i)
n = s[0]
k = s[1]
a = gets.split.map(&:to_i)

sum = Array.new(n + 1, 0)
minimum = 10000000000
best = 0

1.upto(n) do |i|
    sum[i] = sum[i - 1] + a[i - 1]
    if i >= k
        sumk = sum[i] - sum[i - k]
        if sumk < minimum
            minimum = sumk
            best = i - k + 1
        end
    end
end

puts best

n, k = gets.split.map{|x| x.to_i}
h = gets.split.map{|x| x.to_i}
a = [h[0..k-1].inject(0){|s, x| s + x}]
(k..n-1).each{|i| a << a.last + h[i] - h[i - k]}
puts(a.index(a.min) + 1)

n, k = gets.split(' ').map(&:to_i)
a = gets.split(' ').map(&:to_i)
a.unshift(0)

sum = 0
ans = -1
min = 1_000_000_000
a.each_with_index do |e, i|
  sum += e
  sum -= a[i-k] if i>k

  if i >= k && min > sum
    min = sum
    ans = i - k + 1
  end
end

puts ans

line = gets.chomp.split(" ").map {|e| e.to_i}
n = line[0]
k = line[1]

hs = gets.chomp.split(" ").map {|e| e.to_i}

if k == 1
  min = -1
  minInd = -1
  for i in 0...(hs.length)
    if min == -1 || hs[i] < min
      min = hs[i]
      minInd = i + 1
    end
  end
  puts minInd
else
  ps = [0]

  acc = 0
  for i in 0...(hs.length)
    acc += hs[i]
    ps.push acc
  end

  min = -1
  minInd = -1
  for i in k..(hs.length)
    t = ps[i] - ps[i - k]
    if min == -1 || t < min
      min = t
      minInd = i - k
    end
  end

  puts (minInd + 1)
end

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

min = h[0...k].inject(0) {|sum, i| sum += i}
last_sum = min
(k...n).each do |i|
  last_sum = last_sum + h[i] - h[i-k]
  min = last_sum if min > last_sum
end

puts min

# coding: utf-8

# if __FILE__ == $0
# end

n, k = gets.split.map(&:to_i)
hs = gets.split.map(&:to_i)
hsum = hs[0...k].reduce(:+)
minimum_hsum = hsum
minimum_idx = 0 #zero-based
(0...(n-k)).each { |idx|
    hsum -= hs[idx]
    hsum += hs[idx + k]

    if hsum < minimum_hsum
        minimum_hsum = hsum
        minimum_idx = idx
    end
}

# p [minimum_idx, minimum_hsum]
puts minimum_idx+1+1 #1-based index, another one for obtaining exact index

def solution(fence, take)
  prefix_sum = fence.inject([0]) { |v, i| v << v.last + i }

  min_cost = Float::INFINITY
  index = 1

  for i in 1...fence.size-take do
    if min_cost > prefix_sum[i+take-1] - prefix_sum[i-1]
      min_cost = prefix_sum[i+take-1] - prefix_sum[i-1]
      index = i
    end
  end
  index
end

tables, take = gets.split.map(&:to_i)
fence = gets.split.map(&:to_i)

puts solution(fence, take)

def solution(fence, take)

  prefix_sum = fence.inject([0]) { |v, i| v << v.last + i }

  min_cost = Float::INFINITY
  index = -1

  for i in 1...fence.size-take do
    if min_cost > prefix_sum[i+take-1] - prefix_sum[i-1]
      min_cost = prefix_sum[i+take-1] - prefix_sum[i-1]
      index = i
    end
  end
  index
end

tables, take = gets.split.map(&:to_i)
fence = gets.split.map(&:to_i)

puts solution(fence, take)

n, k = gets.split(' ').map(&:to_i)
a = gets.split(' ').map(&:to_i)
a.unshift(0)

sum = 0
ans = -1
min = 1_000_000
a.each_with_index do |e, i|
  sum += e
  sum -= a[i-k] if i>k

  if i >= k && min > sum
    min = sum
    ans = i - k + 1
  end
end

puts ans

line = gets.chomp.split(" ").map {|e| e.to_i}
n = line[0]
k = line[1]

hs = gets.chomp.split(" ").map {|e| e.to_i}

if k == 1
  min = -1
  minInd = -1
  for i in 0...(hs.length)
    if min == -1 || hs[i] < min
      min = hs[i]
      minInd = i + 1
    end
  end
  puts minInd
else
  ps = []

  acc = 0
  for i in 0...(hs.length)
    acc += hs[i]
    ps.push acc
  end

  min = -1
  minInd = -1
  for i in (k - 1)...(hs.length)
    t = ps[i] - ps[i - k + 1]
    if min == -1 || t < min
      min = t
      minInd = i - k + 1
    end
  end

  puts (minInd + 1)

end

line = gets.chomp.split(" ").map {|e| e.to_i}
n = line[0]
k = line[1]

hs = gets.chomp.split(" ").map {|e| e.to_i}

if k == 1
  min = -1
  minInd = -1
  for i in 0...(hs.length)
    if min == -1 || hs[i] < min
      min = hs[i]
      minInd = i + 1
    end
  end
  puts minInd
else
  ps = [0]

  acc = 0
  for i in 0...(hs.length)
    acc += hs[i]
    ps.push acc
  end

  min = -1
  minInd = -1
  for i in k...(hs.length)
    t = ps[i] - ps[i - k]
    if min == -1 || t < min
      min = t
      minInd = i - k
    end
  end

  puts (minInd + 1)
end

line = gets.chomp.split(" ").map {|e| e.to_i}
n = line[0]
k = line[1]

hs = gets.chomp.split(" ").map {|e| e.to_i}
ps = []

acc = 0
for i in 0...(hs.length)
  acc += hs[i]
  ps.push acc
end

min = -1
minInd = -1
for i in (k - 1)...(hs.length)
  t = ps[i] - ps[i - k + 1]
  if min == -1 || t < min
    min = t
    minInd = i - k + 1
  end
end

puts (minInd + 1)


Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can multiply or divide your number by $$$2$$$, $$$4$$$ or $$$8$$$, and division is only allowed if the number is divisible by the chosen divisor. Formally, if the register contains a positive integer $$$x$$$, in one operation it can be replaced by one of the following:   $$$x \cdot 2$$$  $$$x \cdot 4$$$  $$$x \cdot 8$$$  $$$x / 2$$$, if $$$x$$$ is divisible by $$$2$$$  $$$x / 4$$$, if $$$x$$$ is divisible by $$$4$$$  $$$x / 8$$$, if $$$x$$$ is divisible by $$$8$$$ For example, if $$$x = 6$$$, in one operation it can be replaced by $$$12$$$, $$$24$$$, $$$48$$$ or $$$3$$$. Value $$$6$$$ isn't divisible by $$$4$$$ or $$$8$$$, so there're only four variants of replacement.Now Johnny wonders how many operations he needs to perform if he puts $$$a$$$ in the register and wants to get $$$b$$$ at the end.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The following $$$t$$$ lines contain a description of test cases. The first and only line in each test case contains integers $$$a$$$ and $$$b$$$ ($$$1 \leq a, b \leq 10^{18}$$$) — the initial and target value of the variable, respectively.

Output $$$t$$$ lines, each line should contain one integer denoting the minimum number of operations Johnny needs to perform. If Johnny cannot get $$$b$$$ at the end, then write $$$-1$$$.

NoteIn the first test case, Johnny can reach $$$5$$$ from $$$10$$$ by using the shift to the right by one (i.e. divide by $$$2$$$).In the second test case, Johnny can reach $$$44$$$ from $$$11$$$ by using the shift to the left by two (i.e. multiply by $$$4$$$).In the third test case, it is impossible for Johnny to reach $$$21$$$ from $$$17$$$.In the fourth test case, initial and target values are equal, so Johnny has to do $$$0$$$ operations.In the fifth test case, Johnny can reach $$$3$$$ from $$$96$$$ by using two shifts to the right: one by $$$2$$$, and another by $$$3$$$ (i.e. divide by $$$4$$$ and by $$$8$$$).

def solve(num)
  start = num[0].to_i.to_s(2)
  target = num[1].to_i.to_s(2)
  start_index = start.index("1")
  target_index = target.index("1")
  start = start[start_index..-1]
  target = target[target_index..-1]
  start_rindex = start.rindex("1")
  target_rindex = target.rindex("1")
  return -1 if start_rindex != target_rindex
  i = 0
  while i <= start_rindex
    return -1 if start[i] != target[i]
    i += 1
  end
  longer = [start.length, target.length].max
  shorter = [start.length, target.length].min
  diff = longer - shorter
  (diff / 3.0).ceil
end

amount = gets.chomp.to_i
amount.times do
  input = gets.chomp.split(" ")
  puts solve(input)
end

def solve(num)
  start = num[0].to_i.to_s(2)
  target = num[1].to_i.to_s(2)
  i = 0
  while start[i] == 0
    start.shift
  end
  i = 0
  while target[i] == 0
    target.shift
  end
  start_index = start.rindex("1")
  target_index = target.rindex("1")
  return -1 if start_index != target_index
  i = 0
  while i <= start_index
    foo = start[i]
    bar = target[i]
    return -1 if foo != bar
    i += 1
  end

  foo = [start.length, target.length].max
  baz = [start.length, target.length].min
  t = foo - baz
  (t / 3.0).ceil

end

amount = gets.chomp.to_i
amount.times do
  input = gets.chomp.split(" ")
  puts solve(input)
end

t = 0
t = gets.chomp.to_i

while t>0
    a,b = gets.chomp.split(' ').map{|a| a.to_i}
    #puts "Value of a is" ,a
    #puts "Value of b is ",b
    i = 0
    min = 0
    value = 0
    if a < b
        while(a<b)
            a=a*2
            i+= 1
        end

    else
        while(b<a)
            b=b*2
            i+=1
        end
    end

    if a!=b
        puts "-1"
    else
        min = [1,i%3].min
        value = i/3 + min
        puts value
    end
    t = t - 1
end

data_lines = gets.chomp
input_values = []
(1..data_lines.to_i).each do
	input_str = gets.chomp
	val1, val2 = input_str.split(" ")
	input_values.push [val1.to_i, val2.to_i]
end

input_values.each do |values_pair|
	from_value = values_pair[0]
	to_value = values_pair[1]
	if from_value == to_value
		puts 0
		next
	end
	if from_value > to_value
		if from_value % to_value > 0
			puts -1
			next
		end
		if (from_value / to_value) % 2 > 0
			puts -1
			next
		end
	end
	if to_value > from_value
		if to_value % from_value > 0
			puts -1
			next
		end
		if (to_value / from_value) % 2 > 0
			puts -1
			next
		end
	end
	result = nil
	iter = 0
	if from_value > to_value
		tmp = to_value
		to_value = from_value
		from_value = tmp
	end
	# p 'from_value = ' + from_value.to_s
	# p 'to_value = ' + to_value.to_s

	while from_value != to_value
		# p 'from_value = ' + from_value.to_s
		iter += 1

		if to_value >= from_value * 8
			# p 'yes'
			from_value = from_value * 8
		elsif to_value >= from_value * 4
			# p 'yes2'
			from_value = from_value * 4
		elsif to_value >= from_value * 2
			# p 'yes3'
			from_value = from_value * 2
		else
			from_value = to_value
			iter = -1
		end
	end
	puts iter
end


Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s.

The first line contains the s line which is the inputted part. The second line contains an integer n (1 ≤ n ≤ 100) which is the number of visited pages. Then follow n lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only.

If s is not the beginning of any of n addresses of the visited pages, print s. Otherwise, print the lexicographically minimal address of one of the visited pages starting from s. The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages.

s = gets.chomp!
n = gets.to_i
visited = $stdin.readlines.map(&:chomp!).sort!
t = visited.bsearch{|x| x >= s}
if t.nil? or (/#{s}/ =~ t) != 0
  puts s
else
  puts t
end

word = gets.strip
n    = gets.to_i

a = []
o = []

for i in 0..(n-1)
  a << gets.strip
end

a.each {|x| o << x if x.start_with?(word) }

o.length == 0 ? (puts word) : (puts o.min)

str = STDIN.gets.chomp
n   = STDIN.gets.to_i
lines = []
n.times { lines << STDIN.gets.chomp }

lines.sort.each do |line|
  if line.rindex(str) == 0
    puts line
    exit
  end
end
puts str

s, n = gets.chomp, gets.to_i
lines = []
n.times { lines << gets.chomp }

lines.sort.each do |line|
  if line.start_with?(s)
    puts line; exit
  end
end
puts s

=begin 59A - Word
str = gets.chomp
lower = 0
upper = 0
str.each_char { |w| /[[:lower:]]/.match(w) ? lower+= 1 : upper+= 1 }
puts upper > lower ? str.upcase : str.downcase
=end
str = gets.chomp
n = gets.to_i
out = nil
while n > 0
	tmp = gets.chomp
  if /\A#{str}[[:lower:]]*/.match(tmp)
    if out.nil? || tmp < out
      out = tmp
    end
  end
  n-=1
end
puts out.nil? ? str : out

s=gets.strip
n=gets.to_i
m=""
n.times{|i| w=gets.strip; m=(m<w && !m.empty?)?m:w if w.start_with? s}
puts (m.empty?)?s:m

s = gets.chomp!
n = gets.to_i

mas = Array.new()
for i in 0..n-1
  mas[i] = gets.chomp!
end

mas.sort!
for i in 0..n-1
  if (mas[i].index(s) == 0)
    puts mas[i]
    exit
  end
end

puts s

str = gets.chomp
num = gets.chomp.to_i

lines = []
num.times {|i|
  lines << gets.chomp
}

regexp = Regexp.new("^" + str)
strs = lines.select {|line| regexp =~ line}
if strs.length == 0
  puts str
else
  puts strs.sort[0]
end

s = gets.strip
a = []

gets.to_i.times {
    n = gets.strip
    a.push n if n.start_with? s
}

puts a.empty? ? s : a.sort.first

str = STDIN.gets.chomp
n   = STDIN.gets.to_i
lines = []
n.times { lines << STDIN.gets.chomp }
lines.sort!

lines.each do |line|
  if line.rindex(str) == 0
    puts line
    exit
  end
end
puts str

str = gets.strip; gets; auto = []
while g = gets; auto.push g.strip; end
s = auto.sort.grep(/^#{str}+/).first
print s ? s : str

=begin 59A - Word
str = gets.chomp
lower = 0
upper = 0
str.each_char { |w| /[[:lower:]]/.match(w) ? lower+= 1 : upper+= 1 }
puts upper > lower ? str.upcase : str.downcase
=end
str = gets.chomp
n = gets.to_i
max = 101
out = str
while n > 0
	tmp = gets.chomp
  if /\A#{str}[[:lower:]]*/.match(tmp)
    if tmp.size < max
      max = tmp.size
      out = tmp
    end
  end
  n-=1
end
puts out

=begin 59A - Word
str = gets.chomp
lower = 0
upper = 0
str.each_char { |w| /[[:lower:]]/.match(w) ? lower+= 1 : upper+= 1 }
puts upper > lower ? str.upcase : str.downcase
=end
str = gets.chomp
n = gets.to_i
max = 101
out = str
while n > 0
	tmp = gets.chomp
  if /\A#{str}[[:lower:]]*/.match(tmp)
    if tmp.size < max
      max = tmp.size
      out = tmp
    elsif tmp.size == max
      out = tmp < out ? tmp : out
    end
  end
  n-=1
end
puts out

s=gets.strip
n=gets.to_i # n can bo omitted in calculations
ok=false
m=""
n.times{|i| w=gets.strip; m,ok=((m<w || !ok)?m:w),true if w.start_with? m}
puts (ok ? m : s)


Given an array a1, a2, ..., an of n integers, find the largest number in the array that is not a perfect square.A number x is said to be a perfect square if there exists an integer y such that x = y2.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array. The second line contains n integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — the elements of the array. It is guaranteed that at least one element of the array is not a perfect square.

Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists.

NoteIn the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2.

n,*a=$<.read.split.map &:to_i
p a.sort_by(&:-@).find{|e|e<0||Math.sqrt(e).to_i**2!=e}

n = gets.to_i
a = gets.split.map(&:to_i)
a.sort!
k = a.pop
while k >= 0 && (k ** 0.5).to_i ** 2 == k do
  k = a.pop
end
puts k

#!usr/local/bin/ruby -w

def isPerfectSqr?(a)
	k = Math.sqrt(a).ceil
	if(k*k == a) then return true
	else
		return false
	end
end

n = gets.chomp.to_i

arr = gets.split.map{|i| i.to_i}

ans = -1e7;

arr.each do |a|
	if(a<0 || !isPerfectSqr?(a) ) then ans = [ans,a].max end
end

puts ans

n = gets.to_i
num = gets.chomp.split(' ').map{|n| n.to_i }.sort
address = n -1
while (address > 0) do
  if num[address] == -1
    break
  end
  if ((Math.sqrt(num[address].abs) -  Math.sqrt(num[address].abs).to_i) != 0)
    break
  end
  address = address - 1
end

puts num[address]

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

a.each{|t|
  y = Math.sqrt(t.abs).to_i
  if y*y!=t
    puts t
    exit
  end
}

gets
p gets.split.map(&:to_i).select {|x| x < 0 || Math.sqrt(x).modulo(1) != 0}.max

a = gets.to_i
array = gets.chomp.split(" ")
array = array.map { |n| n.to_i }
x = array.select { |n| n>=0 and Math.sqrt(n)%1!=0 }.max
y = array.select { |n| n<0 }.max
ans = []
if x !=nil
    ans << x
end

if y !=nil
    ans << y
end

if ans.length !=0
    puts ans.max
end

n = gets.to_i
a = gets.split.map(&:to_i)
a.sort!
k = a.pop
while k > 0 && (k ** 0.5).to_i ** 2 == k do
  k = a.pop
end
puts k

n = gets.to_i
num = gets.chomp.split(' ').map{|n| n.to_i }.sort
address = n -1
while (address > 0) do
  if num[address].abs == 1
    break
  end
  if ((Math.sqrt(num[address].abs) -  Math.sqrt(num[address].abs).to_i) != 0)
    break
  end
  address = address - 1
end

puts num[address]

n = gets.to_i
num = gets.chomp.split(' ').map{|n| n.to_i }.sort
address = n -1
while (address > 0) do
  if ((Math.sqrt(num[address].abs) -  Math.sqrt(num[address].abs).to_i) != 0)
    break
  end
  address = address - 1
end
puts num[address]

n = gets.to_i
num = gets.chomp.split(' ').map{|n| n.to_i }
address = n -1
while (address > 0) do
  if ((Math.sqrt(num[address].abs) -  Math.sqrt(num[address].abs).to_i) != 0)
    break
  end
  address = address - 1
end
puts num[address]

gets
p gets.split.map(&:to_i).select {|x| x >= 0 && Math.sqrt(x).modulo(1) != 0}.max

n=gets.to_i;p gets.split.map(&:to_i).reject{|x|x<0 or Math.sqrt(x).floor**2==x}.sort[-1]

a = gets.to_i
array = gets.chomp.split(" ")
array = array.map { |n| n.to_i }
x = array.select { |n| n>=0 and (Math.sqrt(n)%1!=0 or n==1) }.max
y = array.select { |n| n<0 }.max
ans = []
if x !=nil
    ans << x
end

if y !=nil
    ans << y
end

if ans.length !=0
    puts ans.max
end

a = gets.to_i
array = gets.chomp.split(" ")
array = array.map { |n| n.to_i }
x = array.select { |n| n>=0 and (Math.sqrt(n)%1!=0 or n==1) }.max
y = array.select { |n| n<0 and (Math.sqrt(n*-1)%1!=0 or n==-1) }.max
ans = []
if x !=nil
    ans << x
end

if y !=nil
    ans << y
end

if ans.length !=0
    puts ans.max
end

a = gets.to_i
array = gets.chomp.split(" ")
array = array.map { |n| n.to_i }
x = array.select { |n| n>=0 and Math.sqrt(n)%1!=0 }.max
y = array.select { |n| n<0 and Math.sqrt(n*-1)%1!=0 }.max
ans = []
if x !=nil
    ans << x
end

if y !=nil
    ans << y
end

if ans.length !=0
    puts ans.max
end


In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction).Write a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.

The first line of the input contains n (2 ≤ n ≤ 1000) — number of bidders. The second line contains n distinct integer numbers p1, p2, ... pn, separated by single spaces (1 ≤ pi ≤ 10000), where pi stands for the price offered by the i-th bidder.

The single output line should contain two integers: index of the winner and the price he will pay. Indices are 1-based.

#!/usr/bin/ruby
gets
a=gets.split.map(&:to_i).each_with_index.to_a.sort.reverse
puts "#{a[0].last+1} #{a[1].first}"

n = gets.to_i
dx = gets.split().map{|i| i.to_i }
i = dx.index(dx.max) + 1
dx.sort!.reverse!
puts i.to_s + " " + dx[1].to_s

# https://codeforces.com/problemset/problem/386/A

gets
bids = gets.split(' ').map(&:to_i)

highest_bid = 0
highest_bid_index = 0
second_highest_bid = 0

bids.each_with_index do |bid, index|
  if bid > highest_bid
    second_highest_bid = highest_bid
    highest_bid = bid
    highest_bid_index = index
  elsif bid > second_highest_bid
    second_highest_bid = bid
  end
end

puts "#{highest_bid_index+1} #{second_highest_bid}"

n=gets.to_i
mas=gets.split.map &:to_i
i=mas.index(mas.max)+1
mas[mas.index(mas.max)]=-1
puts "#{i} #{mas.max}"

n = gets.to_i
v = gets.split.map(&:to_i)
ans = v.map.with_index.to_a.sort{ |a, b| b[0] <=> a[0] }
puts "#{ans[0][1] + 1} #{ans[1][0]}"


Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area. Formally, the carrot can be viewed as an isosceles triangle with base length equal to 1 and height equal to h. Igor wants to make n - 1 cuts parallel to the base to cut the carrot into n pieces. He wants to make sure that all n pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area?  Illustration to the first example.

The first and only line of input contains two space-separated integers, n and h (2 ≤ n ≤ 1000, 1 ≤ h ≤ 105).

The output should contain n - 1 real numbers x1, x2, ..., xn - 1. The number xi denotes that the i-th cut must be made xi units away from the apex of the carrot. In addition, 0 < x1 < x2 < ... < xn - 1 < h must hold.  Your output will be considered correct if absolute or relative error of every number in your output doesn't exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .

NoteDefinition of isosceles triangle: https://en.wikipedia.org/wiki/Isosceles_triangle.

n,h = gets.split.map(&:to_f)
for i in 1..n-1
p h*((i/n)**0.5)
end

n, h = gets.chomp.split(" ").map(&:to_f)
b = 1

hh = h / Math.sqrt(n)

(n.to_i - 1).times do |i|
  print(hh * Math.sqrt(i+1), " ")
end
puts

n, h = gets.chomp.split.map(&:to_i)
a = []
(1...n).each { |i|
   a << Math.sqrt(i.to_f / n) * h
}
puts a.map(&:to_s).join(' ')


Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark "?". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s="ab?b" as a result, it will appear in t="aabrbb" as a substring.Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol "?" should be considered equal to any other symbol.

The first line contains two integers n and m (1 ≤ n ≤ m ≤ 1000) — the length of the string s and the length of the string t correspondingly. The second line contains n lowercase English letters — string s. The third line contains m lowercase English letters — string t.

In the first line print single integer k — the minimal number of symbols that need to be replaced. In the second line print k distinct integers denoting the positions of symbols in the string s which need to be replaced. Print the positions in any order. If there are several solutions print any of them. The numbering of the positions begins from one.

def go a, b
  res = []
  for i in 0..(a.length)
    if a[i] != b[i]
      res.push i
    end
  end

  return res
end

n, m = gets.strip.split.map &:to_i
a = gets.strip
b = gets.strip

res = *(1..n)
for i in 0..(m-n)
  curr = go(a, b[i..i+n-1]).map{ |x| x + 1 }
  if curr.length < res.length
    res = curr
  end
end

print res.length.to_s + "\n"
res.each{ |x| print x.to_s + " " }
print "\n"

sub_str_length, str_length = gets.split.map(&:to_i)

sub_str = gets.chomp
str = gets.chomp
min_replacements = 1000;
min_replace = *(1..sub_str_length)

def string_diff(str1, str2)
  return [] if (str1 == str2)
  (0..str1.length).map { |i| i + 1 if str1[i] != str2[i] }.compact
end

if str == sub_str
  puts 0
elsif sub_str == ''
  puts str.length
else
  (0..(str_length - sub_str_length)).each do |i|
    replacements = string_diff(str[i, sub_str_length], sub_str)
    min_replace == replacements if i == 0
    if replacements.empty?
      min_replacements = 0
      min_replace = []
      break
    elsif replacements.length < min_replacements
      min_replacements = replacements.length
      min_replace = replacements
    end
  end
  puts min_replacements
  puts min_replace.join(' ')
end

inp = gets.split(' ')

a = gets.chomp
b = gets.chomp

def match(a,b)
	min_errors_size = 10**9
	min_errors_array = Array.new
	for i in (0..b.size-a.size)
		errors = []
		for j in (0..a.size-1)
			if a[j]!=b[i+j]
					errors << j+1
			end
		end
		if errors.size < min_errors_size
			min_errors_array = errors
			min_errors_size = errors.size
		end
	end
	return min_errors_array
end

ans = match(a,b)

puts ans.size

puts ans.join(' ')

str = gets.split(" ")
n = str[0].to_i; m = str[1].to_i
s = gets.chomp
t = gets.chomp

res = []
ans = 1e5

for i in (0...(m-n+1))
      cnt = 0
      temp = []
      k = i
      for j in (0...n)
            if t[k] != s[j]
                  cnt+=1
                  temp.push(j+1)
            end
            k+=1
      end
      if cnt < ans
            ans = cnt
            res = temp
      end
end

print ans
print "\n"

res.each do |val|
      print "#{val} "
end

sub_str_length, str_length = gets.split.map(&:to_i)

sub_str = gets.chomp
str = gets.chomp
min_replacements = 1000;
min_replace = []

def string_diff(str1, str2)
  return [] if(str1 == str2)
  (0..str1.length).map { |i| i + 1 if str1[i] != str2[i] }.compact
end

if str == sub_str
  puts 0
else
  (0..(str_length - sub_str_length)).each do |i|
    replacements = string_diff(str[i, sub_str_length + i - 1], sub_str)
    if replacements.empty?
      min_replacements = 0
      min_replace = []
      break
    elsif replacements.length < min_replacements
      min_replacements = replacements.length
      min_replace = replacements
    end
  end
  puts min_replacements
  puts min_replace.join(' ')
end

sub_str_length, str_length = gets.split.map(&:to_i)

sub_str = gets.chomp
str = gets.chomp
min_replacements = 1000;
min_replace = []

def string_diff(str1, str2)
  return [] if(str1 == str2)
  (0..str1.length).map { |i| i + 1 if str1[i] != str2[i] }.compact
end

if str == sub_str
  puts 0
else
  (0..(str_length - sub_str_length)).each do |i|
    replacements = string_diff(str[i, sub_str_length], sub_str)
    if replacements.empty?
      min_replacements = 0
      min_replace = []
      break
    elsif replacements.length < min_replacements
      min_replacements = replacements.length
      min_replace = replacements
    end
  end
  puts min_replacements
  puts min_replace.join(' ')
end

sub_str_length, str_length = gets.split.map(&:to_i)

sub_str = gets.chomp
str = gets.chomp
min_replacements = 1000;
min_replace = []

def string_diff(str1, str2)
  return [] if(str1 == str2)
  (0..str1.length).map { |i| i + 1 if str1[i] != str2[i] }.compact
end

if str == sub_str
  puts 0
else
  (0..(str_length - sub_str_length)).each do |i|
    replacements = string_diff(str[i, sub_str_length + i], sub_str)
    if replacements.empty?
      min_replacements = 0
      min_replace = []
      break
    elsif replacements.length < min_replacements
      min_replacements = replacements.length
      min_replace = replacements
    end
  end
  puts min_replacements
  puts min_replace.join(' ')
end

sub_str_length, str_length = gets.split.map(&:to_i)

sub_str = gets.chomp
str = gets.chomp
min_replacements = 1000;
min_replace = []

def string_diff(str1, str2)
  return [] if(str1 == str2)
  puts "=====#{str1}========#{str2}===="
  (0..str1.length).map { |i| i + 1 if str1[i] != str2[i] }.compact
end

if str == sub_str
  puts 0
else
  (0..(str_length - sub_str_length)).each do |i|
    replacements = string_diff(str[i, sub_str_length], sub_str)
    if replacements.empty?
      min_replacements = 0
      min_replace = []
      break
    elsif replacements.length < min_replacements
      min_replacements = replacements.length
      min_replace = replacements
    end
  end
  puts min_replacements
  puts min_replace.join(' ')
end

sub_str_length, str_length = gets.split.map(&:to_i)

sub_str = gets.chomp
str = gets.chomp
min_replacements = 1000;
min_replace = []

def string_diff(str1, str2)
  (0..str1.length).map { |i| i + 1 if str1[i] != str2[i] }.compact
end

(0..(str_length - sub_str_length)).each do |i|
  replacements = string_diff(str[i, sub_str_length + i - 1], sub_str)
  if replacements.length < min_replacements
    min_replacements = replacements.length
    min_replace = replacements
  end
end

puts min_replacements
puts min_replace.join(' ')

sub_str_length, str_length = gets.split.map(&:to_i)

sub_str = gets.chomp
str = gets.chomp
min_replacements = 1000;
min_replace = []

def string_diff(str1, str2)
  (0..str1.length).map { |i| i + 1 if str1[i] != str2[i] }.compact
end

(0..(str_length - sub_str_length)).each do |i|
  replacements = string_diff(str[i, sub_str_length + i - 1], sub_str)
  if replacements.length < min_replacements
    min_replacements = replacements.length
    min_replace = replacements
  end
end

puts min_replacements
p min_replace.join(' ')

inp = gets.split(' ')

n = inp.first.to_i
m = inp.last.to_i

a = gets.chomp
b = gets.chomp

def match(a,b)
	min_errors_size = 10**9
	min_errors_array = Array.new
	for i in (0..b.size-1)
		errors = []
		for j in (0..a.size-1)
			if a[j]!=b[i+j]
					errors << j+1
			end
		end
		if errors.size < min_errors_size
			min_errors_array = errors
			min_errors_size = errors.size
		end
	end
	return min_errors_array
end

ans = match(a,b)

puts ans.size

puts ans.join(' ')


Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.According to the schedule, a student can take the exam for the i-th subject on the day number ai. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day bi (bi < ai). Thus, Valera can take an exam for the i-th subject either on day ai, or on day bi. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number ai.Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.

The first line contains a single positive integer n (1 ≤ n ≤ 5000) — the number of exams Valera will take. Each of the next n lines contains two positive space-separated integers ai and bi (1 ≤ bi < ai ≤ 109) — the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly.

Print a single integer — the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date.

NoteIn the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5.In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject.

n, k = STDIN.readline.split.map {|s| s.to_i }
pairs = []
n.times do
	a, b = STDIN.readline.split.map {|s| s.to_i }
	pairs.push([a, b])
end
pairs.sort!
pos = 0
pairs.each do |late, early|
	if early >= pos
		pos = early
	else
		pos = late
	end
end
puts pos

n = gets.chomp.to_i;
arr = Array.new(n);

n.times { |x|
  arr[x] = gets.chomp.split(' ').map(&:to_i);
}
arr.sort!;
pre = -1;

arr.each { |x, y|
  if (pre <= y)
    pre = y;
  else
    pre = x;
  end
}
puts pre;

n=gets.to_i
arr=[]
n.times{|e|
	x=gets.split.map{|e| e.to_i}
	arr<<x
}
arr.sort!
ans=1

arr.each{|e|
	if e[1]<ans
		ans=e[0]
	else
		ans=e[1]
	end
}
puts ans

# coding: utf-8

# if __FILE__ == $0
# end
Day = Struct.new(:a, :b)
n = gets.to_i
days = []
n.times {
    a, b = gets.split.map(&:to_i)
    days << Day.new(a, b)
}
days.sort! { |d1, d2|
    if d1.a != d2.a
        d1.a - d2.a
    else
        d1.b - d2.b
    end
}
# 이전에 풀었던 아이디어가 완전히 틀린 건 아니었음.
# 단, 무조건 마지막 아이템을 참고해서 풀면 언젠가 틀린다.
# days 는 a(원 응시일), b(조기 응시일) 오름차순으로 정렬되어있다.
# 따라서 a 날짜에 따라 각 시험을 응시하면 순서대로 완성되나 최소가 되기 어렵다. (특이한 케이스가 있음)
# 따라서 b의 정보를 참고해서 시험을 응시하게 되는데,
# min_day <= day.b 가 유지되는 경우는
# days의 전체 b정렬상태가 감소하지 않는 추세로 표현된 상태이다.
# 이때는 계속 b의 날짜를 따라 시험을 봐도 되므로, days.last.b 가 성립한다.
# 만약에 b에서 흐름이 깨질 경우가 문제인데,
# 정렬 순서에서 벗어나서 시험을 봐야하므로, b의 날짜에 시험을 볼 수 없다.
# b의 날짜에 볼 경우, 성적표 기재 순서가 바뀌게 됨. 어쩔 수 없이 a 날짜를 택해야한다.
# 그리고 그 날짜 기준으로 b의 날짜에 봤을 때 성적표 기재 순서가 유지되는지 확인해야한다.
# 정렬 흐름에서 깨진 시험의 a날짜는 마지노선이 된다.

min_day = 0
days.each { |day|
    if min_day <= day.b
        min_day = day.b
    else
        min_day = day.a
    end
}

puts min_day

n = Integer(gets)
a = []
nums = []
for i in 0...n
    a[i] = []
    nums[i] = []
    nums[i] = gets.chomp.split
    a[i][0] = Integer(nums[i][0])
    a[i][1] = Integer(nums[i][1])
end

a = a.sort_by{|x,y|[x,y]}
best = -1
for i in 0...n
    if best <= a[i][1]
        best = a[i][1]
    else
        best = a[i][0]
    end
end
print best

n = gets.chomp.to_i
arr = []
for i in (0..n-1)
	arr << gets.chomp.split.map(&:to_i)
end

arr = arr.sort_by{|x| x}

x = arr[0].min
for i in (1..n-1)
	if arr[i].min >= x
		x =  arr[i].min
	else
		x = arr[i].max
	end
end

print x

n = gets.to_i
arr = []
b_arr = []
n.times do
	arr << gets.split(" ").map(&:to_i)
	b_arr << arr[-1][1]
end
arr.sort!
# max_h = {}
# x = arr.chunk{|x| x[0]}.each do |a|
# 	max_h[a[0]] = a[1].collect{|e| e[1]}.max
# end
max = 0
arr.each do |a|
	if max <= a[1]
		max = a[1]
	else
		max = a[0]
	end
end
puts "#{max}"

n = gets.to_i
a = []
n.times do
	a << gets.split.map(&:to_i)
end
a.sort!

prev = 0
n.times do |i|
	prev = a[i][1] >= prev ? a[i][1] : a[i][0]
end
puts prev

n = gets.to_i
a = []
n.times do
  a << gets.chomp.split.map(&:to_i)
end
a.sort!
d = 0
for i in 0...n
  a[i].sort!
  if a[i][0] >= d
    s = a[i][0]
  elsif a[i][1] >= d
    s = a[i][1]
  end
  d = s
end
puts d

# coding: utf-8

# if __FILE__ == $0
# end
Day = Struct.new(:a, :b)
n = gets.to_i
days = []
n.times {
    a, b = gets.split.map(&:to_i)
    days << Day.new(a, b)
}
days.sort! { |d1, d2|
    if d1.a != d2.a
        d1.a - d2.a
    else
        d1.b - d2.b
    end
}
bday_broken = false
bprev = 0
days.each { |day|
    if bprev <= day.b
        bprev = day.b
    else
        bday_broken = true
    end
}

if bday_broken
    puts days.last.a
else
    puts days.last.b
end

# coding: utf-8

# if __FILE__ == $0
# end
Day = Struct.new(:a, :b)
n = gets.to_i
days = []
n.times {
    a, b = gets.split.map(&:to_i)
    days << Day.new(a, b)
}
days.sort! { |d1, d2|
    if d1.a != d2.a
        d1.a - d2.a
    else
        d1.b - d1.b
    end
}
bday_broken = false
bprev = 0
days.each { |day|
    if bprev <= day.b
        bprev = day.b
    else
        bday_broken = true
    end
}

if bday_broken
    puts days.last.a
else
    puts days.last.b
end

n = Integer(gets)
a = []
nums = []
for i in 0...n
    a[i] = []
    nums[i] = []
    nums[i] = gets.chomp.split
    a[i][0] = Integer(nums[i][0])
    a[i][1] = Integer(nums[i][1])
end

a = a.sort_by{|x,y|x}
best = -1
for i in 0...n
    if best <= a[i][1]
        best = a[i][1]
    else
        best = a[i][0]
    end
end
print best

n = Integer(gets)
a = []
nums = []
for i in 0...n
    a[i] = []
    nums[i] = []
    nums[i] = gets.chomp.split
    a[i][0] = Integer(nums[i][0])
    a[i][1] = Integer(nums[i][1])
end
pointer = 1
for i in 0...n-1
    if a[i][0] == a[i + 1][0]
        pointer = 1
    else
        pointer = 0
        break
    end
end
best = -1
if pointer == 0
    a = a.sort_by{|x,y|x}
else
    a = a.sort_by{|x,y|y}
end
for i in 0...n
    if best <= a[i][1]
        best = a[i][1]
    else
        best = a[i][0]
    end
end
print best

n = gets.chomp.to_i
arr = []
for i in (0..n-1)
	arr << gets.chomp.split.map(&:to_i)
end

arr = arr.sort_by{|x,y| x&&y}

x = arr[0].min
for i in (1..n-1)
	if arr[i].min >= x
		x =  arr[i].min
	else
		x = arr[i].max
	end
end

print x

n = gets.chomp.to_i
arr = []
for i in (0..n-1)
	arr << gets.chomp.split.map(&:to_i)
end

arr = arr.sort_by{|x,y| y&&x}

x = arr[0].min
for i in (1..n-1)
	if arr[i].min >= x
		x =  arr[i].min
	else
		x = arr[i].max
	end
end

print x

n = gets.chomp.to_i
arr = []
for i in (0..n-1)
	arr << gets.chomp.split.map(&:to_i)
end

arr = arr.sort_by{|x,y| y&&x}
if arr[0].min <= arr[n-1].min
	print arr[n-1].min
else
	print arr[n-1].max
end

n = gets.to_i
arr = []
b_arr = []
n.times do
	arr << gets.split(" ").map(&:to_i)
	b_arr << arr[-1][1]
end
arr.sort!
max_h = {}
x = arr.chunk{|x| x[0]}.each do |a|
	max_h[a[0]] = a[1].collect{|e| e[1]}.max
end
max = 0
max_h.each do |k,v|
	if max <= v
		max = v
	else
		max = k
	end
end
puts "#{max}"

n = gets.to_i
arr = []
b_arr = []
n.times do
	arr << gets.split(" ").map(&:to_i)
	b_arr << arr[-1][1]
end
arr.sort!
max_h = {}
x = arr.chunk{|x| x[0]}.each do |a|
	max_h[a[0]] = a[1].collect{|e| e[1]}.max
end
max = 0
max_h.each do |k,v|
	if v >= max
		max = v
	else
		max = k
	end
end
puts "#{max}"

n = gets.to_i
arr = []
b_arr = []
n.times do
	arr << gets.split(" ").map(&:to_i)
	b_arr << arr[-1][1]
end
arr.sort!
x = arr.chunk{|x| x[0]}.to_a.last[1].collect{|e| e[1]}
z = x.max
if b_arr.all?{|e| z >= e}
	ans = z
else
	ans = arr[-1][0]
end
puts ans

n = gets.to_i
z = []
n.times {
  z << gets.chomp.split.map(&:to_i)
}

z.sort! { |x, y| x[0] <=> y[0] }
x = z[0][1]
(1...n).each do |i|
  x = z[i][1] >= x ? z[i][1] : z[i][0]
end
puts x


You have $$$n$$$ chains, the $$$i$$$-th chain consists of $$$c_i$$$ vertices. Vertices in each chain are numbered independently from $$$1$$$ to $$$c_i$$$ along the chain. In other words, the $$$i$$$-th chain is the undirected graph with $$$c_i$$$ vertices and $$$(c_i - 1)$$$ edges connecting the $$$j$$$-th and the $$$(j + 1)$$$-th vertices for each $$$1 \le j < c_i$$$.Now you decided to unite chains in one graph in the following way:   the first chain is skipped;  the $$$1$$$-st vertex of the $$$i$$$-th chain is connected by an edge with the $$$a_i$$$-th vertex of the $$$(i - 1)$$$-th chain;  the last ($$$c_i$$$-th) vertex of the $$$i$$$-th chain is connected by an edge with the $$$b_i$$$-th vertex of the $$$(i - 1)$$$-th chain.   Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph.A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of chains you have. The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$2 \le c_i \le 10^9$$$) — the number of vertices in the corresponding chains. The third line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$a_1 = -1$$$; $$$1 \le a_i \le c_{i - 1}$$$). The fourth line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$b_1 = -1$$$; $$$1 \le b_i \le c_{i - 1}$$$). Both $$$a_1$$$ and $$$b_1$$$ are equal to $$$-1$$$, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, print the length of the longest simple cycle.

NoteIn the first test case, the longest simple cycle is shown below:   We can't increase it with the first chain, since in such case it won't be simple — the vertex $$$2$$$ on the second chain will break simplicity.

def read
  gets.split.map &:to_i
end
gets.to_i.times do
  n = gets.to_i
  c, a, b = read, read, read
  dp = [0] * (n + 1)
  (1...n).each do |i|
    d = (a[i] - b[i]).abs
    if d == 0
      dp[i + 1] = c[i] + 1
    else
      dp[i + 1] = c[i] + 1 + [d, dp[i] - d].max
    end
  end
  puts dp.max
end

def read
  gets.split.map &:to_i
end
gets.to_i.times do
  n = gets.to_i
  c, a, b = read, read, read
  dp = [c[0]] + [0] * (n - 1)
  (1...n).each do |i|
    d = (a[i] - b[i]).abs
    if d == 0
      dp[i] = c[i] + 1
    else
      dp[i] = c[i] + 1 + [d, dp[i - 1] - d].max
    end
  end
  puts dp.max
end


Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter.The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland.Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of m pieces of paper in the garland. Calculate what the maximum total area of the pieces of paper in the garland Vasya can get.

The first line contains a non-empty sequence of n (1 ≤ n ≤ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≤ m ≤ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make.

Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer.

NoteIn the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6.In the second test sample Vasya cannot make a garland at all — he doesn't have a sheet of color z.

#!/usr/bin/ruby
h=Hash.new(0)
gets.chomp.each_char{|c|h[c]+=1}
g=Hash.new(0)
gets.chomp.each_char{|c|g[c]+=1}
r=0
g.each{|k,v|
	if h[k]==0
		p -1
		exit
	end
	r+=[h[k],v].min
}
p r

a,b,ans=Array.new(26,0),Array.new(26,0),0
gets.chomp.split('').each{|i| a[i.ord-97]+=1}
gets.chomp.split('').each{|i| b[i.ord-97]+=1}
26.times do |i|
	if a[i]==0 and a[i]!=b[i]
		puts "-1"
		exit
	end
end
26.times{|i| ans+=[a[i],b[i]].min}
puts ans

h = {}
# ?a.upto(?z) { |c| h[c] = 0 }
s = STDIN.readline.chop
s.each_char do |c|
	if h[c] == nil ;
		h[c] = 0
	end
	h[c] += 1
end

ans = 0
flag = true
s = STDIN.readline.chop
s.each_char do |c|
	if h[c] == nil ;
		flag = false
	elsif h[c] > 0 ;
		h[c] -= 1
		ans += 1
	end
end

print flag ? ans : -1

s1 = gets.chomp.split("")
s2 = gets.chomp.split("")
count1 = Hash.new(0)
s1.each do |a|
	count1[a] += 1
end

count2 = Hash.new(0)
s2.each do |a|
	count2[a] += 1
end

ans = true
s = 0
count2.each do |k,v|
	if count1[k] != 0
		s += [count1[k],v].min
	else
		ans = false
		break
	end
end
puts ans ? s : "-1"

c1, c2 = {}, {}
gets.chomp.each_byte{|c| c1[c]=c1[c].nil? ? 1 : c1[c]+1}
gets.chomp.each_byte{|c| c2[c]=c2[c].nil? ? 1 : c2[c]+1}
sum = 0
c2.each do |k,v|
	if c1[k].nil?
		puts -1
		exit 0
	end
	sum += [v, c1[k]].min
end
puts sum

a = gets.chomp
b = gets.chomp
cnt1 = Hash.new
cnt2 = Hash.new
for x in a.scan /./
  if cnt1[x] == nil
    cnt1[x] = 0
  end
  cnt1[x] += 1
end
for x in b.scan /./
  if cnt2[x] == nil
    cnt2[x] = 0
  end
  cnt2[x] += 1
end
ans = 0
cnt2.each_pair do |k, v|
  if cnt1[k] == nil
    puts -1
    exit
  end
  ans += [v, cnt1[k]].min
end
puts ans

h = {}
?a.upto(?z) { |c| h[c] = 0 }
s = STDIN.readline.chop
s.each_char { |c| h[c] += 1 }

ans = 0
s = STDIN.readline.chop
s.each_char do |c|
	if h[c] > 0
		h[c] -= 1
		ans += 1
	end
end
ans = -1 if ans == 0
print ans

t = gets.to_i
t.times do
	n = gets.to_i
	s = 0
	i = 1
	ans = -1
	(1..n).each do |i|
		s += i
		if s >= n
			ans = i
			s -= i
			break
		end
	end
	row,col = ans,n - s

	sum = row + 1
	numerator = sum - col
	denominator = col

	numerator,denominator = denominator,numerator if row.even?

	puts "TERM #{n} IS #{numerator}/#{denominator}"
end

c1, c2 = {}, {}
gets.chomp.each_byte{|c| c1[c]=c1[c].nil? ? 1 : c1[c]+1}
gets.chomp.each_byte{|c| c2[c]=c2[c].nil? ? 1 : c2[c]+1}
sum = 0
c1.each{|k,v| sum+=[v,c2[k].nil? ? 0 : c2[k]].min}
sum = -1 if sum == 0
puts sum


Karen has just arrived at school, and she has a math test today!  The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition.Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa.The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test.Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row?Since this number can be quite large, output only the non-negative remainder after dividing it by 109 + 7.

The first line of input contains a single integer n (1 ≤ n ≤ 200000), the number of numbers written on the first row. The next line contains n integers. Specifically, the i-th one among these is ai (1 ≤ ai ≤ 109), the i-th number on the first row.

Output a single integer on a line by itself, the number on the final row after performing the process above. Since this number can be quite large, print only the non-negative remainder after dividing it by 109 + 7.

NoteIn the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15.Karen performs the operations as follows:  The non-negative remainder after dividing the final number by 109 + 7 is still 36, so this is the correct output.In the second test case, the numbers written on the first row are 3, 7, 5 and 2.Karen performs the operations as follows:  The non-negative remainder after dividing the final number by 109 + 7 is 109 + 6, so this is the correct output.

require 'openssl'
N = gets.chomp.to_i
A = gets.split.map(&:to_i)
M = 1000000007
sign = 1
until (N - 1) % 4 == 0
  na = Array.new(N - 1, 0)
  (N - 1).times { |i| na[i] = A[i] + sign * A[i + 1]; sign *= -1 }
  N, A, na = N - 1, na, A
end
f = (1..N / 2 + 1).each_with_object([1]) { |i, o| o << o[-1] * i % M }
vf = (-(N / 2)..0).each_with_object([f[N / 2 + 1].to_bn.mod_exp(M - 2, M)]) { |i, o| o << o[-1] * (-i + 1) % M }.reverse
ans = 0
(0...N).step(2).each { |i| ans = (ans + A[i] * f[N / 2] * vf[i / 2] * vf[N / 2 - i / 2]) % M }
ans += M if ans < 0
p ans