You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that .

The first line contains integer n (1 ≤ n ≤ 5·105), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]| ≤  109) — the elements of array a.

Print a single integer — the number of ways to split the array into three parts with the same sum.

#
# E - Number of Ways
#

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

s = a.reduce(:+)

if (s % 3 != 0)
  puts 0
else

  count = (1..10000000).map { |i| 0 }

  s /= 3
  sub_sum = 0

  (n - 1).downto(0) do |i|
    sub_sum += a[i]
    count[i] = 1 if sub_sum == s
  end

  (n - 2).downto(0) do |i|
    count[i] += count[i + 1]
  end

  answer = 0
  sub_sum = 0
  i = 0

  loop do
    break if i + 2 >= n

    sub_sum += a[i]
    answer += count[i + 2] if sub_sum == s
    i += 1
  end

  puts answer
end

#!/usr/bin/ruby

n = STDIN.readline.to_i
arr = STDIN.readline.split.map {|s| s.to_i }

total = arr.reduce(:+)
if total%3 != 0
	puts 0
	exit
end
target = total / 3

sums = [0]
sum = 0
arr.each {|x| sums.push(sum += x) }

low, result = 0, 0
(1..n-2).each do |i|
	low += 1 if sums[i] == target
	result += low if total - sums[i+1] == target
end
puts result

n = gets.chomp.to_i
a = gets.chomp.split.map(&:to_i)
sum = 0
a.each { |x| sum += x }
if sum % 3 != 0
  puts 0
  exit
end
sum /= 3
ans, cnt, psum = 0, 0, 0
for x in 0...n-1 do
  psum += a[x]
  ans += cnt if psum == 2 * sum
  cnt += 1   if psum == sum
end
puts ans

n=gets.to_i
x=gets.split.map{|e| e.to_i}
s1=x.inject(0){|sum1,e|
	sum1+e
}
if s1%3!=0 || n<3 then
	puts 0
else
	s3=s1/3
	sum=0
	arr=[]
	i=0
	x.each{|e|
		sum=sum+e
		if s3==sum then
			arr<<i
		end
		i=i+1
	}
	arr2=[]
	x.reverse!
	i=x.size-1
	sum=0
	x.each{|e|
		sum=sum+e
		if s3==sum then
			arr2<<i
		end
		i=i-1
	}
	arr2.reverse!
	ans=0
	while !arr.empty? && !arr2.empty?
		if arr2[0]<=arr[0]+1 then
			arr2.shift
		else
			ans+=arr2.size
			arr.shift
		end
	end
	puts ans
end

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
acc = 0
ar = []
gets.split.each { |i|
    i = i.to_i
    acc += i
    ar << acc
}

# p ar

# ar.last 는 반드시 3의 배수이다.
# 각 부분의 합을 p, q, r 이라고 할 때, p + q + r = 3n
# p = 3a, q = 3b, r = 3c 라고 할 때
# p + q + r = 3*(a + b+ c) = 3n 이고, 3으로 양변을 나누면
# a + b + c = n 이때 a, b, c, n 은 모두 정수이다.
# 만약 p q r 중 하나가 3의 배수가 아니라면 합이 정수가 되지 못한다.
# 그리고 균등하게 분할해야하므로 p = q = r, 3a = 3b = 3c, a = b = c이다.

if ar.last % 3 != 0
    puts "0"
else
    partsum = ar.last/3
    dpartsum = partsum * 2
    partsum_counter = 0

    combinations = 0
    ar[0...(n-1)].each { |i|
        if dpartsum == i
            combinations += partsum_counter
        end

        if partsum == i
            partsum_counter += 1
        end
    }

    puts combinations
end

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
# sum = [0]
# arr.each do |a|
# 	sum << a + sum[-1]
# end
# sum.shift
# count = 0
# (0...(n-2)).each do |i|
# 	((i + 1)...(n-1)).each do |j|
# 		if (sum[i] == (sum[j] - sum[i])) && (sum[i] == (sum[-1] - sum[j] ))
# 			# puts "#{i} #{j}"
# 			count += 1
# 		end
# 	end
# end
# # puts "#{sum}"
# puts "#{count}"
sum = arr.inject(0,:+)
if sum % 3 != 0
	puts 0
else
	sum /= 3
	s = 0
	count = 0
	current_ways = 0
	arr[0..(n-2)].each do |a|
		s += a

		count += current_ways if s == 2 * sum
		current_ways += 1 if s == sum
	end
	puts count
end

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

sum, answer, count, temp_sum = 0, 0, 0, 0

arr.each { |e| sum = sum + e }

if sum % 3 == 0
  sum = sum / 3
  for i in 0...(elements - 1)
    temp_sum = temp_sum + arr[i]
    answer = answer + count if temp_sum == 2 * sum
    count = count + 1 if temp_sum == sum
  end

end

puts answer

n = gets.to_i
a = gets.split.map(&:to_i)
a_sum = [a[0]]
(n - 1).times.each{|i| a_sum[i + 1] = a_sum[i] + a[i + 1]}
goal = a_sum[n - 1] == 0 ? 0 : a_sum[n - 1] / 3
an = [nil, 0, 0]
ind = 1
ans = 0
n.times do |i|
  if ind == 1 && a_sum[i] == goal && a_sum[i] == goal * 2
    an[1] += 1
    an[2] += 1
  elsif ind == 1 && a_sum[i] == goal
    an[1] += 1
  elsif ind == 2 && a_sum[i] == goal
    ans += an[1] * an[2]
    ind = 1
    an[1] = 1
  elsif a_sum[i] == goal * 2
    ind = 2
    an[2] += 1
  end
  if i == n - 1 && ind == 2
    ans += an[1] * an[2]
  end
end
if ans == 0 && (an[1] < 1 || an[2] < 1) || (goal == 0 && an[1] < 3) || goal * 3 != a_sum[n - 1]
  puts 0
elsif goal == 0
  puts (an[1] - 1) * (an[1] - 2) / 2
else
  puts ans
end

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

r_sum = a.reverse.each_with_object([0]) { |i, a| a << a.last + i }.reverse

l_sum = Hash.new { 0 }

sum = 0
result = 0

a.each_with_index do |a, i|
  sum = sum + a
  l_sum[sum] += 1

  next if i.zero? || i == (n - 1)

  result += l_sum[sum/2] - (sum.zero? ? 1 : 0) if r_sum[i+1]*2 == sum && sum.even?
end

puts result

#
# E - Number of Ways
#

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

s = a.reduce(:+)

if (s % 3 != 0)
  puts 0
else

  s /= 3
  count = 0
  ans = 0
  sub_sum = 0

  for i in (0..n-1)
    sub_sum += a[i]

    count += 1 if sub_sum == s
    ans += count if sub_sum == 2 * s
  end

  puts ans
end

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
acc = 0
ar = []
gets.split.each { |i|
    i = i.to_i
    acc += i
    ar << acc
}

# p ar

# ar.last 는 반드시 3의 배수이다.
# 각 부분의 합을 p, q, r 이라고 할 때, p + q + r = 3n
# p = 3a, q = 3b, r = 3c 라고 할 때
# p + q + r = 3*(a + b+ c) = 3n 이고, 3으로 양변을 나누면
# a + b + c = n 이때 a, b, c, n 은 모두 정수이다.
# 만약 p q r 중 하나가 3의 배수가 아니라면 합이 정수가 되지 못한다.
# 그리고 균등하게 분할해야하므로 p = q = r, 3a = 3b = 3c, a = b = c이다.

if ar.last % 3 != 0
    puts "0"
else
    partsum = ar.last/3
    dpartsum = partsum * 2
    partsum_counter = 0

    combinations = 0
    ar[1...(n-1)].each { |i|
        if partsum == i
            partsum_counter += 1
        end

        if dpartsum == i &&
            combinations += partsum_counter
        end
    }

    puts combinations
end

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
acc = 0
ar = []
gets.split.each { |i|
    i = i.to_i
    acc += i
    ar << acc
}

# p ar

# ar.last 는 반드시 3의 배수이다.
# 각 부분의 합을 p, q, r 이라고 할 때, p + q + r = 3n
# p = 3a, q = 3b, r = 3c 라고 할 때
# p + q + r = 3*(a + b+ c) = 3n 이고, 3으로 양변을 나누면
# a + b + c = n 이때 a, b, c, n 은 모두 정수이다.
# 만약 p q r 중 하나가 3의 배수가 아니라면 합이 정수가 되지 못한다.
# 그리고 균등하게 분할해야하므로 p = q = r, 3a = 3b = 3c, a = b = c이다.

if ar.last % 3 != 0
    puts "0"
else
    partsum = ar.last/3
    dpartsum = partsum * 2
    partsum_counter = 0

    combinations = 0
    ar[1...n].each { |i|
        if dpartsum == i
            combinations += partsum_counter
        end

        if partsum == i
            partsum_counter += 1
        end
    }

    puts combinations
end

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
acc = 0
ar = []
arr = gets.split.each { |i|
    i = i.to_i
    acc += i
    ar << acc
}

# ar.last 는 반드시 3의 배수이다.
# 각 부분의 합을 p, q, r 이라고 할 때, p + q + r = 3n
# p = 3a, q = 3b, r = 3c 라고 할 때
# p + q + r = 3*(a + b+ c) = 3n 이고, 3으로 양변을 나누면
# a + b + c = n 이때 a, b, c, n 은 모두 정수이다.
# 만약 p q r 중 하나가 3의 배수가 아니라면 합이 정수가 되지 못한다.
# 그리고 균등하게 분할해야하므로 p = q = r, 3a = 3b = 3c, a = b = c이다.

if ar.last % 3 != 0
    puts "0"
else
    partsum = ar.last/3
    dpartsum = partsum * 2
    partsum_counter = 0

    combinations = 0
    ar.each { |i|
        if dpartsum == i
            combinations += partsum_counter
        end

        if partsum == i
            partsum_counter += 1
        end
    }

    puts combinations
end

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

sum, answer, count, psum = 0, 0, 0, 0

arr.each { |e| sum = sum + e }

unless sum % 3 != 0
  sum = sum / 3

  for i in 0...elements do
    psum = psum + arr[i]
    answer = answer + count if psum == 2 * sum
    count = count + 1 if psum == sum
  end

end

puts answer

n = gets.to_i
a = gets.split.map(&:to_i)
a_sum = [a[0]]
(n - 1).times.each{|i| a_sum[i + 1] = a_sum[i] + a[i + 1]}
goal = a_sum[n - 1] == 0 ? 0 : a_sum[n - 1] / 3
if goal * 3 != a_sum[n - 1]
  puts 0
else
  a1 = a_sum.count(goal)
  a2 = a_sum.count(goal * 2)
  puts a1 == a2 ? (a1 - 1) * (a1 - 2) / 2 : a1 * a2
end

n = gets.to_i
a = gets.split.map(&:to_i)
a_sum = [a[0]]
(n - 1).times.each{|i| a_sum[i + 1] = a_sum[i] + a[i + 1]}
goal = a_sum[n - 1] == 0 ? 0 : a_sum[n - 1] / 3
a1 = a_sum.count(goal)
a2 = a_sum.count(goal * 2)
if (a1 < 1 || a2 < 1) || goal * 3 != a_sum[n - 1]
  puts 0
else
  puts goal == goal * 2 ? (a1 - 1) * (a1 - 2) / 2 : a1 * a2
end

n = gets.to_i
a = gets.split.map(&:to_i)
a_sum = [a[0]]
(n - 1).times.each{|i| a_sum[i + 1] = a_sum[i] + a[i + 1]}
goal = a_sum[n - 1] == 0 ? 0 : a_sum[n - 1] / 3
an = [nil, 0, 0]
ind = 1
n.times do |i|
  if ind == 1 && a_sum[i] == goal && a_sum[i] == goal * 2
    an[1] += 1
    an[2] += 1
  elsif ind == 1 && a_sum[i] == goal
    an[1] += 1
  elsif a_sum[i] == goal * 2
    ind = 2
    an[2] += 1
  end
end
if (an[1] < 1 || an[2] < 1) || (goal == 0 && an[1] < 3) || goal * 3 != a_sum[n - 1]
  puts 0
elsif goal == 0
  puts (an[1] - 1) * (an[1] - 2) / 2
else
  puts an[1] * an[2]
end

n = gets.to_i
a = gets.split.map(&:to_i)
a_sum = [a[0]]
(n - 1).times.each{|i| a_sum[i + 1] = a_sum[i] + a[i + 1]}
goal = a_sum[n - 1] == 0 ? 0 : a_sum[n - 1] / 3
a1 = a_sum.count(goal)
a2 = a_sum.count(goal * 2)
if (a1 < 1 || a2 < 1) || goal * 3 != a_sum[n - 1]
  puts 0
else
  puts a1 == a2 ? (a1 - 1) * (a1 - 2) / 2 : a1 * a2
end

n = gets.to_i
a = gets.split.map(&:to_i)
a_sum = [a[0]]
(n - 1).times.each{|i| a_sum[i + 1] = a_sum[i] + a[i + 1]}
goal = a_sum[n - 1] == 0 ? 0 : a_sum[n - 1] / 3
an = [nil, 0, 0]
ind = 1
ans = 0
n.times do |i|
  if ind == 1 && a_sum[i] == goal && a_sum[i] == goal * 2
    an[1] += 1
    an[2] += 1
  elsif ind == 1 && a_sum[i] == goal
    an[1] += 1
  elsif ind == 2 && a_sum[i] == goal
    ans += an[1] * an[2]
    ind = 1
    an[1] = 1
  elsif a_sum[i] == goal * 2
    ind = 2
    an[2] += 1
  end
  if i == n - 1 && ind == 2
    ans += an[1] * an[2]
  end
end
if ans > 0
  puts ans
elsif (an[1] < 1 || an[2] < 1) || (goal == 0 && an[1] < 3) || goal * 3 != a_sum[n - 1]
  puts 0
elsif goal == 0
  puts (an[1] - 1) * (an[1] - 2) / 2
else
  puts ans
end

n = gets.to_i
a = gets.split.map(&:to_i)
a_sum = [a[0]]
(n - 1).times.each{|i| a_sum[i + 1] = a_sum[i] + a[i + 1]}
goal = a_sum[n - 1] == 0 ? 0 : a_sum[n - 1] / 3
an = [nil, 0, 0]
ind = 1
ans = 0
n.times do |i|
  if ind == 1 && a_sum[i] == goal && a_sum[i] == goal * 2
    an[1] += 1
    an[2] += 1
  elsif ind == 1 && a_sum[i] == goal
    an[1] += 1
  elsif ind == 2 && a_sum[i] == goal
    p an
    ans += an[1] * an[2]
    ind = 1
    an[1] = 1
  elsif a_sum[i] == goal * 2
    ind = 2
    an[2] += 1
  end
  if i == n - 1 && ind == 2
    ans += an[1] * an[2]
  end
end
if ans > 0
  puts ans
elsif (an[1] < 1 || an[2] < 1) || (goal == 0 && an[1] < 3) || goal * 3 != a_sum[n - 1]
  puts 0
elsif goal == 0
  puts (an[1] - 1) * (an[1] - 2) / 2
else
  puts ans
end


You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci.Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu :  cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}.Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color.

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge.  It is guaranteed that the given graph has no self-loops or multiple edges.

Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color.

require 'set'
n,m=gets.split.map(&:to_i)
id = [0] + gets.split.map(&:to_i);
inn = [-1]*(1e5.to_i+1)
s = Set[]
m.times do |u|
	a,b = gets.split.map(&:to_i)
	x,y = id[a],id[b]
	x,y=y,x if x>y
	if x!=y and not s.include? [x,y] then
		s << [x,y]
		inn[x]=0 if inn[x]==-1
		inn[y]=0 if inn[y]==-1
		inn[x]+=1
		inn[y]+=1
	end
end

ans,j=-1,0
inn.each_with_index do |v,u|
	if ans<v then
		ans=v
		j=u
	end
end
if j!=0 then
	puts j
else
	j=2147483647
	id.each_with_index do |u,i|
		next if i==0
		j=u if u<j
	end
	puts j
end

require 'set'
n,m=gets.split.map(&:to_i)
id = [0] + gets.split.map(&:to_i);
inn = [-1]*(1e5.to_i+1)
s = Set[]
m.times do |u|
	a,b = gets.split.map(&:to_i)
	x,y = id[a],id[b]
	x,y=y,x if x>y
	if x!=y and not s.include? [x,y] then
		inn[x]=0 if inn[x]==-1
		inn[y]=0 if inn[y]==-1
		inn[x]+=1
		inn[y]+=1
	end
end

ans,j=-1,0
inn.each_with_index do |v,u|
	if ans<v then
		ans=v
		j=u
	end
end
if j!=0 then
	puts j
else
	j=2147483647
	id.each do |u|
		j=u if u<j
	end
	puts j
end

require 'set'
n,m=gets.split.map(&:to_i)
id = [0] + gets.split.map(&:to_i);
inn = [-1]*(1e5.to_i+1)
s = Set[]
m.times do |u|
	a,b = gets.split.map(&:to_i)
	x,y = id[a],id[b]
	x,y=y,x if x>y
	if x!=y and not s.include? [x,y] then
		inn[x]=0 if inn[x]==-1
		inn[y]=0 if inn[y]==-1
		inn[x]+=1
		inn[y]+=1
	end
end

ans,j=-1,0
inn.each_with_index do |v,u|
	if ans<v then
		ans=v
		j=u
	end
end
if j!=0 then
	puts j
else
	j=2147483647
	id.each_with_index do |u,i|
		next if i==0
		j=u if u<j
	end
	puts j
end


After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:  There is at least one digit in the string,  There is at least one lowercase (small) letter of the Latin alphabet in the string,  There is at least one of three listed symbols in the string: '#', '*', '&'.   Considering that these are programming classes it is not easy to write the password.For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.

The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols.  Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password.

Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.

NoteIn the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.   In the second test one of possible algorithms will be:   to move the pointer of the second symbol once to the right.  to move the pointer of the third symbol twice to the right.

TEST_MODE = ARGV[0] == 't'

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

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

# actual codes here
BIG_INT = 1000000

def find_in(str)
  return 0 if yield(str[0])
  for i in 1..str.size/2
    return i if yield(str[i]) or yield(str[str.size-i])
  end
  return BIG_INT
end

def analyze(str)
  [
    find_in(str) { |c| 'a' <= c && c <= 'z' },
    find_in(str) { |c| '0' <= c && c <= '9' },
    find_in(str) { |c| '#*&'.index(c) != nil }
  ]
end

def findmin(arr)
  min = BIG_INT
  (0..arr.size-1).each { |i|
    sum = arr[i][0]
    (0..arr.size-1).each { |j|
      next if i==j
      sum = arr[i][0] + arr[j][1]
      next if sum >= min
      (0..arr.size-1).each { |k|
        next if i==k || j==k
        sum = arr[i][0] + arr[j][1] + arr[k][2]
        next if sum >= min
        min = sum if sum < min
      }
    }
  }
  return min
end

def solve(input, output)
  n, m = parse_int_array(input[0])
  arr = input[1..-1].collect {|str|
    analyze(str)
  }
  p(arr)
  output << findmin(arr).to_s
end

tests do
  # test cases
  t(["3 4",
"1**2",
"a3*0",
"c4**"], "1")
  t(["5 5",
"#*&#*",
"*a1c&",
"&q2w*",
"#a3c#",
"*&#*&"], "3")
end

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

n, m = gets.split.map(&:to_i)
a = n.times.map{gets.chomp}

aa = Array.new(3){Array.new(n, 0)}
[/[[:alpha:]]/, /\d/, /\W/].each_with_index do |reg, i|
  n.times do |j|
    t1 = a[j] =~ reg
    t2 = (a[j].reverse =~ reg) + 1 if a[j].reverse =~ reg
    aa[i][j] = [t1, t2].min || 1000
  end
end

mi = 1000
n.times do |i|
  n.times do |j|
    next if j == i
    n.times do |k|
      next if k == i || k == j
      mi = [aa[0][i] + aa[1][j] + aa[2][k], mi].min
    end
  end
end
p mi


Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.

The first line contains integer n (1 ≤ n ≤ 105) — the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105.  The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.

In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.

7
i
am
not
main
in
the
family
<3i<>3am<3the<3<main<3in<3the<3><3family<3

NotePlease note that Dima got a good old kick in the pants for the second sample from the statement.

n=gets.to_i
w=['']
n.times{w<<gets.chomp}
w<<''
m=gets.chomp
w=w.join '<3'
j=0
m.size.times{|i|j+=1 if j<w.size && m[i]==w[j]}
puts j==w.size ? 'yes':'no'

n = gets.to_i
s = "<3"
for i in 0...n
  s << gets.strip + "<3"

end

t = gets.strip

a = s.length
b = t.length

j = 0
for i in 0...a
  until t[j] == s[i]
    j += 1
    if j >= b
      print "no"
      exit
    end
  end
  j += 1
end

print "yes"

cnt = gets.to_i
cstr = "<3"
cnt.times {	cstr <<  gets.chomp << "<3" }
str = gets.chomp
idx = 0
cstr.each_char {|c|
	res = str.index(c, idx)
	if res == nil
		puts "no"
		exit
	end
	idx = res + 1
}
puts "yes"

n = gets.to_i
pattern = "<3"
n.times do |i|
  pattern = pattern << gets.chomp
  pattern = pattern << "<3"
end
ans = gets
len = pattern.size()
index = 0
alen = ans.size()
alen.times do |i|
  next if (pattern[index]!=ans[i])
  break if index == len or alen - i < len - index
  index += 1
end
if index == len then
  puts "yes"
else
  puts "no"
end

n = Integer(gets.chomp)
original_text = Array.new(n+1)
for i in 0...n
    original_text[i] = "<3" + gets.chomp
end
original_text[n] = "<3"
text_received = gets.chomp
pointer = 0
find_all = true
for i in 0...n+1
    for k in 0...original_text[i].length
        a = original_text[i][k]
        find = false
        for j in pointer...text_received.length
            if text_received[j] == a
                pointer = j + 1
                find = true
                break
            end
        end
    end
    if !find
        find_all = false
        break
    end
end

if find_all
    puts "yes"
else
    puts "no"
end

d = ('<3' + (gets.to_i.times.map{gets.split}).join('<3') + '<3').chars.to_a
str = gets.strip.chars.to_a
index = 0; get = 0;
(d.length).times do |i|
    get = i
    while(d[i] != str[index])
        if index == str.length-1
            break
        end
        index+=1
    end

    if index == str.length-1
        break
    end
    if d[i] == str[index]
        index+=1
    end
end
(get == d.length-1)? (puts "yes") : (puts "no")

w = []
for _ in 1..Integer(gets.chomp)
  w << gets.chomp
end
s = "<3#{w * '<3'}<3"
t = gets.chomp
p = 0
n = s.size
for i in 0...t.size
  break if p == n
  p += 1 if t[i] == s[p]
end
puts(p == n ? 'yes' : 'no')

n = gets.chomp.to_i
msg = ["<3"]

n.times do
  word = gets.chomp
  msg.push(word)
  msg.push("<3")
end

enc = gets.chomp

msg = msg.join("")

curr = 0
enc.each_char do |c|
  if (curr < msg.length && c == msg[curr])
    curr += 1
  end
end

if (curr == msg.length)
  puts "yes"
else
  puts "no"
end

cnt = gets.to_i
cstr = "<3"
cnt.times {	cstr <<  gets.chomp << "<3" }
str = gets.chomp
idx = 0
cstr.each_char {|c|
	res = str.index(c, idx)
	if res == nil
		puts "no"
		puts "idx=#{idx}, char=#{c}"
		exit
	end
	idx = res + 1
}
puts "yes"

n = gets.to_i
s = []
n.times do
  s << gets.chop
end
ans = gets.chop
pattern = "<3"
n.times do |i|
  pattern = pattern + s[i]
  pattern = pattern + "<3"
end
len = pattern.size()
cnt = 0
index = 0
if ans.size() - len != 1 then
  puts "no"
  exit
end
len.times do |i|
  while pattern[i] != ans[index] do
    index += 1
    cnt += 1
    break if index >= ans.size()
  end
  index += 1
  break if index >= ans.size()
end
if cnt == 1 then
  puts "yes"
else
  puts "no"
end

n = gets.to_i
s = []
n.times do
  s << gets.chop
end
ans = gets.chop
pattern = "<3"
n.times do |i|
  pattern = pattern + s[i]
  pattern = pattern + "<3"
end
len = pattern.size()
insert = false
index = 0
if ans.size() - len != 1 then
  puts "no"
  exit
end
len.times do |i|
  if ans[index] != pattern[i] then
    puts "no" if insert
    insert = true
    index += 1
  end
  index += 1
end
puts "yes"

n = gets.to_i
s = []
n.times do
  s << gets.chop
end
ans = gets.chop
pattern = "<3"
n.times do |i|
  pattern = pattern + s[i]
  pattern = pattern + "<3"
end
len = pattern.size()
cnt = 0
index = 0
len.times do |i|
  while pattern[i] != ans[index] do
    index += 1
    cnt += 1
    break if index >= ans.size()
  end
  index += 1
  break if index >= ans.size()
end
if cnt == 1 then
  puts "yes"
else
  puts "no"
end

n = Integer(gets.chomp)
original_text = ""
for i in 0...n
    original_text += gets.chomp
end
text_received = gets.chomp
pointer = 0
count = ""
for i in 0...original_text.length
    a = original_text[i]
    for j in pointer...text_received.length
        if text_received[j] == a
            pointer = j + 1
            count += a
            break
        end
    end
end

if count == original_text && text_received.length > original_text.length + 2 * n
    puts "yes"
else
    puts "no"
end

n = Integer(gets.chomp)
original_text = ""
for i in 0...n
    original_text += gets.chomp
end
text_received = gets.chomp
pointer = 0
count = ""
for i in 0...original_text.length
    a = original_text[i]
    for j in pointer...text_received.length
        if text_received[j] == a
            pointer = j + 1
            count += a
            break
        end
    end
end

if count == original_text
    puts "yes"
else
    puts "no"
end

d = ('<3' + (gets.to_i.times.map{gets.split}).join('<3') + '<3').chars.to_a
str = gets.strip.chars.to_a
index = 0; get = 0;
(d.length).times do |i|
    gets = i
    while(d[i] != str[index])
        if index == str.length-1
            break
        end
        index+=1
    end

    if index == str.length-1
        break
    end
end
(get == d.length-1)? (puts "yes") : (puts "no")

d = ('<3' + (gets.to_i.times.map{gets.split}).join('<3') + '<3').chars.to_a
str = gets.strip.chars.to_a
index = 0; get = 0;
(d.length).times do |i|
    get = i
    while(d[i] != str[index])
        if index == str.length-1
            break
        end
        index+=1
    end

    if index == str.length-1
        break
    end
end
(get == d.length-1)? (puts "yes") : (puts "no")

d = gets.to_i.times.map{gets.split}
str = gets.strip.chars.to_a
ans = ""
str.each{|x| (ans+=x) if (x>='a' && x<='z')}
(ans == d.join)? (puts "yes") : (puts "no")

d = ('<3' + (gets.to_i.times.map{gets.split}).join('<3') + '<3').chars.to_a
str = gets.strip.chars.to_a
index = 0; get = 0;
(d.length).times do |i|
	while(d[i] != str[index])
		if index == str.length-1
			break
		end
		index+=1
	end

	if index == str.length-1
		get = i
		break
	end
end
(get == d.length-1)? (puts "yes") : (puts "no")

n=gets.to_i
w=[]
n.times{w<<gets.chomp}
m=gets.chomp
w=w.join '<3'
j=0
m.size.times{|i|j+=1 if j<w.size && m[i]==w[j]}
puts j==w.size ? 'yes':'no'

n=gets.to_i
w=[]
n.times{w<<gets.chomp}
m=gets.chomp
w=w.join '<3'
j=0
m.size.times{|i|j+=1 if m[i]==w[j]}
puts j==w.size ? 'yes':'no'

n=gets.to_i
w=[]
n.times{w<<gets.chomp}
m=gets.chomp
w=w.join '<3'
j=0
m.size.times{|i|j+=1 if j<w.size && m[i]==w[j]}
puts j>=w.size ? 'yes':'no'

n=gets.to_i
w=[]
n.times{w<<gets.chomp}
w<<''
m=gets.chomp
w=w.join '<3'
j=0
m.size.times{|i|j+=1 if j<w.size && m[i]==w[j]}
puts j==w.size ? 'yes':'no'


Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies.In order to avoid this representatives of both companies decided to make an agreement on the sets the companies should present. The sets should be chosen in the way that maximizes the total income of the companies.All elements are enumerated with integers. The ChemForces company has discovered $$$n$$$ distinct chemical elements with indices $$$a_1, a_2, \ldots, a_n$$$, and will get an income of $$$x_i$$$ Berland rubles if the $$$i$$$-th element from this list is in the set of this company.The TopChemist company discovered $$$m$$$ distinct chemical elements with indices $$$b_1, b_2, \ldots, b_m$$$, and it will get an income of $$$y_j$$$ Berland rubles for including the $$$j$$$-th element from this list to its set.In other words, the first company can present any subset of elements from $$$\{a_1, a_2, \ldots, a_n\}$$$ (possibly empty subset), the second company can present any subset of elements from $$$\{b_1, b_2, \ldots, b_m\}$$$ (possibly empty subset). There shouldn't be equal elements in the subsets.Help the representatives select the sets in such a way that no element is presented in both sets and the total income is the maximum possible.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$)  — the number of elements discovered by ChemForces. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$x_i$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$1 \leq x_i \leq 10^9$$$)  — the index of the $$$i$$$-th element and the income of its usage on the exhibition. It is guaranteed that all $$$a_i$$$ are distinct. The next line contains a single integer $$$m$$$ ($$$1 \leq m \leq 10^5$$$)  — the number of chemicals invented by TopChemist. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$b_j$$$ and $$$y_j$$$, ($$$1 \leq b_j \leq 10^9$$$, $$$1 \leq y_j \leq 10^9$$$)  — the index of the $$$j$$$-th element and the income of its usage on the exhibition. It is guaranteed that all $$$b_j$$$ are distinct.

Print the maximum total income you can obtain by choosing the sets for both companies in such a way that no element is presented in both sets.

NoteIn the first example ChemForces can choose the set ($$$3, 7$$$), while TopChemist can choose ($$$1, 2, 4$$$). This way the total income is $$$(10 + 2) + (4 + 4 + 4) = 24$$$.In the second example ChemForces can choose the only element $$$10^9$$$, while TopChemist can choose ($$$14, 92, 35$$$). This way the total income is $$$(239) + (15 + 65 + 89) = 408$$$.

l1 = gets.to_i
a = {}
l1.times{
  k,v =  gets.chomp.split(" ").map{|x| x.to_i}
  a[k] = v
}

b = {}
l2 = gets.to_i
l2.times{
  k,v =  gets.chomp.split(" ").map{|x| x.to_i}
  b[k] = v
}

a.each_key{|k|
  if b[k]
    if b[k] > a[k]
      a.delete(k)
    else
      b.delete(k)
    end
  end
}

puts a.values.inject(0){|sum,x| sum+x} + b.values.inject(0){|sum,x| sum+x}

# http://codeforces.com/problemset/problem/981/B
a, b = [], []
n = gets.chomp.to_i
n.times do
  a << gets.chomp.split.map(&:to_i)
end
a.sort!

m = gets.chomp.to_i
m.times do
  b << gets.chomp.split.map(&:to_i)
end
b.sort!

sum = 0
for i in 0..(n - 1)
  sum += a[i][1]
end

for i in 0..(m - 1)
  sum += b[i][1]
end

repeated_index = []
i, j = 0, 0
while i < n && j < m
  if a[i][0] == b[j][0]
    repeated_index << [i, j]
    i += 1
    j += 1
  elsif a[i][0] < b[j][0]
    i += 1
  else
    j += 1
  end
end

if repeated_index.empty?
  puts sum
else
  for i in 0..(repeated_index.length - 1)
    a_repeated_index = repeated_index[i][0]
    b_repeated_index = repeated_index[i][1]

    sum -= a[a_repeated_index][1] < b[b_repeated_index][1] ? a[a_repeated_index][1] : b[b_repeated_index][1]
  end

  puts sum
end


Don't you tell me what you think that I can beIf you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct hero in the beginning of the game.There are $$$2$$$ teams each having $$$n$$$ players and $$$2n$$$ heroes to distribute between the teams. The teams take turns picking heroes: at first, the first team chooses a hero in its team, after that the second team chooses a hero and so on. Note that after a hero is chosen it becomes unavailable to both teams.The friends estimate the power of the $$$i$$$-th of the heroes as $$$p_i$$$. Each team wants to maximize the total power of its heroes. However, there is one exception: there are $$$m$$$ pairs of heroes that are especially strong against each other, so when any team chooses a hero from such a pair, the other team must choose the other one on its turn. Each hero is in at most one such pair.This is an interactive problem. You are to write a program that will optimally choose the heroes for one team, while the jury's program will play for the other team. Note that the jury's program may behave inefficiently, in this case you have to take the opportunity and still maximize the total power of your team. Formally, if you ever have chance to reach the total power of $$$q$$$ or greater regardless of jury's program choices, you must get $$$q$$$ or greater to pass a test.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^3$$$, $$$0 \le m \le n$$$) — the number of players in one team and the number of special pairs of heroes. The second line contains $$$2n$$$ integers $$$p_1, p_2, \ldots, p_{2n}$$$ ($$$1 \le p_i \le 10^3$$$) — the powers of the heroes. Each of the next $$$m$$$ lines contains two integer $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 2n$$$, $$$a \ne b$$$) — a pair of heroes that are especially strong against each other. It is guaranteed that each hero appears at most once in this list. The next line contains a single integer $$$t$$$ ($$$1 \le t \le 2$$$) — the team you are to play for. If $$$t = 1$$$, the first turn is yours, otherwise you have the second turn. Hacks In order to hack, use the format described above with one additional line. In this line output $$$2n$$$ distinct integers from $$$1$$$ to $$$2n$$$ — the priority order for the jury's team. The jury's team will on each turn select the first possible hero from this list. Here possible means that it is not yet taken and does not contradict the rules about special pair of heroes.

NoteIn the first example the first turn is yours. In example, you choose $$$6$$$, the other team is forced to reply with $$$2$$$. You choose $$$5$$$, the other team chooses $$$4$$$. Finally, you choose $$$3$$$ and the other team choose $$$1$$$.In the second example you have the second turn. The other team chooses $$$6$$$, you choose $$$5$$$, forcing the other team to choose $$$1$$$. Now you choose $$$4$$$, the other team chooses $$$3$$$ and you choose $$$2$$$.

require 'set'
nm = gets.chomp.split(" ").map(&:to_i)
powers = gets.chomp.split(" ").map(&:to_i)
pairs = []
n = nm[0]
m = nm[1]

m.times do
  pairs.push gets.chomp.split(" ").map(&:to_i)
end

nopairs = []

t = gets.to_i
forcedmove = false
selected = Set.new
justplayedpair = false
toplayforced = -1

(2*n).times do
#  puts "#{t} #{forcedmove} #{toplayforced} #{justplayedpair}"
  if t==2
    opponentmove = gets.to_i
    if opponentmove==-1
#      powers[nil] =0
      exit
    end
    selected.add(opponentmove)
    powers[opponentmove-1] = 0
    forcedmove = false
    if not justplayedpair
      toplayforced = -1

      pairs.each do |pair|
        if pair.include?(opponentmove)
          forcedmove = true
          toplayforced = (pair - [opponentmove])[0]
          break
        end
      end
    end
    t=1

  else
    #your move
    if forcedmove
      toplay = toplayforced
      justplayedpair = false
    else
      #your move and it's free
      played = false
      pairs.each do |pair|
        if not selected.include?(pair[0])
          #play this pair
          toplay = pair.max
          score1 = powers[pair[0]-1]
          score2 = powers[pair[1]-1]

          if score1>score2
            toplay = pair[0]
          else
            toplay = pair[1]
          end

          played = true
          justplayedpair = true
        end
      end

      if not played
        toplay = powers.index(powers.max)+1
        justplayedpair = false
        #put the largest unselected no-pair dude
      end
    end

#    puts forcedmove
#    puts played
    puts toplay
    STDOUT.flush
    powers[toplay-1] = 0
    selected.add(toplay)
    t = 2
  end
end

require 'set'
nm = gets.chomp.split(" ").map(&:to_i)
powers = gets.chomp.split(" ").map(&:to_i)
pairs = []
n = nm[0]
m = nm[1]

m.times do
  pairs.push gets.chomp.split(" ").map(&:to_i)
end

nopairs = []

t = gets.to_i
forcedmove = false
selected = Set.new
justplayedpair = false
toplayforced = -1

(2*n).times do
#  puts "#{t} #{forcedmove} #{toplayforced} #{justplayedpair}"
  if t==2
    opponentmove = gets.to_i
    if opponentmove==-1
      exit
    end
    selected.add(opponentmove)
    powers[opponentmove-1] = 0
    forcedmove = false
    if not justplayedpair
      toplayforced = -1

      pairs.each do |pair|
        if pair.include?(opponentmove)
          forcedmove = true
          toplayforced = (pair - [opponentmove])[0]
          break
        end
      end
    end
    t=1

  else
    #your move
    if forcedmove
      toplay = toplayforced
      justplayedpair = false
    else
      #your move and it's free
      played = false
      pairs.each do |pair|
        if not selected.include?(pair[0])
          #play this pair
          toplay = pair.max
          played = true
          justplayedpair = true
        end
      end

      if not played
        toplay = powers.index(powers.max)+1
        justplayedpair = false
        #put the largest unselected no-pair dude
      end
    end

#    puts forcedmove
#    puts played
    puts toplay
    STDOUT.flush
    powers[toplay-1] = 0
    selected.add(toplay)
    t = 2
  end
end

require 'set'
nm = gets.chomp.split(" ").map(&:to_i)
powers = gets.chomp.split(" ").map(&:to_i)
pairs = []
n = nm[0]
m = nm[1]

m.times do
  pairs.push gets.chomp.split(" ").map(&:to_i)
end

nopairs = []

t = gets.to_i
forcedmove = false
selected = Set.new
justplayedpair = false

(2*n).times do
  if t==2
    opponentmove = gets.to_i
    if opponentmove==-1
      exit
    end
    selected.add(opponentmove)
    powers[opponentmove-1] = 0
    forcedmove = false
    if not justplayedpair
      toplayforced = -1

      pairs.each do |pair|
        if pair.include?(opponentmove)
          forcedmove = true
          toplayforced = (pair - [opponentmove])[0]
        end
      end
    end
    t=1

  else
    #your move
    if forcedmove
      toplay = toplayforced
      justplayedpair = false
    else
      #your move and it's free
      played = false
      pairs.each do |pair|
        if not selected.include?(pair[0])
          #play this pair
          toplay = pair.max
          played = true
          justplayedpair = true
        end
      end

      if not played
        toplay = powers.index(powers.max)+1
        justplayedpair = false
        #put the largest unselected no-pair dude
      end
    end

#    puts forcedmove
#    puts played
    puts toplay
    STDOUT.flush
    powers[toplay-1] = 0
    selected.add(toplay)
    t = 2
  end
end

require 'set'
nm = gets.chomp.split(" ").map(&:to_i)
powers = gets.chomp.split(" ").map(&:to_i)
pairs = []
n = nm[0]
m = nm[1]

m.times do
  pairs.push gets.chomp.split(" ").map(&:to_i)
end

nopairs = []

t = gets.to_i
forcedmove = false
selected = Set.new
justplayedpair = false
toplayforced = -1

(2*n).times do
#  puts "#{t} #{forcedmove} #{toplayforced} #{justplayedpair}"
  if t==2
    opponentmove = gets.to_i
    if opponentmove==-1
      powers[nil] =0
#      exit
    end
    selected.add(opponentmove)
    powers[opponentmove-1] = 0
    forcedmove = false
    if not justplayedpair
      toplayforced = -1

      pairs.each do |pair|
        if pair.include?(opponentmove)
          forcedmove = true
          toplayforced = (pair - [opponentmove])[0]
          break
        end
      end
    end
    t=1

  else
    #your move
    if forcedmove
      toplay = toplayforced
      justplayedpair = false
    else
      #your move and it's free
      played = false
      pairs.each do |pair|
        if not selected.include?(pair[0])
          #play this pair
          toplay = pair.max
          played = true
          justplayedpair = true
        end
      end

      if not played
        toplay = powers.index(powers.max)+1
        justplayedpair = false
        #put the largest unselected no-pair dude
      end
    end

#    puts forcedmove
#    puts played
    puts toplay
    STDOUT.flush
    powers[toplay-1] = 0
    selected.add(toplay)
    t = 2
  end
end

require 'set'
nm = gets.chomp.split(" ").map(&:to_i)
powers = gets.chomp.split(" ").map(&:to_i)
pairs = []
n = nm[0]
m = nm[1]

m.times do
  pairs.push gets.chomp.split(" ").map(&:to_i)
end

nopairs = []

t = gets.to_i
forcedmove = false
selected = Set.new
justplayedpair = false

(2*n).times do
  if t==2
    opponentmove = gets.to_i
    if opponentmove==-1
      exit
    end
    selected.add(opponentmove)
    powers[opponentmove-1] = 0

    if not justplayedpair
      forcedmove = false
      toplayforced = -1

      pairs.each do |pair|
        if pair.include?(opponentmove)
          forcedmove = true
          toplayforced = (pair - [opponentmove])[0]
        end
      end
    end
    t=1

  else
    #your move
    if forcedmove
      toplay = toplayforced
      justplayedpair = false
    else
      #your move and it's free
      played = false
      pairs.each do |pair|
        if not selected.include?(pair[0])
          #play this pair
          toplay = pair.max
          played = true
          justplayedpair = true
        end
      end

      if not played
        toplay = powers.index(powers.max)+1
        justplayedpair = false
        #put the largest unselected no-pair dude
      end
    end

#    puts forcedmove
#    puts played
    puts toplay
    STDOUT.flush
    powers[toplay-1] = 0
    selected.add(toplay)
    t = 2
  end
end

require 'set'
nm = gets.chomp.split(" ").map(&:to_i)
powers = gets.chomp.split(" ").map(&:to_i)
pairs = []
n = nm[0]
m = nm[1]

m.times do
  pairs.push gets.chomp.split(" ").map(&:to_i)
end

nopairs = []

t = gets.to_i
forcedmove = false
selected = Set.new
justplayedpair = false

(2*n).times do
  if t==2
    opponentmove = gets.to_i
    if opponentmove==-1
      exit
    end
    selected.add(opponentmove)
    powers[opponentmove-1] = 0

    if not justplayedpair
      forcedmove = false
      toplayforced = -1

      pairs.each do |pair|
        if pair.include?(opponentmove)
          forcedmove = true
          toplayforced = (pair - [opponentmove])[0]
        end
      end
    end
    t=1

  else
    #your move
    if forcedmove
      toplay = toplayforced
    else
      #your move and it's free
      played = false
      pairs.each do |pair|
        if not selected.include?(pair[0])
          #play this pair
          toplay = pair.max
          played = true
          justplayedpair = true
        end
      end

      if not played
        toplay = powers.index(powers.max)+1
        #put the largest unselected no-pair dude
      end
    end

#    puts forcedmove
#    puts played
    puts toplay
    STDOUT.flush
    powers[toplay-1] = 0
    selected.add(toplay)
    t = 2
  end
end


Four players participate in the playoff tournament. The tournament is held according to the following scheme: the first player will play with the second, and the third player with the fourth, then the winners of the pairs will play in the finals of the tournament.It is known that in a match between two players, the one whose skill is greater will win. The skill of the $$$i$$$-th player is equal to $$$s_i$$$ and all skill levels are pairwise different (i. e. there are no two identical values in the array $$$s$$$).The tournament is called fair if the two players with the highest skills meet in the finals.Determine whether the given tournament is fair.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. A single line of test case contains four integers $$$s_1, s_2, s_3, s_4$$$ ($$$1 \le s_i \le 100$$$) — skill of the players. It is guaranteed that all the numbers in the array are different.

For each testcase, output YES if the tournament is fair, or NO otherwise.

NoteConsider the example:  in the first test case, players $$$2$$$ and $$$3$$$ with skills $$$7$$$ and $$$9$$$ advance to the finals;  in the second test case, players $$$2$$$ and $$$4$$$ with skills $$$5$$$ and $$$9$$$ advance to the finals. The player with skill $$$6$$$ does not advance, but the player with skill $$$5$$$ advances to the finals, so the tournament is not fair;  in the third test case, players $$$1$$$ and $$$3$$$ with skills $$$5$$$ and $$$8$$$ advance to the finals;  in the fourth test case, players $$$1$$$ and $$$3$$$ with skills $$$6$$$ and $$$3$$$ advance to the finals. The player with skill $$$5$$$ does not advance, but the player with skill $$$3$$$ advances to the finals, so the tournament is not fair.

t = gets.to_i
t.times{|x|
	a = gets.split.map &:to_i
	if a.max(2) == a[0..1].sort.reverse || a.max(2) == a[2..3].sort.reverse then
		puts "NO"
	else
		puts "YES"
	end
}

def solution(arr)
	m1, m2 = [arr[0], arr[1]].max, [arr[2], arr[3]].max
	[m1, m2].sort == arr.max(2).sort
end

t = gets.to_i
t.times do
	arr = gets.chomp.split(' ').map(&:to_i)
	puts solution(arr) ? 'Yes' : 'No'
end

t = gets.to_i
t.times{|x|
	a = gets.split.map &:to_i
	if a.max(2) == a[0..1].sort.reverse || a.max(2) == a[2..3].sort.reverse then
		puts "YES"
	else
		puts "NO"
	end
}


Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The $$$i$$$-th page contains some mystery that will be explained on page $$$a_i$$$ ($$$a_i \ge i$$$).Ivan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page $$$i$$$ such that Ivan already has read it, but hasn't read page $$$a_i$$$). After that, he closes the book and continues to read it on the following day from the next page.How many days will it take to read the whole book?

The first line contains single integer $$$n$$$ ($$$1 \le n \le 10^4$$$) — the number of pages in the book. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$i \le a_i \le n$$$), where $$$a_i$$$ is the number of page which contains the explanation of the mystery on page $$$i$$$.

Print one integer — the number of days it will take to read the whole book.

NoteExplanation of the example test:During the first day Ivan will read only the first page. During the second day Ivan will read pages number $$$2$$$ and $$$3$$$. During the third day — pages $$$4$$$-$$$8$$$. During the fourth (and the last) day Ivan will read remaining page number $$$9$$$.

N = gets.to_i
A = gets.split.map &:to_i
ans = 0
am = nil
(1..N).each{ |i|
  a = A[i-1]
  if !am
    am = a
    ans += 1
  end
  am = a if a > am
  if am <= i
    am = nil
    next
  end
}
p ans

require 'set'
#if File.exists?("input")
#  $stdin = File.open("input")
#  $stdout = File.open("output","w")
#end
n = gets.to_i
arr = gets.chomp.split(" ").map(&:to_i)

i=0
ans=0
mySet = Set.new

while(i<n)
	ans+=1;
    loop do
		mySet.add(arr[i])
    	if(mySet.include?(i+1))
    		mySet.delete(i+1)
    	end
    	i+=1
    	break if mySet.empty?
    end
end

puts ans


Alice and Bob play ping-pong with simplified rules.During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return.The one who doesn't make a return loses this play. The winner of the play commences the next play. Alice starts the first play.Alice has $$$x$$$ stamina and Bob has $$$y$$$. To hit the ball (while serving or returning) each player spends $$$1$$$ stamina, so if they don't have any stamina, they can't return the ball (and lose the play) or can't serve the ball (in this case, the other player serves the ball instead). If both players run out of stamina, the game is over.Sometimes, it's strategically optimal not to return the ball, lose the current play, but save the stamina. On the contrary, when the server commences a play, they have to hit the ball, if they have some stamina left.Both Alice and Bob play optimally and want to, firstly, maximize their number of wins and, secondly, minimize the number of wins of their opponent.Calculate the resulting number of Alice's and Bob's wins.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^6$$$) — Alice's and Bob's initial stamina.

For each test case, print two integers — the resulting number of Alice's and Bob's wins, if both of them play optimally.

NoteIn the first test case, Alice serves the ball and spends $$$1$$$ stamina. Then Bob returns the ball and also spends $$$1$$$ stamina. Alice can't return the ball since she has no stamina left and loses the play. Both of them ran out of stamina, so the game is over with $$$0$$$ Alice's wins and $$$1$$$ Bob's wins.In the second test case, Alice serves the ball and spends $$$1$$$ stamina. Bob decides not to return the ball — he loses the play but saves stamina. Alice, as the winner of the last play, serves the ball in the next play and spends $$$1$$$ more stamina. This time, Bob returns the ball and spends $$$1$$$ stamina. Alice doesn't have any stamina left, so she can't return the ball and loses the play. Both of them ran out of stamina, so the game is over with $$$1$$$ Alice's and $$$1$$$ Bob's win.In the third test case, Alice serves the ball and spends $$$1$$$ stamina. Bob returns the ball and spends $$$1$$$ stamina. Alice ran out of stamina, so she can't return the ball and loses the play. Bob, as a winner, serves the ball in the next $$$6$$$ plays. Each time Alice can't return the ball and loses each play. The game is over with $$$0$$$ Alice's and $$$7$$$ Bob's wins.

n = gets.chomp.to_i
n.times do
    s, t = gets.chomp.split(" ").map(&:to_i)
    if s  == t
        puts "#{s-1}" + " " + "#{t}"
    elsif s > t
        puts "#{s-1}" + " " + "#{t}"
    elsif s < t
        puts "#{s-1}" + " " + "#{t}"
    end
end

t = gets.to_i
t.times do
 a, b = gets.split.map(&:to_i)
 puts (a-1).to_s + " " + b.to_s
end

n = gets.chomp.to_i
n.times do
    s, t = gets.chomp.split(" ").map(&:to_i)
    if s  == t
        if s == 1
            x = 0
            y = 1
            puts "#{x}" + " " "#{y}"
        else
            puts "#{s}" + " " + "#{t}"
        end
    elsif s > t
        puts "#{s-t}" + " " + "#{t}"
    elsif s < t
        puts "#{s-1}" + " " + "#{t-(s-1)}"
    end
end

n = gets.chomp.to_i
n.times do
    s, t = gets.chomp.split(" ").map(&:to_i)
    if s  == t
        puts "#{s-1}" + " " + "#{t}"
    elsif s > t
        puts "#{s-1}" + " " + "#{t}"
    elsif s < t
        puts "#{s-1}" + " " + "#{t-1}"
    end
end

n = gets.chomp.to_i
n.times do
    s, t = gets.chomp.split(" ").map(&:to_i)
    if s  == t
        puts "#{s-1}" + " " + "#{t}"
    elsif s > t
        puts "#{s-t}" + " " + "#{t}"
    elsif s < t
        puts "#{s-1}" + " " + "#{t-(s-1)}"
    end
end

n = gets.chomp.to_i
n.times do
    s, t = gets.chomp.split(" ").map(&:to_i)
    if s  == t
        if s == 1
            x = 0
            y = 1
            puts "#{x}" + " " "#{y}"
        else
            puts "#{s}" + " " + "#{t}"
        end
    elsif s > t
        puts "#{s-1}" + " " + "#{t}"
    elsif s < t
        puts "#{s}" + " " + "#{t-1}"
    end
end


You are given a string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters and an integer number $$$k$$$.Let's define a substring of some string $$$s$$$ with indices from $$$l$$$ to $$$r$$$ as $$$s[l \dots r]$$$.Your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ positions $$$i$$$ such that $$$s[i \dots i + n - 1] = t$$$. In other words, your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$.It is guaranteed that the answer is always unique.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 50$$$) — the length of the string $$$t$$$ and the number of substrings. The second line of the input contains the string $$$t$$$ consisting of exactly $$$n$$$ lowercase Latin letters.

Print such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$. It is guaranteed that the answer is always unique.

n, k = gets.split.map(&:to_i)
s = gets.chomp
m = (n + 1..n * 2).find { |i|
	str = "?" * i
	str[...n] = s
	str[-n..] = s
	str[...n] == s
} - n
puts s + s[-m..] * (k - 1)

N, K = gets.split.map(&:to_i)
s = gets.chomp
n = N
(1...N).each do |i|
    if s[i, N-i] == s[0, N-i]
        n = i
        break
    end
end
ans = ''
(K-1).times do
    ans << s[0, n]
end
ans << s
puts ans

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

t=s.dup
k-=1

j = n-1
while j>0
  break if t[(n-j)...n] == s[0...j]
  j-=1
end

k.times do
  t << s[j...n]
end
puts t

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

i = nil
j = 0
loop {
  i = j if t[0..j] == t[-1-j..-1]
  j += 1
  break if j >= t.size-1
}

puts (t.size == 1 || i.nil? ? t * k : t[0..i] + t[i+1..-1] * k)

#i_am_fucking_stupid

v = gets.chomp.split(" ")
a = gets.chomp

s = a.size

m = 0

for i in 1..s-1
	temp = a[0...i]
	if temp == a[-i..-1]
		if m < temp.size
			m = temp.size
		end
	end
end

print a
(v[1].to_i - 1).times do
	print(a[m..-1])
end

n, k = gets.split().map{ |x| x.to_i }
s = gets.chomp
len = n - 1
until len == 0 do
    if s[0, len] == s[n - len, len]
        break
    end
    len -= 1
end
t = s[len, n - len]
(k - 1).times { s = s + t }
puts s

def ascan; gets.split.map(&:to_i); end

n,k = ascan
str = gets.chomp

if k == 1
    puts str; exit
elsif n == 1
    puts str*k; exit
else
    t = nil
    1.upto(n-1) do |i|
        if str[i..-1] == str[0..(-1-i)]
            header = str[0...i]
            footer = str[i..-1]
            puts header*k+footer; exit
        end
    end
    puts str*k; exit
end

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

def splitof(str)
  a = str.length-2
  while a >=0
    break if str[0..a]==str[-1-a..-1]
    a-=1
  end

  if a==-1
    return [str,""]
  else
    return [str[0..-2-a],str[-1-a..-1]]
  end
end

asd = splitof(str)
#p asd
k.times do
  print(asd[0])
end

print(asd[1])
puts

#! /usr/bin/env ruby

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

def c(s, t)
  cnt=0
  (0..(s.size-t.size)).each do |i|
    cnt+=1 if s[i...(i+t.size)]==t
  end
  # print "#{s} #{t} #{cnt}\n"
  return cnt==2
end

n.times do |i|
  t=s+s[-(i+1)..-1]
  # print "#{t} #{s} #{s[-(i+1)..-1]}\n"
  if c(t, s)
    puts s+s[-(i+1)..-1]*(k-1)
    break
  end
end

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

t=s.dup
k-=1

k.times do
  j = 1
  while j<n && t[(n-j)...n] == s[0...j]
    j+=1
  end
  j-=1
  t += s[j...n]
end
puts t

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

i = 0
loop {
  t[0..i] == t[-1-i..-1] ? i += 1 : break
  break if i > t.size-1-i
}
i = -1 if t[0] != t[-1]

puts (t.size == 1 ? t * k : i == -1 ? t * k : t[0..t.size-i-1] * k + t[t.size-i..-1])

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

i = j = 0
loop {
  t[0..j] == t[-1-j..-1] ? i = j : nil
  j += 1
  break if j > t.size-1-j
}
i = -1 if t[0] != t[-1]

puts (t.size == 1 ? t * k : i == -1 ? t * k : t[0..t.size-i-1] + t[t.size-i..-1] * k)

a = gets.chomp.split(" ")
st = gets.chomp

j = 0
i = 1
while i < a[0].to_i
  if(st[i] == st[j])
    j += 1
  else
    if(j > 0)
      i -= 1
     end
    j = 0
  end
  i += 1
end

print(st)

(a[1].to_i-1).times do
  print(st[j...a[0].to_i])
end

a = gets.chomp.split(" ")
st = gets.chomp

j = 0
i = 1
while i < a[0].to_i
  if(st[i] == st[j])
    j += 1
  else
    j = 0
  end
  i += 1
end

print(st)

(a[1].to_i-1).times do
  print(st[j...a[0].to_i])
end

v = gets.chomp.split(" ")
a = gets.chomp

s = (a.size / 2).ceil
m = 0

for i in 1..s
	temp = a[0...i]
	if temp == a[-i..-1]
		if m < temp.size
			m = temp.size
		end
	end
end

print a
(v[1].to_i - 1).times do
	print(a[m..-1])
end


You had $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ arranged in a circle. For each pair of neighboring numbers ($$$a_1$$$ and $$$a_2$$$, $$$a_2$$$ and $$$a_3$$$, ..., $$$a_{n - 1}$$$ and $$$a_n$$$, and $$$a_n$$$ and $$$a_1$$$), you wrote down: are the numbers in the pair equal or not.Unfortunately, you've lost a piece of paper with the array $$$a$$$. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array $$$a$$$ which is consistent with information you have about equality or non-equality of corresponding pairs?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ cases follow. The first and only line of each test case contains a non-empty string $$$s$$$ consisting of characters E and/or N. The length of $$$s$$$ is equal to the size of array $$$n$$$ and $$$2 \le n \le 50$$$. For each $$$i$$$ from $$$1$$$ to $$$n$$$:    if $$$s_i =$$$ E then $$$a_i$$$ is equal to $$$a_{i + 1}$$$ ($$$a_n = a_1$$$ for $$$i = n$$$);  if $$$s_i =$$$ N then $$$a_i$$$ is not equal to $$$a_{i + 1}$$$ ($$$a_n \neq a_1$$$ for $$$i = n$$$).

For each test case, print YES if it's possible to choose array $$$a$$$ that are consistent with information from $$$s$$$ you know. Otherwise, print NO. It can be proved, that if there exists some array $$$a$$$, then there exists an array $$$a$$$ of positive integers with values less or equal to $$$10^9$$$.

NoteIn the first test case, you can choose, for example, $$$a_1 = a_2 = a_3 = 5$$$.In the second test case, there is no array $$$a$$$, since, according to $$$s_1$$$, $$$a_1$$$ is equal to $$$a_2$$$, but, according to $$$s_2$$$, $$$a_2$$$ is not equal to $$$a_1$$$.In the third test case, you can, for example, choose array $$$a = [20, 20, 4, 50, 50, 50, 20]$$$.In the fourth test case, you can, for example, choose $$$a = [1, 3, 3, 7]$$$.

gets.to_i.times{puts gets.count(?N)==1 ? "NO" : "YES"}

gets.to_i.times{puts gets.count(?N)==1 ? "NO":"YES"}


You are given a sequence $$$a$$$, initially consisting of $$$n$$$ integers.You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).To achieve this, you choose some integer $$$x$$$ that occurs at least once in $$$a$$$, and then perform the following operation any number of times (possibly zero): choose some segment $$$[l, r]$$$ of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains $$$x$$$. More formally, you choose some contiguous subsequence $$$[a_l, a_{l + 1}, \dots, a_r]$$$ such that $$$a_i \ne x$$$ if $$$l \le i \le r$$$, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the $$$(r+1)$$$-th is now $$$l$$$-th, the element that was $$$(r+2)$$$-th is now $$$(l+1)$$$-th, and so on (i. e. the remaining sequence just collapses).Note that you can not change $$$x$$$ after you chose it.For example, suppose $$$n = 6$$$, $$$a = [1, 3, 2, 4, 1, 2]$$$. Then one of the ways to transform it in two operations is to choose $$$x = 1$$$, then:  choose $$$l = 2$$$, $$$r = 4$$$, so the resulting sequence is $$$a = [1, 1, 2]$$$;  choose $$$l = 3$$$, $$$r = 3$$$, so the resulting sequence is $$$a = [1, 1]$$$. Note that choosing $$$x$$$ is not an operation. Also, note that you can not remove any occurrence of $$$x$$$.Your task is to find the minimum number of operations required to transform the sequence in a way described above.You have to answer $$$t$$$ independent test cases.

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

For each test case, print the answer — the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  dp = Hash.new {|_| [-1]}
  arr.each_with_index do |el, ind|
    if dp.has_key?(el)
      dp[el] << ind
    else
      dp[el] = dp[el] + [ind]
    end
    #dp[el] = dp[el] + [ind]
  end
  mn = 10 ** 10
  mn_v = -1
  dp.each do |k, v|
    tmp = 0
    st = v[0]
    (v[1..] + [n]).each do |el|
      if (el - st > 1)
        tmp += 1
      end
      st = el
    end
    mn = [mn, tmp].min
  end
  puts mn
end

t = gets.to_i

1.upto t do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  new = a.chunk(&:itself).map(&:first)
  h = new.tally
  h[new[0]] -= 1
  h[new[-1]] -= 1
  puts h.values.min + 1
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  dp = Hash.new {|_| [-1]}
  arr.each_with_index do |el, ind|
    if dp.has_key?(el)
        dp[el] << ind
      else
        dp[el] = dp[el]
      end
  end
  mn = 10 ** 10
  mn_v = -1
  dp.each do |k, v|
    tmp = 0
    st = v[0]
    (v[1..] + [n]).each do |el|
      if (el - st > 1)
        tmp += 1
      end
      st = el
    end
    mn = [mn, tmp].min
  end
  puts mn
end


Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≤ i ≤ n) has a best friend p[i] (1 ≤ p[i] ≤ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i].Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm:   on the first day of revising each student studies his own Mathematical Analysis notes,  in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≤ i ≤ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study.You are given two sequences that describe the situation on the third and fourth days of revising:  a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising;  b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b.

The first line contains integer n (1 ≤ n ≤ 105) — the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≤ ai ≤ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≤ bi ≤ n).

Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≤ p[i] ≤ n). It is guaranteed that the solution exists and that it is unique.

n = gets.to_i
a = gets.split.map &:to_i
b = gets.split.map &:to_i
d = Array.new(n + 1)
a.each_with_index { |x, i| d[x] = i + 1 }
c = b.each.map { |x| d[x] }
puts c

n = gets.to_i
a = gets.split.map &:to_i
b = gets.split.map &:to_i
d = []
a.each_with_index { |x, i| d[x] = i + 1 }
c = b.each.map { |x| d[x] }
puts c

gets
d = []
gets.split.each_with_index { |x, i| d[x.to_i] = i + 1 }
puts gets.split.each.map { |x| d[x.to_i] }

n = gets.chomp.to_i
a = gets.chomp.split(/ /).map!{|x| x.to_i}
b = gets.chomp.split(/ /).map!{|x| x.to_i}
ab = []
for i in 0..n-1
    ab << [a[i], b[i]]
end
ab.sort!{|ab1,ab2|
    ab1[0] <=> ab2[0]
}
ret = []
for i in 0..n-1
    ret << ab[i][1]
end
puts ret.join(" ")

n = gets.to_i
a, b = [0, 1].map { gets.split.map(&:to_i) }
p = []
n.times do |i|
  p[a[i] - 1] = b[i]
end
puts p.join(' ')


There is an array $$$a$$$ with $$$n-1$$$ integers. Let $$$x$$$ be the bitwise XOR of all elements of the array. The number $$$x$$$ is added to the end of the array $$$a$$$ (now it has length $$$n$$$), and then the elements are shuffled.You are given the newly formed array $$$a$$$. What is $$$x$$$? If there are multiple possible values of $$$x$$$, you can output any of them.

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 description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of integers in the resulting array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 127$$$) — the elements of the newly formed array $$$a$$$. Additional constraint on the input: the array $$$a$$$ is made by the process described in the statement; that is, some value of $$$x$$$ exists.

For each test case, output a single integer — the value of $$$x$$$, as described in the statement. If there are multiple possible values of $$$x$$$, output any of them.

NoteIn the first test case, one possible array $$$a$$$ is $$$a=[2, 5, 4]$$$. Then $$$x = 2 \oplus 5 \oplus 4 = 3$$$ ($$$\oplus$$$ denotes the bitwise XOR), so the new array is $$$[2, 5, 4, 3]$$$. Afterwards, the array is shuffled to form $$$[4, 3, 2, 5]$$$.In the second test case, one possible array $$$a$$$ is $$$a=[1, 10, 6, 10]$$$. Then $$$x = 1 \oplus 10 \oplus 6 \oplus 10 = 7$$$, so the new array is $$$[1, 10, 6, 10, 7]$$$. Afterwards, the array is shuffled to form $$$[6, 1, 10, 7, 10]$$$.In the third test case, all elements of the array are equal to $$$6$$$, so $$$x=6$$$.In the fourth test case, one possible array $$$a$$$ is $$$a=[100, 100]$$$. Then $$$x = 100 \oplus 100 = 0$$$, so the new array is $$$[100, 100, 0]$$$. Afterwards, the array is shuffled to form $$$[100, 100, 0]$$$. (Note that after the shuffle, the array can remain the same.)

(1..gets.to_i).map{
  gets
  puts gets.split[0]}

(1..gets.to_i).map{
  gets
  puts gets.sub(/\s.*$/,"") }

(1..gets.to_i).map{
  gets
  puts gets.split.map(&:to_i)[0] }

gets.to_i.times do
  gets
  puts gets.split.map(&:to_i)[0]
end

gets.to_i.times do
  gets.to_i
  puts gets.split.map(&:to_i)[0]
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  n.times do |i|
    x = 0
    n.times do |j|
      x ^= a[j] if j != i
    end
    if (a[i] == x)
      puts a[i]
      break
    end
  end
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  for i in 0..(n - 1)
    x = 0
    for j in 0..(n - 1)
      x ^= a[j] if j != i
    end
    if (a[i] == x)
      puts a[i]
      break
    end
  end
end

# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  n.times do |i|
    now = a[i]
    sum = 0
    n.times do |j|
      next if i == j
      sum ^= a[j]
    end
    if now == sum
      puts now
      break
    end
  end
end


One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game.He took a checkered white square piece of paper, consisting of n × n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him.Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist.

The first line contains two integers n and m (1 ≤ n ≤ 1000, 1 ≤ m ≤ min(n·n, 105)) — the size of the squared piece of paper and the number of moves, correspondingly.  Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the number of row and column of the square that gets painted on the i-th move.  All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom.

On a single line print the answer to the problem — the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1.

n,m = gets.split.map(&:to_i)
bins = Array.new(n){Array.new(n){0}}
p [*1..m].find{ |o|
    x,y = gets.split.map(&:to_i)
    y-=1; x-=1
    !->{
        if y>=2
            return if 9 == bins[y-2][x-2] += 1 if x>=2
            return if 9 == bins[y-2][x-1] += 1 if x>=1
            return if 9 == bins[y-2][x] += 1
        end
        if y>=1
            return if 9 == bins[y-1][x-2] += 1 if x>=2
            return if 9 == bins[y-1][x-1] += 1 if x>=1
            return if 9 == bins[y-1][x] += 1
        end
            return if 9 == bins[y][x-2] += 1 if x>=2
            return if 9 == bins[y][x-1] += 1 if x>=1
            return if 9 == bins[y][x] += 1
        true
    }[]
} || -1

n, m = STDIN.readline.split.map {|s| s.to_i }
lines = STDIN.readlines
count = n.times.map { n.times.map { 0 } }
dr = [-1, -1, -1, 0, 0, 0, 1, 1, 1]
dc = [-1, 0, 1, -1, 0, 1, -1, 0, 1]
lines.each_with_index do |line, i|
	x, y = line.split.map {|s| s.to_i-1 }
	9.times do |j|
		r = x+dr[j]
		next if r == -1 or r == n
		c = y+dc[j]
		next if c == -1 or c == n
		count[r][c] += 1
		if count[r][c] == 9
			puts i+1
			exit
		end
	end
end
puts -1

n, m = STDIN.readline.split.map {|s| s.to_i }
count = n.times.map { n.times.map { 0 } }
result = -1
dr = [-1, -1, -1, 0, 0, 0, 1, 1, 1]
dc = [-1, 0, 1, -1, 0, 1, -1, 0, 1]
m.times do |i|
	x, y = STDIN.readline.split.map {|s| s.to_i-1 }
	next if result != -1
	9.times do |j|
		r = x+dr[j]
		next if r == -1 or r == n
		c = y+dc[j]
		next if c == -1 or c == n
		count[r][c] += 1
		if count[r][c] == 9
			result = i+1
		end
	end
end
puts result

n,m = gets.split.map(&:to_i)
array = Array.new(n){ Array.new(n) }

m.times do |z|
    x,y = gets.split.map(&:to_i)
    x -= 1
    y -= 1
    array[x][y] = true
    -1.upto(1) do |i|
        if x+i <0 || x+i >n-1
            next
        end
        -1.upto(1) do |j|
            if y+j <0 || y+j >n-1
                next
            end
            if(!array[x+i][y+j])
                next
            end
            black = 0
            catch(:exit) {
            -1.upto(1) do |k|
                if x+i+k < 0 || x+i+k > n-1
                    next
                end
                -1.upto(1) do |l|
                    if y+j+l < 0 || y+j+l > n-1
                        next
                    end
                    if(array[x+i+k][y+j+l])
                        black += 1
                    else
                    throw :exit
                    end
                end
            end
            if black == 9
                puts z+1
                exit
            end
            }
        end
    end
end
puts -1

n,m = gets.split.map(&:to_i)
array = Array.new(n){ Array.new(n) }

m.times do |i|
    x,y = gets.split.map(&:to_i)
    x -= 1
    y -= 1
    array[x][y] = true
    -1.upto(1) do |i|
        if x+i <0 || x+i >n-1
            next
        end
        -1.upto(1) do |j|
            if y+j <0 || y+j >n-1
                next
            end
            if(!array[x+i][y+j])
                next
            end
            black = 0
            -1.upto(1) do |k|
                if x+i+k < 0 || x+i+k > n-1
                    next
                end
                -1.upto(1) do |l|
                    if y+j+l < 0 || y+j+l > n-1
                        next
                    end
                    if(array[x+i+k][y+j+l])
                        black += 1
                    else
                        break
                    end
                end
            end
            if black == 9
                puts m-1
                exit
            end
        end
    end
end
puts -1


A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?

The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion.  The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.

Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print  - 1.

#!/usr/bin/ruby
gets
m=gets.split.map(&:to_i).min-1
p m==0 ? -1 : 1

gets
z = gets.split.map(&:to_i).min - 1
if z==0
    puts -1
else
    puts 1
end

n = gets.to_i
currency = gets.split(' ')
currency.map!{|c| c.to_i}
currency.sort!
if currency.first == 1
    puts -1
else
    puts 1
end

# http://codeforces.com/contest/560/problem/A
# A. Currency System in Geraldion
def unfortunate_value(values)
  return nil if values.include?(1)

  values.sort!
  (1..(10**6)).to_a.find do |n|
    values.all? { |v| n % v != 0 }
  end
end

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

ans = unfortunate_value(values)
puts ans.nil? ? -1 : ans

n = gets.to_i
input = gets.split(' ')
nums = (input.collect { |x| x.to_i }).sort!

if nums[0] == 1
	puts -1
else
	puts 1
end

n = gets.to_i
a = gets.split.map(&:to_i).sort
puts a[0] == 1 ? -1 : 1

n=gets.to_i
x=gets.split.map{|e| e.to_i}.min
if x==1 then
	puts -1
else
	puts 1
end

gets
nums = gets.chomp.split.map(&:to_i)
puts nums.include?(1) ? -1 : 1

gets
q = gets.split.map { |c| c.to_i }.sort
puts q[0] == 1 ? -1 : 1

n = gets.chomp
A = []
nbs = gets.chomp.split(" ")
exist = false
nbs.each do |x|
    exist ||= x.to_i == 1
end

if exist
    print -1
else
    print 1
end

n = gets.chomp
A = []
nbs = gets.chomp.split(" ")
exist = false
nbs.each do |x|
    exist = true if x.to_i == 1
end

print exist ? -1 : 1

# coding: utf-8

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

if ar.first == 1
    puts "-1" # 1 can express all!
else
    puts 1
end

n = gets.to_i
a = gets.split.map(&:to_i)
puts a.include?(1) ? -1 : 1

arr=gets(gets).split.map(&:to_i).sort(); puts arr[0] == 1 ? "-1" : "1"

num = gets.to_i
numbers=gets.split(' ')
result = numbers.collect{ |x| x.to_i }.sort!
puts -1 if result[0] == 1
puts 1 if result[0] != 1

banknoteNum = gets.chomp.to_i
banknotes = gets.chomp.split(' ').map {|item| item.to_i}

if banknotes.include?(1)
	puts "-1"
	exit
else
	puts "1"
	exit
end

banknotes.sort!

nowIndex = 0

until banknotes.length - 1 == nowIndex
	if banknotes[nowIndex + 1] - banknotes[nowIndex] > 1
		puts banknotes[nowIndex] + 1
		exit
	end

 	nowIndex += 1
 end

#!/usr/bin/ruby
gets
m=gets.split.map(&:to_i).min-1
p m==0 ? -1 : m

# http://codeforces.com/contest/560/problem/A
# A. Currency System in Geraldion
def unfortunate_value(values)
  return nil if values.include?(1)

  values.sort!
  (1..(10**6)).to_a.select do |n|
    return true if values.all? { |v| n % v != 0 }
  end.first
end

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

ans = unfortunate_value(values)
puts ans.nil? ? -1 : ans

# coding: utf-8

n = gets.to_i
ar = gets.split.map(&:to_i).sort
total_sum = ar.reduce(:+)
i = 0
uf_num = -1
for j in ar
    if j - i > 1
        uf_num = i
        break
    else
        i = j
    end
end

if uf_num == -1
    puts "-1"
else
    puts total_sum - 1
end

# coding: utf-8

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

if ar.first == 1
    puts "-1" # 1 can express all!
else
    puts ar.first - 1
end

# coding: utf-8

n = gets.to_i
ar = gets.split.map(&:to_i).sort
total_sum = ar.reduce(:+)
i = ar.first
uf_num = -1
for j in ar[1..-1]
    if j - i > 1
        uf_num = i + 1
        break
    else
        i = j
    end
end

if uf_num == -1
    puts "-1"
else
    puts total_sum - (uf_num - 1) + uf_num
end

arr=gets.split.map(&:to_i).sort(); puts arr[0] == 1 ? "-1" : "1"


A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length $$$0$$$ are not allowed).Let's consider empty cells are denoted by '.', then the following figures are stars:  The leftmost figure is a star of size $$$1$$$, the middle figure is a star of size $$$2$$$ and the rightmost figure is a star of size $$$3$$$. You are given a rectangular grid of size $$$n \times m$$$ consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from $$$1$$$ to $$$n$$$, columns are numbered from $$$1$$$ to $$$m$$$. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed $$$n \cdot m$$$. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most $$$n \cdot m$$$ stars.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$3 \le n, m \le 100$$$) — the sizes of the given grid. The next $$$n$$$ lines contains $$$m$$$ characters each, the $$$i$$$-th line describes the $$$i$$$-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only.

If it is impossible to draw the given grid using stars only, print "-1". Otherwise in the first line print one integer $$$k$$$ ($$$0 \le k \le n \cdot m$$$) — the number of stars needed to draw the given grid. The next $$$k$$$ lines should contain three integers each — $$$x_j$$$, $$$y_j$$$ and $$$s_j$$$, where $$$x_j$$$ is the row index of the central star character, $$$y_j$$$ is the column index of the central star character and $$$s_j$$$ is the size of the star. Each star should be completely inside the grid.

NoteIn the first example the output 23 4 13 5 2is also correct.

def make_hash(n, m, boardstr)
  {}.tap do |h|
    (0...n).each do |i|
      (0...m).each do |j|
        h[[i,j]] = true if boardstr[i][j] == ?*
      end
    end
  end
end

require 'set'

def move(point, y, x)
  i, j = point
  [i + y, j + x]
end

def get_star(board, i, j)
  p, q = i, j

  points = Set.new

  up = [p, q]
  down = [p, q]
  left = [p, q]
  right = [p, q]

  size = -1

  while board[up] && board[down] && board[left] && board[right]
    points << up
    points << down
    points << left
    points << right

    size += 1

    up = move(up, -1, 0)
    down = move(down, 1, 0)
    left = move(left, 0, -1)
    right = move(right, 0, 1)
  end

  [points, size] if size > 0

end

def solution
  n, m = read_ints

  boardstr = []

  n.times do
    boardstr << read_string
  end

  board = make_hash(n, m, boardstr)
  lit = Set.new(board.keys)

  stars = []

  (1...(n-1)).each do |i|
    (1...(m-1)).each do |j|
      star_points, star_size = get_star(board, i, j)
      next unless star_points

      stars << [i+1, j+1, star_size]
      lit.subtract(star_points)

    end
  end

  if lit.empty?
    puts stars.size
    stars.each do |s|
      puts s.join(' ')
    end
  else
    puts(-1)
  end

end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

H, W = gets.split.map(&:to_i)
pic = []
H.times do |i|
    pic[i] = gets.chomp
end

down = Array.new(H+1){Array.new(W+1, -1)}
up = Array.new(H+1){Array.new(W+1, -1)}
left = Array.new(H+1){Array.new(W+1, -1)}
right = Array.new(H+1){Array.new(W+1, -1)}

H.times do |i|
    W.times do |j|
        up[i][j] = (pic[i][j] == '*' ? up[i-1][j] + 1 : -1)
        left[i][j] = (pic[i][j] == '*' ? left[i][j-1] + 1 : -1)
    end
end
(H-1).downto(0) do |i|
    (W-1).downto(0) do |j|
        down[i][j] = pic[i][j] == '*' ? down[i+1][j] + 1 : -1
        right[i][j] = pic[i][j] == '*' ? right[i][j+1] + 1 : -1
    end
end

ans = []
H.times do |i|
    W.times do |j|
        num = [down[i][j], left[i][j], up[i][j], right[i][j]].min
        if num > 0
            pic[i][j] = '.'
            (1..num).each do |k|
                pic[i-k][j] = '.'
                pic[i+k][j] = '.'
                pic[i][j-k] = '.'
                pic[i][j+k] = '.'
            end
            ans.push([i+1, j+1, num])
        end
    end
end

if pic.all?{|row| row.count('*') == 0}
    puts ans.length
    ans.each do |arr|
        puts arr.join(' ')
    end
else
    puts -1
end


DZY has a sequence a, consisting of n integers.We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment.Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.You only need to output the length of the subsegment you find.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).

In a single line print the answer to the problem — the maximum length of the required subsegment.

NoteYou can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.

n = gets.chomp.to_i
if n == 1
	puts 1
	exit
end
a = gets.split.map{ |i| i.to_i }
r = [1] * n
l = r.clone

( 1..n-1 ).each do |i|
	l[i] = l[i-1] + 1 if a[i] > a[i-1]
end

(n - 2).downto( 0 ).each do |i|
	r[i] = r[i+1] + 1 if a[i] < a[i+1]
end

ans = r[1] + 1
( 1..n-2 ).each do |i|
	ans = [ans, l[i-1] + r[i+1] + 1].max if a[i+1] - a[i-1] >= 2
	ans = [ans, l[i-1] + 1].max
	ans = [ans, r[i+1] + 1].max
end
ans = [ans, l[-2] + 1].max
puts ans

# Calculates the derivative
def derivative(ar)
    return ar.clone().unshift(0).each_cons(2).map{|x, y| y - x}
    # each_cons returns an iterator over pairs of elements
    # clone to get over the dumb ruby passig by reference
end

# Returns indices of non-increaseing points
def loc(ar)
    # Obtain the derivative of the input
    der = derivative(ar)
    return der.each_index.select{|i| der[i] <= 0}
    # each_index returns an itetrator over indices
    # select returns elements that match condition
end

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

# Obtain the locations of non-increasing points
negloc = loc(a).unshift(0).push(n)

# Create an array to store lengths of segments
seqlength = [negloc[1]]

# Loop over locations of non-increasing points
for i in 1..(negloc.length - 1) do
    j = negloc[i]
    if i == negloc.length - 1
        seqlength[i] = negloc[i] - negloc[i-1] + 1
    elsif j + 1 < a.length && a[j-1] + 1 < a[j+1]
        seqlength[i] = negloc[i+1] - negloc[i-1]
    elsif j - 2 > -1 && a[j-2] + 1 < a[j]
        seqlength[i] = negloc[i+1] - negloc[i-1]
    else
        seqlength[i] = negloc[i] - negloc[i-1] + 1
    end
end

puts [seqlength.max,n].min

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

left, right = Array.new(n), Array.new(n)

best = n <= 2 ? n : 1
left[0] = 1
(1..(n - 1)).each do |i|
  left[i] = a[i] > a[i - 1] ? left[i - 1] + 1 : 1
end

right[n - 1] = 1
(0..(n - 2)).to_a.reverse.each do |i|
  right[i] = a[i] < a[i + 1] ? right[i + 1] + 1 : 1
end

(1..(n - 2)).each do |i|
  best = [best, left[i - 1] + right[i + 1] + 1].max if a[i - 1] + 1 < a[i + 1]
  best = [best, left[i] + 1].max
  best = [best, right[i] + 1].max
end

puts best

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

left, right = Array.new(n), Array.new(n)

best = n <= 2 ? n : 1
left[0] = 1
(1..(n - 1)).each do |i|
  left[i] = a[i] > a[i - 1] ? left[i - 1] + 1 : 1
  # puts best
end

right[n - 1] = 1
(0..(n - 2)).to_a.reverse.each do |i|
  right[i] = a[i] < a[i + 1] ? right[i + 1] + 1 : 1
  # puts best
end

(1..(n - 2)).each do |i|
  best = [best, left[i - 1] + right[i + 1] + 1].max if a[i - 1] + 1 < a[i + 1]
  best = [best, left[i] + 1].max
  best = [best, right[i] + 1].max
  # puts best
end

# puts left.join(" ")
# puts right.join(" ")
puts best

n = gets.to_i
a = gets.split(' ').map { |c| c.to_i }

if n == 1
    puts 1
    exit
end

leftright = Array.new(n, 0)
rightleft = Array.new(n, 0)
leftright[0] = rightleft[n - 1] = 1

(n - 1).times do |i|
    pos = i + 1
    leftright[pos] = 1 + (a[pos] > a[pos - 1] ? leftright[pos - 1] : 0)
end
(n - 1).times do |i|
    pos = n - i - 2
    rightleft[pos] = 1 + (a[pos] < a[pos + 1] ? rightleft[pos + 1] : 0)
end

best = 1 + [rightleft[1], leftright[n - 2]].max
(n - 2).times do |i|
    pos = i + 1
    best = [best, leftright[pos - 1] + 1].max
    best = [best, rightleft[pos + 1] + 1].max
    if a[pos - 1] + 2 <= a[pos + 1]
        best = [best, leftright[pos - 1] + 1 + rightleft[pos + 1]].max
    end
end

puts best

n = gets.chomp.to_i
a = gets.split.map{ |i| i.to_i }
r = [1] * n
l = r.clone

( 1..n-1 ).each do |i|
	l[i] = l[i-1] + 1 if a[i] > a[i-1]
end

(n - 2).downto( 0 ).each do |i|
	r[i] = r[i+1] + 1 if a[i] < a[i+1]
end

ans = r[0]
( 1..n-2 ).each do |i|
	ans = [ans, l[i-1] + r[i+1] + 1].max if a[i+1] - a[i-1] >= 2
end
ans = [ans, l[-1]].max
puts ans

n = gets.chomp.to_i
a = gets.split.map{ |i| i.to_i }
r = [1] * n
l = r.clone

( 1..n-1 ).each do |i|
	l[i] = l[i-1] + 1 if a[i] > a[i-1]
end

(n - 2).downto( 0 ).each do |i|
	r[i] = r[i+1] + 1 if a[i] < a[i+1]
end

ans = r[0]
( 1..n-2 ).each do |i|
	ans = [ans, l[i-1] + r[i+1] + 1].max if a[i+1] - a[i-1] >= 2
	ans = [ans, l[i-1] + 1].max
	ans = [ans, r[i+1] + 1].max
end
ans = [ans, l[-1]].max
puts ans

n = gets.chomp.to_i
a = gets.split.map{ |i| i.to_i }
l = 0
r = 1
ans = 1
changes = -1
while l < n && r < n do
	if a[r] <= a[r - 1]
		if changes < 0
			if l == r - 1
				a[r-1] = a[r] - 1
				changes = l
			else
				a[r] = a[r-1] + 1
				changes = r
			end
		else
			l = changes + 1
			changes = -1
		end
	end
	ans = [ans, r - l + 1].max
	r += 1
end
puts ans

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

longest_so_far = 0
length = 1
hicat = 0
i = 0

while i < n - 1
    if a[i] >= a[i+1]
        lognest_so_far = length if length > longest_so_far
        length = length - hicat
        hicat = length
    end
    length = length + 1
    i = i + 1
end

lognest_so_far = length if length > longest_so_far

puts lognest_so_far

def derivative(ar)
    # Each cons returns an iterator over pairs of elements
    return ar.clone().unshift(0).each_cons(2).map{|x, y| y - x}
end

def loc(ar, v)
    return ar.each_index.select{|i| ar[i] <= v}
end

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

if (n <= 2)
    puts n
    exit
end

# Obtain the derivative of the input
der = derivative(a)

# Obtain the locations of negatives
negloc = loc(der,0).unshift(0).push(n)

seqlength = []

for i in 0..(negloc.length - 1) do
   j = negloc[i]

   if i == 0
        seqlength[i] = negloc[1]
   elsif i == negloc.length - 1
        seqlength[i] = negloc[i] - negloc[i-1] + 1
   elsif j+1 < a.length && a[j-1] + 1 < a[j+1]
        seqlength[i] = negloc[i+1] - negloc[i-1]
   else
        seqlength[i] = negloc[i] - negloc[i-1] + 1
   end

end

puts [seqlength.max,n].min

def derivative(ar)
    # Each cons returns an iterator over pairs of elements
    return ar.clone().unshift(0).each_cons(2).map{|x, y| y - x}
end

def loc(ar, v)
    return ar.each_index.select{|i| ar[i] <= v}
end

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

if (n <= 2)
    puts n
    exit
end

# Obtain the derivative of the input
der = derivative(a)

# Obtain the locations of negatives
negloc = loc(der,0).unshift(0).push(n)

seqlength = []

for i in 0..(negloc.length - 1) do
   j = negloc[i]

   if i == 0
        seqlength[i] = negloc[1]
   elsif i == negloc.length - 1
        seqlength[i] = negloc[i] - negloc[i-1] + 1
   elsif j+1 < a.length && a[j-1] + 1 < a[j+1]
        seqlength[i] = negloc[i+1] - negloc[i-1]
   else
        seqlength[i] = negloc[i] - negloc[i-1] + 1
   end

end

puts seqlength.max

def derivative(ar)
    # Each cons returns an iterator over pairs of elements
    return ar.clone().unshift(0).each_cons(2).map{|x, y| y - x}
end

def loc(ar, v)
    return ar.each_index.select{|i| ar[i] <= v}
end

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

# Obtain the derivative of the input
der = derivative(a)

# Obtain the locations of negatives
negloc = loc(der,0).unshift(0).push(n)

seqlength = []

for i in 0..(negloc.length - 1) do
   j = negloc[i]

   if i == 0
        seqlength[i] = negloc[1]
   elsif i == negloc.length - 1
        seqlength[i] = negloc[i] - negloc[i-1] + 1
   elsif j+1 < a.length && a[j-1] + 1 < a[j+1]
        seqlength[i] = negloc[i+1] - negloc[i-1]
   else
        seqlength[i] = negloc[i] - negloc[i-1] + 1
   end

end
puts seqlength.max

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

longest_so_far = 0
length = 1
hicat = 0
i = 0

while i < n - 1
    if a[i] >= a[i+1]
        longest_so_far = length if length > longest_so_far
        length = length - hicat
        hicat = length
    end
    length = length + 1
    i = i + 1
end

longest_so_far = length if length > longest_so_far

puts longest_so_far

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

puts n
puts a

longest_so_far = 0
length = 1
hicat = 0
i = 0

while i < n - 1
    if a[i] >= a[i+1]
        lognest_so_far = length if length > longest_so_far
        length = length - hicat
        hicat = length
    end
    length = length + 1
    i = i + 1
end

lognest_so_far = length if length > longest_so_far

puts lognest_so_far

def derivative(ar)
    # Each cons returns an iterator over pairs of elements
    return ar.clone().unshift(0).each_cons(2).map{|x, y| y - x}
end

def loc(ar, v)
    return ar.each_index.select{|i| ar[i] <= v}
end

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

# Obtain the derivative of the input
der = derivative(a)

# Obtain the locations of negatives
negloc = loc(der,0).unshift(0).push(n)

seqlength = []

for i in 0..(negloc.length - 1) do
   j = negloc[i]

   if i == 0
        seqlength[i] = negloc[1]
   elsif i == negloc.length - 1
        seqlength[i] = negloc[i] - negloc[i-1]
   elsif j+1 < a.length && a[j-1] + 1 < a[j+1]
        seqlength[i] = negloc[i+1] - negloc[i-1]
   else
        seqlength[i] = negloc[i] - negloc[i-1] + 1
   end

end

puts seqlength.max

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

longest_so_far = 0
length = 1
hicat = 0
i = 0

while i < n - 1
    if a[i] >= a[i+1]
        longest_so_far = length if length > longest_so_far
        length = length - hicat
        hicat = length
    end
    length = length + 1
    i = i + 1
end

lognest_so_far = length if length > longest_so_far

puts longest_so_far

def derivative(ar)
    # Each cons returns an iterator over pairs of elements
    return ar.clone().unshift(0).each_cons(2).map{|x, y| y - x}
end

def loc(ar, v)
    return ar.each_index.select{|i| ar[i] <= v}
end

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

if (n <= 2)
    return n
    exit
end

# Obtain the derivative of the input
der = derivative(a)

# Obtain the locations of negatives
negloc = loc(der,0).unshift(0).push(n)

seqlength = []

for i in 0..(negloc.length - 1) do
   print "Now at: "
   puts negloc[i]

   j = negloc[i]

   if i == 0
        seqlength[i] = negloc[1]
   elsif i == negloc.length - 1
        seqlength[i] = negloc[i] - negloc[i-1] + 1
   elsif j+1 < a.length && a[j-1] + 1 < a[j+1]
        seqlength[i] = negloc[i+1] - negloc[i-1]
   else
        seqlength[i] = negloc[i] - negloc[i-1] + 1
   end

end

puts seqlength.max

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

left, right = Array.new(n), Array.new(n)

left[0] = 1
(1..(n - 1)).each do |i|
  left[i] = a[i] > a[i - 1] ? left[i - 1] + 1 : 1
end

right[n - 1] = 1
(0..(n - 2)).to_a.reverse.each do |i|
  right[i] = a[i] < a[i + 1] ? right[i + 1] + 1 : 1
end

best = 1
(1..(n - 2)).each do |i|
  best = [best, left[i] + right[i] + 1].max if a[i - 1] + 1 < a[i + 1]
end

puts best

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

left, right = Array.new(n), Array.new(n)

left[0] = 1
(1..(n - 1)).each do |i|
  left[i] = a[i] > a[i - 1] ? left[i - 1] + 1 : 1
end

right[n - 1] = 1
(0..(n - 2)).to_a.reverse.each do |i|
  right[i] = a[i] < a[i + 1] ? right[i + 1] + 1 : 1
end

best = 1
(1..(n - 2)).each do |i|
  best = [best, left[i - 1] + right[i + 1] + 1].max if a[i - 1] + 1 < a[i + 1]
  best = [best, left[i] + 1, right[i] + 1].max
  # puts best
end

# puts left.join(" ")
# puts right.join(" ")
puts best

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

left, right = Array.new(n), Array.new(n)

best = 1
left[0] = 1
(1..(n - 1)).each do |i|
  left[i] = a[i] > a[i - 1] ? left[i - 1] + 1 : 1
  best = [best, left[i] + 1].max
end

right[n - 1] = 1
(0..(n - 2)).to_a.reverse.each do |i|
  right[i] = a[i] < a[i + 1] ? right[i + 1] + 1 : 1
  best = [best, right[i] + 1].max
end

(1..(n - 2)).each do |i|
  best = [best, left[i - 1] + right[i + 1] + 1].max if a[i - 1] + 1 < a[i + 1]
end

puts best

n = gets.to_i
a = gets.split(' ').map { |c| c.to_i }
leftright = Array.new(n, 0)
rightleft = Array.new(n, 0)
leftright[0] = rightleft[n - 1] = 1

(n-1).times do |i|
  pos = i + 1
  leftright[pos] = 1
  if a[pos] > a[pos - 1]
    leftright[pos] += 1
  end
end

(n-1).times do |i|
  pos = n - 2 - i
  rightleft[pos] = 1
  if a[pos] < a[pos + 1]
    rightleft[pos] += 1
  end
end

best = [1 + rightleft[1], 1 + leftright[n - 2]].max
a.each_with_index do |val, i|
  next if i == 0 || i == n - 1 || a[i - 1] + 2 > a[i + 1]
  best = [best, leftright[i - 1] + 1 + rightleft[i + 1]].max
end

puts best


Alice and Bob are playing a game on a matrix, consisting of $$$2$$$ rows and $$$m$$$ columns. The cell in the $$$i$$$-th row in the $$$j$$$-th column contains $$$a_{i, j}$$$ coins in it.Initially, both Alice and Bob are standing in a cell $$$(1, 1)$$$. They are going to perform a sequence of moves to reach a cell $$$(2, m)$$$.The possible moves are:   Move right — from some cell $$$(x, y)$$$ to $$$(x, y + 1)$$$;  Move down — from some cell $$$(x, y)$$$ to $$$(x + 1, y)$$$. First, Alice makes all her moves until she reaches $$$(2, m)$$$. She collects the coins in all cells she visit (including the starting cell).When Alice finishes, Bob starts his journey. He also performs the moves to reach $$$(2, m)$$$ and collects the coins in all cells that he visited, but Alice didn't.The score of the game is the total number of coins Bob collects.Alice wants to minimize the score. Bob wants to maximize the score. What will the score of the game be if both players play optimally?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of the testcase contains a single integer $$$m$$$ ($$$1 \le m \le 10^5$$$) — the number of columns of the matrix. The $$$i$$$-th of the next $$$2$$$ lines contain $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^4$$$) — the number of coins in the cell in the $$$i$$$-th row in the $$$j$$$-th column of the matrix. The sum of $$$m$$$ over all testcases doesn't exceed $$$10^5$$$.

For each testcase print a single integer — the score of the game if both players play optimally.

NoteThe paths for the testcases are shown on the following pictures. Alice's path is depicted in red and Bob's path is depicted in blue.

MOD = 10 ** 9 + 7
def gs; gets.chomp; end
def gi; gets.to_i; end
def gli; gets.split.map(&:to_i); end
def cyesno(x); puts x ? :Yes : :No; end
def uyesno(x); puts x ? :YES : :NO; end
def array_to_hash_by_count(c); Hash.new(0).tap { |x| c.each { |z| x[z] += 1 } }; end

def solve
  n = gi
  a = gli
  b = gli
  a_s = a.sum
  b_s = 0
  mn = [a_s, b.sum].max
  for i in (0..n-1)
    a_s -= a[i]
    tmp = [a_s, b_s].max
    mn = tmp if tmp < mn
    b_s += b[i]
  end
  puts mn
end

def main
  gi.times { solve }
end

main

#!/usr/bin/env ruby

def arline
  gets.chomp.split.map(&:to_i)
end

def pfr(ar)
  res = [0]
  ar.each do |x| res.append(res[-1] + x) end
  res
end

class Grid
  def initialize(ar)
    @pfr = ar.map{|x| pfr(x)}
    @n = ar[0].length
  end
  def score(x)
    [@pfr[1][x-1], @pfr[0][@n] - @pfr[0][x]].max
  end
end

gets.chomp.to_i.times do
  n = gets.chomp.to_i
  a = (1..2).map{arline}
  g = Grid.new(a)
  puts (1..n).map{|x| g.score(x) }.min
end

MOD = 10 ** 9 + 7
def gs; gets.chomp; end
def gi; gets.to_i; end
def gli; gets.split.map(&:to_i); end
def cyesno(x); puts x ? :Yes : :No; end
def uyesno(x); puts x ? :YES : :NO; end
def array_to_hash_by_count(c); Hash.new(0).tap { |x| c.each { |z| x[z] += 1 } }; end

def solve
  n = gi
  a = gli
  b = gli
  a_s = a.sum
  b_s = b.sum
  mn = [a_s, b_s].max
  b_s = 0
  for i in (0..n-1)
    a_s -= a[i]
    b_s += b[i]
    tmp = [a_s, b_s].max
    mn = tmp if mn > tmp
  end
  puts mn - b[-1]
end

def main
  gi.times { solve }
end

main