Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met:  the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.

The first line contains a single integer n (1 ≤ n ≤ 100 000) — the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≤ xi ≤ 100 000) — the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.

In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn — the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.

NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.

n = gets.to_i
x = gets.split.map(&:to_i)
v = x[0]
c = [0,0,0,0,0]
n.times do |i|
  c[x[i]-v+2] += 1
end
maxidx = minidx = 2
5.times do |i|
  if c[i] != 0
    minidx = i if i < minidx
    maxidx = i if i > maxidx
  end
end
diff = maxidx - minidx
if diff != 2
  p n
  puts x.join(" ")
else
  num = []
  cnt = [c[minidx],c[minidx+1],c[minidx+2]]
  a = [cnt[0],cnt[2]].min * 4 #incrase cnt[1]
  b = cnt[1]/2 * 4 #decrease cnt[1]
  if a > b
    k = [cnt[0],cnt[2]].min
    num[0] = cnt[0]-k
    num[2] = cnt[2]-k
    num[1] = cnt[1] + k*2
    ans = num[0] + num[1] +num[2] - k*2
  else
    k = cnt[1]/2
    num[0] = cnt[0] + k
    num[1] = cnt[1] - k*2
    num[2] = cnt[2] + k
    ans = num[0] + num[1] +num[2] - k*2
  end
  p ans
  res = []
  3.times do |i|
    res += [v+minidx-2+i] * num[i] if num[i] > 0
  end
  puts res.join(" ")
end
#p c
#p cnt
#p num

n = gets.chomp.to_i
arr = gets.chomp.split(" ").map {|e| e.to_i}
mi = arr.min
ma = arr.max

out = n
mac = 0
mic = 0
if ma - mi > 1
	arr.each do |e|
		if e == mi
			mic +=1
		elsif e == ma
			mac +=1
		end
	end
end
mmc = (n - mic - mac)

if mic > mac
	mic = mac
else
	mac = mic
end
if mmc % 2 != 0
	mmc = mmc - 1
end
if mmc <= (2*mic)
	out -= mic*2
	arr = arr.map do |e|
		if e == mi && mic > 0
			mic -= 1
			e + 1
		elsif e == ma && mac > 0
			mac -= 1
			e-1
		else
			e
		end
	end
elsif (ma - mi) > 1
	out -= mmc
	mm = mi + 1
	i = 1
	arr = arr.map do |e|
		if e == mm && mmc > 0
			i = -i
			mmc -= 1
			e + i
		else
			e
		end
	end
end
puts out
puts arr.join(" ")

n = gets.to_i
x = gets.split.map(&:to_i)
v = x[0]
c = [0,0,0,0,0]
n.times do |i|
  c[x[i]-v+2] += 1
end
maxidx = minidx = 2
5.times do |i|
  if c[i] != 0
    minidx = i if i < minidx
    maxidx = i if i > maxidx
  end
end
diff = maxidx - minidx
if diff != 2
  p 0
  puts x.join(" ")
else
  num = []
  cnt = [c[minidx],c[minidx+1],c[minidx+2]]
  a = [cnt[0],cnt[2]].min * 4 #incrase cnt[1]
  b = cnt[1]/2 * 4 #decrease cnt[1]
  if a > b
    k = [cnt[0],cnt[2]].min
    num[0] = cnt[0]-k
    num[2] = cnt[2]-k
    num[1] = cnt[1] + k*2
    ans = num[0] + num[1] +num[2] - k*2
  else
    k = cnt[1]/2
    num[0] = cnt[0] + k
    num[1] = cnt[1] - k*2
    num[2] = cnt[2] + k
    ans = num[0] + num[1] +num[2] - k*2
  end
  p ans
  m = num[2] - 1 < 0 ? 0 : num[2] - 1
  print "#{v+minidx-2} " * num[0] +  "#{v+minidx-1} " * num[1] +  "#{v+minidx} " * m
  print "#{v+minidx}" if num[2] > 0
end
#p c
#p cnt
#p num

n = gets.to_i
x = gets.split.map(&:to_i)
v = x[0]
c = [0,0,0,0,0]
n.times do |i|
  c[x[i]-v+2] += 1
end
maxidx = minidx = 2
5.times do |i|
  if c[i] != 0
    minidx = i if i < minidx
    maxidx = i if i > maxidx
  end
end
diff = maxidx - minidx
if diff != 2
  p 0
  puts x.join(" ")
else
  num = []
  cnt = [c[minidx],c[minidx+1],c[minidx+2]]
  a = [cnt[0],cnt[2]].min * 4 #incrase cnt[1]
  b = cnt[1]/2 * 4 #decrease cnt[1]
  if a > b
    k = [cnt[0],cnt[2]].min
    num[0] = cnt[0]-k
    num[2] = cnt[2]-k
    num[1] = cnt[1] + k*2
    ans = num[0] + num[1] +num[2] - k*2
  else
    k = cnt[1]/2
    num[0] = cnt[0] + k
    num[1] = cnt[1] - k*2
    num[2] = cnt[2] + k
    ans = num[0] + num[1] +num[2] - k*2
  end
  p ans
  res = []
  3.times do |i|
    res += [v+minidx-2+i] * num[i] if num[i] > 0
  end
  puts res.join(" ")
end
#p c
#p cnt
#p num

n = gets.chomp.to_i
arr = gets.chomp.split(" ").map {|e| e.to_i}
mi = arr.min
ma = arr.max

out = n
mac = 0
mic = 0
if ma - mi > 1
	arr.each do |e|
		if e == mi
			mic +=1
		elsif e == ma
			mac +=1
		end
	end
end
if mic > mac
	mic = mac
else
	mac = mic
end
mic = mic
out -= mic*2
i = 0
arr = arr.map do |e|
	if e == mi && mic > 0
		mic -= 1
		e + 1
	elsif e == ma && mac > 0
		mac -= 1
		e-1
	else
		e
	end
end
puts out
puts arr.join(" ")


Colossal! — exclaimed Hawk-nose. — A programmer! That's exactly what we are looking for.Arkadi and Boris Strugatsky. Monday starts on SaturdayReading the book "Equations of Mathematical Magic" Roman Oira-Oira and Cristobal Junta found an interesting equation: $$$a - (a \oplus x) - x = 0$$$ for some given $$$a$$$, where $$$\oplus$$$ stands for a bitwise exclusive or (XOR) of two integers (this operation is denoted as ^ or xor in many modern programming languages). Oira-Oira quickly found some $$$x$$$, which is the solution of the equation, but Cristobal Junta decided that Oira-Oira's result is not interesting enough, so he asked his colleague how many non-negative solutions of this equation exist. This task turned out to be too difficult for Oira-Oira, so he asks you to help.

Each test contains several possible values of $$$a$$$ and your task is to find the number of equation's solution for each of them. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of these values. The following $$$t$$$ lines contain the values of parameter $$$a$$$, each value is an integer from $$$0$$$ to $$$2^{30} - 1$$$ inclusive.

For each value of $$$a$$$ print exactly one integer — the number of non-negative solutions of the equation for the given value of the parameter. Print answers in the same order as values of $$$a$$$ appear in the input. One can show that the number of solutions is always finite.

NoteLet's define the bitwise exclusive OR (XOR) operation. Given two integers $$$x$$$ and $$$y$$$, consider their binary representations (possibly with leading zeroes): $$$x_k \dots x_2 x_1 x_0$$$ and $$$y_k \dots y_2 y_1 y_0$$$. Here, $$$x_i$$$ is the $$$i$$$-th bit of the number $$$x$$$ and $$$y_i$$$ is the $$$i$$$-th bit of the number $$$y$$$. Let $$$r = x \oplus y$$$ be the result of the XOR operation of $$$x$$$ and $$$y$$$. Then $$$r$$$ is defined as $$$r_k \dots r_2 r_1 r_0$$$ where:$$$$$$ r_i = \left\{ \begin{aligned} 1, ~ \text{if} ~ x_i \ne y_i \\ 0, ~ \text{if} ~ x_i = y_i \end{aligned} \right. $$$$$$For the first value of the parameter, only $$$x = 0$$$ is a solution of the equation.For the second value of the parameter, solutions are $$$x = 0$$$ and $$$x = 2$$$.

gets.to_i.times do
  p 2**gets.to_i.to_s(2).chars.select { |i| i == ?1 } .size
end

t = gets.to_i
t.times do
  a = gets.to_i
  puts 2**a.to_s(2).count('1')
end

gets.to_i.times do
  n = gets.to_i.to_s(2).chars.select { |i| i == ?1 } .size
  puts 2**n
end


You are given a list of $$$n$$$ integers. You can perform the following operation: you choose an element $$$x$$$ from the list, erase $$$x$$$ from the list, and subtract the value of $$$x$$$ from all the remaining elements. Thus, in one operation, the length of the list is decreased by exactly $$$1$$$.Given an integer $$$k$$$ ($$$k>0$$$), find if there is some sequence of $$$n-1$$$ operations such that, after applying the operations, the only remaining element of the list is equal to $$$k$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq n \leq 2\cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$), the number of integers in the list, and the target value, respectively. The second line of each test case contains the $$$n$$$ integers of the list $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases is not greater that $$$2 \cdot 10^5$$$.

For each test case, print YES if you can achieve $$$k$$$ with a sequence of $$$n-1$$$ operations. Otherwise, print NO. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).

NoteIn the first example we have the list $$$\{4, 2, 2, 7\}$$$, and we have the target $$$k = 5$$$. One way to achieve it is the following: first we choose the third element, obtaining the list $$$\{2, 0, 5\}$$$. Next we choose the first element, obtaining the list $$$\{-2, 3\}$$$. Finally, we choose the first element, obtaining the list $$$\{5\}$$$.

require "set"

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  as = gets.split.map(&:to_i).to_set
  puts as.any? { |a| as.include?(a - k) } ? "YES" : "NO"
end


On Bertown's main street n trees are growing, the tree number i has the height of ai meters (1 ≤ i ≤ n). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the n-th one) should be equal to each other, the heights of the 2-nd and the (n - 1)-th tree must also be equal to each other, at that the height of the 2-nd tree should be larger than the height of the first tree by 1, and so on. In other words, the heights of the trees, standing at equal distance from the edge (of one end of the sequence) must be equal to each other, and with the increasing of the distance from the edge by 1 the tree height must also increase by 1. For example, the sequences "2 3 4 5 5 4 3 2" and "1 2 3 2 1" are beautiful, and '1 3 3 1" and "1 2 3 1" are not. Changing the height of a tree is a very expensive operation, using advanced technologies invented by Berland scientists. In one operation you can choose any tree and change its height to any number, either increase or decrease. Note that even after the change the height should remain a positive integer, i. e, it can't be less than or equal to zero. Identify the smallest number of changes of the trees' height needed for the sequence of their heights to become beautiful.

The first line contains integer n (1 ≤ n ≤ 105) which is the number of trees. The second line contains integers ai (1 ≤ ai ≤ 105) which are the heights of the trees.

Print a single number which is the minimal number of trees whose heights will have to be changed for the sequence to become beautiful.

n = gets.to_i
h = Hash.new(0)
gets.split.map(&:to_i).each_with_index do |i, j|
	k = i - [j, n - 1 - j].min
	h[k] += 1 if k > 0
end
p n - h.max{|a, b| a[1] <=> b[1]}[1]

N  = gets.to_i
a = gets.split(/\s+/).map {|i| i.to_i}
d = {}
d.default = 0
i, j = 0, N - 1
while i <= j
    if a[i] - i > 0
        d[a[i] - i] += 1
    end
    if i != j && a[j] - i > 0
        d[a[j] - i] += 1
    end
    i += 1
    j -= 1
end

puts N - [1, d.values.max].max

N  = gets.to_i
a = gets.split(/\s+/).map {|i| i.to_i}
d = Array.new(100001, 0)
i, j = 0, N - 1
while i <= j
    d[a[i] - i] += 1 if a[i] - i > 0
    d[a[j] - i] += 1 if i != j && a[j] - i > 0
    i += 1
    j -= 1
end
puts N - [1, d.max].max

N = gets.to_i
a = gets.split(/\s+/).map {|i| i.to_i}
d = Hash.new(0)
i, j = 0, N - 1
while i <= j
    d[a[i] - i] += 1 if a[i] - i > 0
    d[a[j] - i] += 1 if i != j && a[j] - i > 0
    i += 1
    j -= 1
end
puts N - [1, d.values.max].max

n = gets.to_i
h = Hash.new(0)
gets.split.map(&:to_i).each_with_index do |i, j|
	h[i - [j, n - 1 - j].min] += 1
end
p n - h.max{|a, b| a[1] <=> b[1]}[1]


Профиль горного хребта схематично задан в виде прямоугольной таблицы из символов «.» (пустое пространство) и «*» (часть горы). Каждый столбец таблицы содержит хотя бы одну «звёздочку». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*».  ....................*..*.......*.**.......*.**..*...**.***********   Пример изображения горного хребта.  Маршрут туриста проходит через весь горный хребет слева направо. Каждый день турист перемещается вправо — в соседний столбец в схематичном изображении. Конечно, каждый раз он поднимается (или опускается) в самую верхнюю точку горы, которая находится в соответствующем столбце.Считая, что изначально турист находится в самой верхней точке в первом столбце, а закончит свой маршрут в самой верхней точке в последнем столбце, найдите две величины:  наибольший подъём за день (равен 0, если в профиле горного хребта нет ни одного подъёма),  наибольший спуск за день (равен 0, если в профиле горного хребта нет ни одного спуска).

В первой строке входных данных записаны два целых числа n и m (1 ≤ n, m ≤ 100) — количество строк и столбцов в схематичном изображении соответственно. Далее следуют n строк по m символов в каждой — схематичное изображение горного хребта. Каждый символ схематичного изображения — это либо «.», либо «*». Каждый столбец матрицы содержит хотя бы один символ «*». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*».

Выведите через пробел два целых числа:   величину наибольшего подъёма за день (или 0, если в профиле горного хребта нет ни одного подъёма),  величину наибольшего спуска за день (или 0, если в профиле горного хребта нет ни одного спуска).

ПримечаниеВ первом тестовом примере высоты гор равны: 3, 4, 1, 1, 2, 1, 1, 1, 2, 5, 1. Наибольший подъем равен 3 и находится между горой номер 9 (её высота равна 2) и горой номер 10 (её высота равна 5). Наибольший спуск равен 4 и находится между горой номер 10 (её высота равна 5) и горой номер 11 (её высота равна 1).Во втором тестовом примере высоты гор равны: 1, 2, 3, 4, 5. Наибольший подъём равен 1 и находится, например, между горой номер 2 (ее высота равна 2) и горой номер 3 (её высота равна 3). Так как в данном горном хребте нет спусков, то величина наибольшего спуска равна 0.В третьем тестовом примере высоты гор равны: 1, 7, 5, 3, 4, 2, 3. Наибольший подъём равен 6 и находится между горой номер 1 (её высота равна 1) и горой номер 2 (её высота равна 7). Наибольший спуск равен 2 и находится между горой номер 2 (её высота равна 7) и горой номер 3 (её высота равна 5). Такой же спуск находится между горой номер 5 (её высота равна 4) и горой номер 6 (её высота равна 2).

#!/usr/bin/env ruby

h, w = gets.split.map(&:to_i)
lines = [[]]
for i in 0..h-1
  lines[i] = gets.chomp.chars
end
lines = lines.transpose

max = 0
min = 0
for i in 1..w-1
  currenthei = lines[i].count('*')
  oldhei = lines[i-1].count('*')
  if currenthei - oldhei > max then max = currenthei - oldhei
  elsif oldhei - currenthei > min then min = oldhei - currenthei end
end

printf("%d %d", max, min)
puts


Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese).You are given an integer $$$n$$$. You need to find two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \le l < r \le 10^{18}$$$ and $$$l + (l + 1) + \ldots + (r - 1) + r = n$$$.

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 a single integer $$$n$$$ ($$$1 \le n \le 10^{18}$$$).

For each test case, print the two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \le l < r \le 10^{18}$$$ and $$$l + (l + 1) + \ldots + (r - 1) + r = n$$$.  It can be proven that an answer always exists. If there are multiple answers, print any.

def i(x)
	x.to_i
end

t = gets
for k in 1..i(t)
	n = gets
	puts "#{-i(n) + 1} #{n}"
end

def i(x)
	x.to_i
end

t = gets
for k in 1..i(t)
	n = gets
	if i(n) == 1
		puts "0 1"
		next
	end
	puts "-#{i(n) - 1} #{n}"
end

info = gets.chomp.to_i
info.times do
  input  = gets.chomp.to_i
  if input.positive?
    print -(input-1), ' ', input
    puts
  elsif input.negative?
    print input, ' ', -(input)-1
    puts
  else
    print 0, ' ', 0
    puts
  end
end

def i(x)
	x.to_i
end

t = gets
for k in 1..i(t)
	n = gets
	if n == 1
		puts "0 1"
		next
	end
	puts "-#{i(n) - 1} #{n}"
end


A Pythagorean triple is a triple of integer numbers $$$(a, b, c)$$$ such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to $$$a$$$, $$$b$$$ and $$$c$$$, respectively. An example of the Pythagorean triple is $$$(3, 4, 5)$$$.Vasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: $$$c = a^2 - b$$$.Obviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple $$$(3, 4, 5)$$$: $$$5 = 3^2 - 4$$$, so, according to Vasya's formula, it is a Pythagorean triple.When Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers $$$(a, b, c)$$$ with $$$1 \le a \le b \le c \le n$$$ such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, print one integer — the number of triples of integers $$$(a, b, c)$$$ with $$$1 \le a \le b \le c \le n$$$ such that they are Pythagorean according both to the real definition and to the formula Vasya came up with.

NoteThe only Pythagorean triple satisfying $$$c = a^2 - b$$$ with $$$1 \le a \le b \le c \le 9$$$ is $$$(3, 4, 5)$$$; that's why the answer for $$$n = 3$$$ is $$$0$$$, and the answer for $$$n = 6$$$ (and for $$$n = 9$$$) is $$$1$$$.

a=[]
i=1
k=1
while k<=8000000000
  k=i*i
  a << k/2+1
  i+=2
end
gets.to_i.times do
  n=gets.to_i
  l=0
  r=44722
  while r-l>1
    m=(l+r)/2
    if a[m]<=n
      l=m
    else
      r=m
    end
  end
  puts l
end

a=[]
i=1
k=1
while k<=1000000000
  k=i*i
  a << k/2+1
  i+=2
end
gets.to_i.times do
  n=gets.to_i
  l=0
  r=15812
  while r-l>1
    m=(l+r)/2
    if a[m]<=n
      l=m
    else
      r=m
    end
  end
  puts l
end


One day n students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people.We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student A is an archenemy to student B, then student B is an archenemy to student A.The students want to split so as no two archenemies were in one team. If splitting in the required manner is impossible, some students will have to sit on the bench.Determine the minimum number of students you will have to send to the bench in order to form the two teams in the described manner and begin the game at last.

The first line contains two integers n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of students and the number of pairs of archenemies correspondingly. Next m lines describe enmity between students. Each enmity is described as two numbers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the indexes of the students who are enemies to each other. Each enmity occurs in the list exactly once. It is guaranteed that each student has no more than two archenemies. You can consider the students indexed in some manner with distinct integers from 1 to n.

Print a single integer — the minimum number of students you will have to send to the bench in order to start the game.

n, m = STDIN.readline.split.map {|s| s.to_i }
enemies = {}
(1..n).each {|i| enemies[i] = [] }
m.times do
	a, b = STDIN.readline.split.map {|s| s.to_i }
	enemies[a].push(b)
	enemies[b].push(a)
end
value_side = {}
sides = [[], [], []]
def add(i, target, value_side, sides, enemies)
	okay = true
	value_side[i] = target
	sides[target].push(i)
	next_target = (target == 0 ? 1 : 0)
	enemies[i].each do |j|
		if not value_side[j]
			add(j, next_target, value_side, sides, enemies)
		elsif value_side[j] == target
			sides[target].delete i
			value_side[i] = 2
			sides[2].push(i)
		end
	end
end
(1..n).each do |i|
	next if value_side[i]
	target = (sides[0].length <= sides[1].length ? 0 : 1)
	add(i, target, value_side, sides, enemies)
end
puts sides[2].length + (sides[0].length + sides[1].length)%2

#I could just assign 0 to some graph[i][j] instead of using path
def DFS(v,p)
	#puts v+1
	p.push(v)
	$colour[v] = :grey
	$n.times do |i|
		if $graph[v][i] == 1
			if $colour[i] == :white
				DFS(i,p)
				#p = Array.new
			elsif $colour[i] == :grey
				unless p[p.length-2] == i
					if $cycle == :void
						$cycle = true
						if p.length % 2 == 1
							$students += 1 #p.length - 2
							#puts "ALALAH!: " + v.to_s + ", " + i.to_s
						end
					end
					break
				end
			end
		end
	end
	$colour[v] = :black
	if $cycle == :void
		$cycle = :false
	end
end

#input = File.open('input.txt','r')
$n, m = gets.split#input.
$n = $n.to_i
m = m.to_i
$graph = Array.new($n)#,Array.new(n,0))
$n.times do |i|
	$graph[i] = Array.new($n,0)
end
m.times do |i|
	a, b = gets.split#input.
	#print(a,' ',b,"\n")
	#puts graph[a.to_i-1][b.to_i-1]
	$graph[a.to_i-1][b.to_i-1] = $graph[b.to_i-1][a.to_i-1] = 1
	#puts graph[a.to_i-1][b.to_i-1]
end
# $graph.each do |i|
	# i.each do |j|
		# print j
		# print ' '
	# end
	# puts
# end
$colour = Array.new($n,:white)
$cycle = :void
$students = 0
$n.times do |i|
	if $colour[i] == :white
		path = Array.new
		DFS(i,path)
		$cycle = :void
	end
end
# if $cycle
	# puts "No"
# else
	# puts "Yes"
# end
if ($n - $students) % 2 == 1
	$students += 1
end
puts $students
#assign a value to a variable only if that variable isn't already set:
#@variable ||= "default value"

#x, y = y, x will interchange the values of x and y

#names2 = %w{  ann richard william susan pat }

#puts "Enrollments will now Stop" if participants > 2500

#Negative index values count from the end of the array

#I could just assign 0 to some graph[i][j] instead of using path
def DFS(v,p)
	#puts v+1
	p.push(v)
	$colour[v] = :grey
	$n.times do |i|
		if $graph[v][i] == 1
			if $colour[i] == :white
				DFS(i,p)
				#p = Array.new
			elsif $colour[i] == :grey
				unless p[p.length-2] == i
					if $cycle == :void
						$cycle = true
						if p.length % 2 == 1
							$students += 1 #p.length - 2
							#puts "ALALAH!: " + v.to_s + ", " + i.to_s
						end
					end
					break
				end
			end
		end
	end
	$colour[v] = :black
	if $cycle == :void
		$cycle = :false
	end
end

#input = File.open('input.txt','r')
$n, m = gets.split#input.
$n = $n.to_i
m = m.to_i
$graph = Array.new($n)#,Array.new(n,0))
$n.times do |i|
	$graph[i] = Array.new($n,0)
end
m.times do |i|
	a, b = gets.split#input.
	#print(a,' ',b,"\n")
	#puts graph[a.to_i-1][b.to_i-1]
	$graph[a.to_i-1][b.to_i-1] = $graph[b.to_i-1][a.to_i-1] = 1
	#puts graph[a.to_i-1][b.to_i-1]
end
# $graph.each do |i|
	# i.each do |j|
		# print j
		# print ' '
	# end
	# puts
# end
$colour = Array.new($n,:white)
$cycle = :void
$students = 0
$n.times do |i|
	if $colour[i] == :white
		path = Array.new
		DFS(i,path)
	end
end
# if $cycle
	# puts "No"
# else
	# puts "Yes"
# end
if ($n - $students) % 2 == 1
	$students += 1
end
puts $students
#assign a value to a variable only if that variable isn't already set:
#@variable ||= "default value"

#x, y = y, x will interchange the values of x and y

#names2 = %w{  ann richard william susan pat }

#puts "Enrollments will now Stop" if participants > 2500

#Negative index values count from the end of the array

#I could just assign 0 to some graph[i][j] instead of using path
def DFS(v,p)
	#puts v+1
	p.push(v)
	$colour[v] = :grey
	$n.times do |i|
		if $graph[v][i] == 1
			if $colour[i] == :white
				DFS(i,p)
			elsif $colour[i] == :grey
				unless p[p.length-2] == i
					$cycle = true
					if p.length % 2 == 1
						$students += 1 #p.length - 2
					end
					break
				end
			end
		end
	end
	$colour[v] = :black
end

#input = File.open('input.txt','r')
$n, m = gets.split#input.
$n = $n.to_i
m = m.to_i
$graph = Array.new($n)#,Array.new(n,0))
$n.times do |i|
	$graph[i] = Array.new($n,0)
end
m.times do |i|
	a, b = gets.split#input.
	#print(a,' ',b,"\n")
	#puts graph[a.to_i-1][b.to_i-1]
	$graph[a.to_i-1][b.to_i-1] = $graph[b.to_i-1][a.to_i-1] = 1
	#puts graph[a.to_i-1][b.to_i-1]
end
# $graph.each do |i|
	# i.each do |j|
		# print j
		# print ' '
	# end
	# puts
# end
$colour = Array.new($n,:white)
$cycle = false
$students = 0
$n.times do |i|
	if $colour[i] == :white
		path = Array.new
		DFS(i,path)
	end
end
# if $cycle
	# puts "No"
# else
	# puts "Yes"
# end
if ($n - $students) % 2 == 1
	$students += 1
end
puts $students
#assign a value to a variable only if that variable isn't already set:
#@variable ||= "default value"

#x, y = y, x will interchange the values of x and y

#names2 = %w{  ann richard william susan pat }

#puts "Enrollments will now Stop" if participants > 2500

#Negative index values count from the end of the array

#I could just assign 0 to some graph[i][j] instead of using path
def DFS(v,p)
	#puts v+1
	p.push(v)
	$colour[v] = :grey
	$n.times do |i|
		if $graph[v][i] == 1
			if $colour[i] == :white
				DFS(i,p)
			elsif $colour[i] == :grey
				unless p[p.length-2] == i
					$cycle = true
					$students += p.length - 2
					break
				end
			end
		end
	end
	$colour[v] = :black
end

#input = File.open('input.txt','r')
$n, m = gets.split#input.
$n = $n.to_i
m = m.to_i
$graph = Array.new($n)#,Array.new(n,0))
$n.times do |i|
	$graph[i] = Array.new($n,0)
end
m.times do |i|
	a, b = gets.split#input.
	#print(a,' ',b,"\n")
	#puts graph[a.to_i-1][b.to_i-1]
	$graph[a.to_i-1][b.to_i-1] = $graph[b.to_i-1][a.to_i-1] = 1
	#puts graph[a.to_i-1][b.to_i-1]
end
# $graph.each do |i|
	# i.each do |j|
		# print j
		# print ' '
	# end
	# puts
# end
$colour = Array.new($n,:white)
$cycle = false
$students = 0
$n.times do |i|
	if $colour[i] == :white
		path = Array.new
		DFS(i,path)
	end
end
# if $cycle
	# puts "No"
# else
	# puts "Yes"
# end
if ($n - $students) % 2 == 1
	$students += 1
end
puts $students
#assign a value to a variable only if that variable isn't already set:
#@variable ||= "default value"

#x, y = y, x will interchange the values of x and y

#names2 = %w{  ann richard william susan pat }

#puts "Enrollments will now Stop" if participants > 2500

#Negative index values count from the end of the array

#I could just assign 0 to some graph[i][j] instead of using path
def DFS(v,p)
	#puts v+1
	p.push(v)
	$colour[v] = :grey
	$n.times do |i|
		if $graph[v][i] == 1
			if $colour[i] == :white
				DFS(i,p)
			elsif $colour[i] == :grey
				unless p[p.length-2] == i
					$cycle = true
					$students += p.length - 2
					break
				end
			end
		end
	end
	$colour[v] = :black
end

#input = File.open('input.txt','r')
$n, m = gets.split#input.
$n = $n.to_i
m = m.to_i
$graph = Array.new($n)#,Array.new(n,0))
$n.times do |i|
	$graph[i] = Array.new($n,0)
end
m.times do |i|
	a, b = gets.split#input.
	#print(a,' ',b,"\n")
	#puts graph[a.to_i-1][b.to_i-1]
	$graph[a.to_i-1][b.to_i-1] = $graph[b.to_i-1][a.to_i-1] = 1
	#puts graph[a.to_i-1][b.to_i-1]
end
# $graph.each do |i|
	# i.each do |j|
		# print j
		# print ' '
	# end
	# puts
# end
$colour = Array.new($n,:white)
$cycle = false
$students = 0
$n.times do |i|
	if $colour[i] == :white
		path = Array.new
		DFS(i,path)
	end
end
# if $cycle
	# puts "No"
# else
	# puts "Yes"
# end
puts $students
#assign a value to a variable only if that variable isn't already set:
#@variable ||= "default value"

#x, y = y, x will interchange the values of x and y

#names2 = %w{  ann richard william susan pat }

#puts "Enrollments will now Stop" if participants > 2500

#Negative index values count from the end of the array

#I could just assign 0 to some graph[i][j] instead of using path
def DFS(v,p)
	#puts v+1
	p.push(v)
	$colour[v] = :grey
	$n.times do |i|
		if $graph[v][i] == 1
			if $colour[i] == :white
				DFS(i,p)
			elsif $colour[i] == :grey
				unless p[p.length-2] == i
					$cycle = true
					$students += p.length - 2
					break
				end
			end
		end
	end
	$colour[v] = :black
end

#input = File.open('input.txt','r')
$n, m = gets.split#input.
$n = $n.to_i
m = m.to_i
$graph = Array.new($n)#,Array.new(n,0))
$n.times do |i|
	$graph[i] = Array.new($n,0)
end
m.times do |i|
	a, b = gets.split#input.
	#print(a,' ',b,"\n")
	#puts graph[a.to_i-1][b.to_i-1]
	$graph[a.to_i-1][b.to_i-1] = $graph[b.to_i-1][a.to_i-1] = 1
	#puts graph[a.to_i-1][b.to_i-1]
end
# $graph.each do |i|
	# i.each do |j|
		# print j
		# print ' '
	# end
	# puts
# end
$colour = Array.new($n,:white)
$cycle = false
$students = 0
$n.times do |i|
	if $colour[i] == :white
		path = Array.new
		DFS(i,path)
	end
end
# if $cycle
	# puts "No"
# else
	# puts "Yes"
# end
if $students % 2 == 1
	$students -= 1
end
puts $students
#assign a value to a variable only if that variable isn't already set:
#@variable ||= "default value"

#x, y = y, x will interchange the values of x and y

#names2 = %w{  ann richard william susan pat }

#puts "Enrollments will now Stop" if participants > 2500

#Negative index values count from the end of the array


Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:Given two binary numbers $$$a$$$ and $$$b$$$ of length $$$n$$$. How many different ways of swapping two digits in $$$a$$$ (only in $$$a$$$, not $$$b$$$) so that bitwise OR of these two numbers will be changed? In other words, let $$$c$$$ be the bitwise OR of $$$a$$$ and $$$b$$$, you need to find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will not be equal to $$$c$$$.Note that binary numbers can contain leading zeros so that length of each number is exactly $$$n$$$.Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $$$01010_2$$$ OR $$$10011_2$$$ = $$$11011_2$$$.Well, to your surprise, you are not Rudolf, and you don't need to help him$$$\ldots$$$ You are the security staff! Please find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will be changed.

The first line contains one integer $$$n$$$ ($$$2\leq n\leq 10^5$$$) — the number of bits in each number. The second line contains a binary number $$$a$$$ of length $$$n$$$. The third line contains a binary number $$$b$$$ of length $$$n$$$.

Print the number of ways to swap two bits in $$$a$$$ so that bitwise OR will be changed.

N = gets.to_i
A = gets.chomp
B = gets.chomp

n00, n01, n10, n11 = 0, 0, 0, 0

N.times do |i|
    if A[i] == '0'
        if B[i] == '0'
            n00 += 1
        else
            n01 += 1
        end
    else
        if B[i] == '0'
            n10 += 1
        else
            n11 += 1
        end
    end
end

puts (n00+n01) * (n10+n11) - n01*n11

n = gets.to_i
a = gets.chomp
b = gets.chomp

azerocount = 0
bzerocount = 0

b.each_char.with_index do |c,i|
  if c=="0"
    if a[i] == "0"
      azerocount+=1
    end
    bzerocount += 1
  end
end

aone = a.count('1')

#p azerocount
#p bzerocount
#p aone
puts azerocount*aone+(bzerocount-azerocount)*(n-aone-azerocount)


The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$).

For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...".

NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG".

S = "RGB"
gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  s = gets
  a = []
  (0...n - k + 1).each do |i|
    (0...3).each do |j|
      cur = 0
      (0...k).each do |shift|
        cur += 1 if s[i+shift] != S[(j + shift) % 3]
      end
      a << cur
    end
  end
  puts a.min
end

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

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end
#def bs(ar,eq,n) en=(eq==1 ? :>= : :>); ar.bsearch_index{|x|x.send(en,n)} end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
q = gi
ans = []
base = ["0","1","2"]
q.times do |i|
  n, k = gsmi
  # RGBは012に変換
  s = gs.gsub(/R/,"0").gsub(/G/,"1").gsub(/B/,"2")
  last =
    if s.length%3==1
      "0"
    elsif s.length%3==2
      "01"
    else
      ""
    end
  ex = base.join * (s.length/3) + last

  #RGBRGB...との差分(距離)をとる
  diff = []
  ex.chars.each.with_index do |str,j|
    d = str.to_i - s[j].to_i
    d = d+3 if d<0
    diff << d
  end
  #debug 'diff', diff.to_s
  # 0,1,2のうちいずれかがk回続けばいい
  a0 = diff[0..(k-1)]
  h=Hash.new(0)
  a0.each{|j|h[j]+=1}
  ar = h.to_a
  #puts ar.to_s
  max = ar.each.map{|j|j[1]}.max
  prev = h
  1.upto(n-k) do |idx|
    prev_i = idx-1
    en = idx+k-1
    h[diff[prev_i]]-=1
    h[diff[en]]+=1
    ar = h.to_a
    #puts ar.to_s
    cnt = ar.each.map{|j|j[1]}.max
    max = cnt if cnt>max
    prev = h
  end

  ans << k-max
end
puts ans

S = "RGB"
gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  s = gets
  a = []
  (0...3).each do |shift|
    d = [0] * n
    cur = 0
    (0...n).each do |i|
      d[i] = (s[i] != S[(i + shift) % 3]) ? 1 : 0
      cur += d[i]
      cur -= d[i - k] if i >= k
      a << cur if i >= k - 1
    end
  end
  puts a.min
end


Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1 → 2 → 4 → 5. In one second, you can perform one of the two following operations:  Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b;  Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b. According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1 → 2 → ... → n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.

The first line contains integers n (1 ≤ n ≤ 105) and k (1 ≤ k ≤ 105) — the number of matryoshkas and matryoshka chains in the initial configuration. The next k lines contain the descriptions of the chains: the i-th line first contains number mi (1 ≤ mi ≤ n), and then mi numbers ai1, ai2, ..., aimi — the numbers of matryoshkas in the chain (matryoshka ai1 is nested into matryoshka ai2, that is nested into matryoshka ai3, and so on till the matryoshka aimi that isn't nested into any other matryoshka). It is guaranteed that m1 + m2 + ... + mk = n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.

In the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.

NoteIn the first sample test there are two chains: 1 → 2 and 3. In one second you can nest the first chain into the second one and get 1 → 2 → 3.In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds.

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

if k == 1
    p 0
    exit
end

k.times {
    a = gets.split(" ")[1..-1].map(&:to_i)
    if a[0] == 1
        i = 0
        i += 1 while i < a.size && a[i] == i + 1
        puts 2 * (n - i) - k + 1
        exit
    end
}

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

if m == 1
  puts 0
  exit
end

m.times do
  a = gets.split.map(&:to_i)
  a = a[1..-1]

  if a[0] == 1
    i = 0
    i += 1 while i < a.size && a[i] == i + 1

    puts((n - i) + (n - i - (m - 1)))
    exit
  end
end

n,m = gets.split.map{ |x| x.to_i }

v = Array.new(n) { [0,0] }
cost,merge = 0,0
real_start = 0
m.times do |i|
  a = gets.split.map{ |x| x.to_i }
  start = 1
  while (a[start] == start)
    start += 1
  end
  if start == 1
    cost += a.size - 1 - start
  else
    cost += a.size - start
    real_start = start
  end
end

merge = n-real_start+1;
#puts "split = #{cost}"
#puts "merge = #{merge}"
puts "#{cost + merge}"

n, k = gets.split.map(&:to_i)
a = k.times.map{gets.split.map(&:to_i)}
a = a.sort_by{|x| x[1]}
accumulate, c = 1, 0
a[0][1..-1].each do |x|
  if x == accumulate
    c += 1
    accumulate += 1
  else
    break
  end
end
ans = (a[0].size - 1 - c) * 2
a[1..-1].each{|x| ans += 2 * x.size - 3}
puts ans

n, k = gets.split.map(&:to_i)
a = k.times.map{gets.split.map(&:to_i)}.sort_by{|x| x[1]}
i = 1
i += 1 while a[0][i + 1] == i + 1
ans = (a[0][1..-1].size - i) * 2
a[1..-1].each{|x| ans += 2 * x[1..-1].size - 1}
puts ans

n, k = gets.split.map(&:to_i)
a = k.times.map{gets.split.map(&:to_i)}.sort_by{|x| x[1]}
accumulate, c = 1, 0
a[0][1..-1].each do |x|
  break if x != accumulate
  c += 1
  accumulate += 1
end
ans = (a[0][1..-1].size - c) * 2
a[1..-1].each{|x| ans += 2 * x[1..-1].size - 1}
puts ans

n, k = gets.split.map(&:to_i)
a = k.times.map{gets.split.map(&:to_i).drop(1)}.find{|x| x[0] == 1}
puts n + n - k + 1 - 2 * a.map.with_index(1).take_while{|x, i| x == i}.size

n, k = gets.split.map(&:to_i)
a = k.times.map{gets.split.map(&:to_i)}
accumulate, c = 1, 0
a[0][1..-1].each do |x|
  if x == accumulate
    c += 1
    accumulate += 1
  else
    break
  end
end
ans = (a[0].size - 1 - c) * 2
a[1..-1].each{|x| ans += 2 * x.size - 3}
puts ans


Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!

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

Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.

NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.

#!/usr/bin/ruby
r=m=1
gets
gets.split.map(&:to_i).each_cons(2){|x,y|
	m=x>y ? 1 : m+1
	r=[r,m].max
}
p r

gets
count=1
mx = 0
gets.split(' ').map(&:to_i).each_cons(2){|x,y|
    if x>y
        mx = [mx,count].max
        count =1
    else
        count+=1
    end
}
p [count,mx].max

n = gets
li = gets.split(' ').map(&:to_i)
count=1
mx = 0
for i in 1...li.length
    if li[i]>=li[i-1]
        count+=1
    else
        mx = [count,mx].max
        count=1
    end
end
puts [count,mx].max

n = gets.to_i
numbers = gets.split(' ').map!(&:to_i)
arr = Array.new(numbers.size, 1)
(numbers.size-1).times do |i|
    number = numbers[i+1]
    if number >= numbers[i]
        arr[i]+=arr[i-1]
    end
end
puts arr.max

n = gets.chomp.to_i
arr = gets.chomp.split(" ").map{|val| val = val.to_i}
curmax = 1
cur = 1
arr.each_with_index do |val,i|
	if i != 0 && val >= arr[i-1]
		cur += 1
	elsif cur > curmax
		curmax = cur
		cur = 1
	else
		cur = 1
	end
end
if cur > curmax
	curmax = cur
end
puts curmax

n = gets.chomp.to_i() - 1;
a = gets.chomp.split.map(&:to_i);
ans = 1;
max = 1;
(1..n).each do |x|
  if (a[x] >= a[x - 1])
      ans += 1;
      max = [max, ans].max;
  else
    ans = 1;
  end
end
p max;

n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
i = 1
max_length = 1
count = 1
while (i < n) do
  if arr[i] >= arr[i-1] then
    count += 1
  else
    count = 1
  end
  max_length = [count, max_length].max
  i += 1
end
puts max_length

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

prev = a.first
l = 1
maxl = 1
for i in 1...n do
    cur = a[i]
    if cur >= prev then
        l += 1
    else
        if l >= maxl then
            maxl = l
        end
        l = 1
    end
    prev = cur
end

if l >= maxl then
    maxl = l
end

puts maxl

n = gets.to_i
a = gets.split(" ")
cur = 0
best = 1
(1..n-1).each { |i|
  if a[i-1].to_i<=a[i].to_i
    if best<i-cur+1
      best=i-cur+1
    end
  else
    cur = i
  end
}
puts best

=begin
string = "foobar"
puts "The string '#{string}' is nonempty." unless string.empty?

puts "foo bar     baz".split
a = [42, 8, 17]
puts '['+a.join(', ')+']'
b = []
(1..5).each do |i|
  b[i] = 2*i
end
puts b

c = %w[a b c]
puts '["'+c.join('", "')+'"]'

user = { :name => "Michael Hartl", :email => "michael@example.com" }
puts user[:name]
puts user[:password]

def pow(x, y)
  p = 1
  y.times{p *= x}
  return p
end
z = pow(3,4)
puts z
=end

a=gets.chomp.to_i
b=gets.chomp.split(" ")
max=1
temp=b[0].to_i
maray=[]
1.upto(a-1) do |i|
if b[i].to_i<temp
maray << max
max=0
end
temp=b[i].to_i
max+=1
end
maray<<max
maray.sort!
puts "#{maray[maray.length-1]}"

gets
x=gets.split.map{|e| e.to_i}
o=x[0]
c=1
ans=1
1.upto(x.size-1){|i|
	if o<=x[i] then
		c=c+1
	else
		c=1
	end
	ans=[ans,c].max
	o=x[i]
}
puts ans

number = STDIN.gets.to_i
numbers = STDIN.gets

numbers = numbers.split(' ').map{|x| x.to_i}

unoozable = 1;
maxunoozable = 1;

0.upto(number-1) do |i|
  if i>0
    if numbers[i] >= numbers[i-1]

    unoozable+=1;
    else

      if unoozable > maxunoozable
        maxunoozable = unoozable;

      end
      unoozable = 1;

    end
  else
    unoozable = 1

  end
end
if unoozable > maxunoozable
  maxunoozable = unoozable;

end
puts maxunoozable

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

arr = []
i = 0
if n == 1
	print 1
else
while i < n-1
	count = 1
	x = i
	while a[x] <= a[x+1]
		count += 1
		x += 1
		if x == n-1
			break
		end
	end
	arr << count
	if count == 1
		i += 1
	elsif x <= n-2
		i = x
	else
		break
	end
end
print arr.max
end

def solution(earnings)

  front = 0
  tail = 0
  max_days = 0
  last_earning = earnings[0]

  for i in 0...earnings.size do
    front += 1
    tail = i if last_earning > earnings[i]
    max_days = [max_days, front - tail].max
    last_earning = earnings[i]
  end

  max_days
end

n = gets()
earnings = gets.strip.split.map { |i| i.to_i }
puts solution(earnings)

arrSize = gets.chomp.to_i
arr = gets.chomp.split

cnt = 1
i = 0
res =0

while i < (arr.length - 1)
  if arr[i].to_i <= arr[i+1].to_i
    cnt = cnt + 1
  else
    cnt = 1
  end
  if res < cnt
    res = cnt
  end
  i = i +1
end

if  arrSize.to_i == 1
  print arrSize.to_i
else
  print res
end

n = gets.to_i
a = gets.split.map(&:to_i)
mx, j = 1, 1
(n - 1).times do |i|
  if a[i] <= a[i + 1]
    j += 1
  else
    mx = [mx, j].max
    j = 1
  end
end
p [mx, j].max

n = gets.to_i
m = gets.split.map(&:to_i)
j=0;max=0
if n == 1
    p 1
else
for i in(1..(n-1))
    if(m[i]<m[i-1])
        if(i-j>max)
            max=i-j
        end
        j=i
    end
end
if i+1-j>max
    max = i+1-j
end
p max
end

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

prev = -1
max = 1
streak = 0
int_arr.each do |val|
    if val >= prev
        streak += 1
    else
        streak = 1
    end

    prev = val
    max = [max, streak].max
end

puts max

# https://codeforces.com/problemset/problem/580/A
n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)

max = 1
i = 1
last = a[0]
sum = 1
while(i < a.length)
    if a[i] >= last
        sum += 1
        max = sum if sum > max
    else
        sum = 1
    end
    last = a[i]
    i += 1
end

puts max

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

result = a.each_with_object({prev: 0, max: 0, step: 0}) do |i, o|
  if i >= o[:prev]
    o[:step] += 1
    o[:max] = [o[:max], o[:step]].max
  else
    o[:step] = 1
  end
  o[:prev] = i
end

p result[:max]

n = gets.to_i
arr = gets.split.map(&:to_i)
ans = 1
l = 1

for i in 1..n-1
  if arr[i] >= arr[i-1]
    l += 1
  else
    l = 1
  end
  ans = [l,ans].max
end

puts ans

n = gets.to_i
a = gets.split.map(&:to_i)
dp = [1]
(1...n).each do |i|
  dp[i] = a[i] >= a[i-1] ? dp[i-1]+1 : 1
end
puts dp.max

def read_int
	c = 0
	while c < 48 || c > 57 do
		c = $stdin.readbyte
	end
	ret = 0
	while c >= 48 && c <= 57 do
		ret = (ret << 3) + (ret << 1) + c - 48
		c = $stdin.readbyte
	end

	ret
end

n = gets.to_i
# a = gets.split.map { |s| s.to_i }
a = []
n.times do
	a << read_int
end

tmp = 1
ans = 1
(1...n).each do |i|
	if a[i] < a[i - 1]
		tmp = 1
	else
		tmp = tmp + 1
		ans = [ans, tmp].max
	end
end

puts ans

def read_int
	c = 0
	while c < 48 || c > 57 do
		c = $stdin.readbyte
	end
	ret = 0
	while c >= 48 && c <= 57 do
		ret = ret * 10 + c - 48
		c = $stdin.readbyte
	end

	ret
end

n = gets.to_i
# a = gets.split.map { |s| s.to_i }
a = []
n.times do
	a << read_int
end

tmp = 1
ans = 1
(1...n).each do |i|
	if a[i] < a[i - 1]
		tmp = 1
	else
		tmp = tmp + 1
		ans = [ans, tmp].max
	end
end

puts ans

n = gets.to_i
a = gets.split.map { |s| s.to_i }

tmp = 1
ans = 1
(1...n).each do |i|
	if a[i] < a[i - 1]
		tmp = 1
	else
		tmp = tmp + 1
		ans = [ans, tmp].max
	end
end

puts ans

def read_int
	c = ?\0
	while c < '0' || c > '9' do
		c = $stdin.readchar
	end
	ret = 0
	while c >= '0' && c <= '9' do
		ret = ret * 10 + (c.ord - '0'.ord)
		c = $stdin.readchar
	end

	ret
end

n = gets.to_i
# a = gets.split.map { |s| s.to_i }
a = []
n.times do
	a << read_int
end

tmp = 1
ans = 1
(1...n).each do |i|
	if a[i] < a[i - 1]
		tmp = 1
	else
		tmp = tmp + 1
		ans = [ans, tmp].max
	end
end

puts ans

dayNumber = gets.chomp.to_i
input = gets.chomp.split(' ').map {|item| item.to_i}
ans = 1
best = 1
for i in (0...(input.length - 1))
	#puts "ans : #{ans}"
	ans += 1 if input[i] <= input[i + 1]
	ans = 1 if input[i] > input[i + 1]
	best = ans if best <= ans
end

puts best

n = gets.chomp.to_i() - 1;
a = gets.chomp.split.map(&:to_i);
ans = 1;
max = -1;
(1..n).each do |x|
  if (a[x] >= a[x - 1])
      ans += 1;
      max = [max, ans].max;
  else
    ans = 1;
  end
end
p max;

n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
i = 1
max_length = 0
count = 1
while (i < n) do
  if arr[i] >= arr[i-1] then
    count += 1
  else
    count = 1
  end
  max_length = [count, max_length].max
  i += 1
end
puts max_length

n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
i = 1
max_length = 0
count = 1
while (i < n) do
  if count == 0 then
    count += 1
  elsif arr[i] >= arr[i-1] then
    count += 1
  else
    count = 0
  end
  max_length = [count, max_length].max
  i += 1
end
puts max_length

n = gets.to_i
a = gets.split(" ")
cur = 0
best = 1
(1..n-1).each { |i|
  if a[i-1].to_i<a[i].to_i
    if best<i-cur+1
      best=i-cur+1
    end
  else
    cur = i
  end
}
puts best

=begin
string = "foobar"
puts "The string '#{string}' is nonempty." unless string.empty?

puts "foo bar     baz".split
a = [42, 8, 17]
puts '['+a.join(', ')+']'
b = []
(1..5).each do |i|
  b[i] = 2*i
end
puts b

c = %w[a b c]
puts '["'+c.join('", "')+'"]'

user = { :name => "Michael Hartl", :email => "michael@example.com" }
puts user[:name]
puts user[:password]

def pow(x, y)
  p = 1
  y.times{p *= x}
  return p
end
z = pow(3,4)
puts z
=end

gets
x=gets.split.map{|e| e.to_i}
o=x[0]
c=1
ans=0
1.upto(x.size-1){|i|
	if o<=x[i] then
		c=c+1
	else
		c=1
	end
	ans=[ans,c].max
	o=x[i]
}
puts ans

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

arr = []
i = 0
while i < n-1
	count = 1
	x = i
	while a[x] <= a[x+1]
		count += 1
		x += 1
		if x == n-1
			break
		end
	end
	arr << count
	if count == 1
		i += 1
	elsif x <= n-2
		i = x
	else
		break
	end
end
print arr.max

def solution(earnings)

  front = 0
  tail = 0
  max_days = 0
  last_earning = earnings[0]

  for i in 1...earnings.size do
    front = i + 1
    tail = i if last_earning > earnings[i]
    max_days = [max_days, front - tail].max
    last_earning = earnings[i]
  end

  max_days
end

n = gets()

earnings = gets.strip.split.map { |i| i.to_i }
puts solution(earnings)

arrSize = gets.chomp.to_i
arr = gets.chomp.split

cnt = 1
i = 0
cntArr = []

while i < (arr.length - 1)
  if arr[i].to_i <= arr[i+1].to_i
    cnt = cnt + 1
  else
    cntArr.push cnt
    cnt = 1
  end
  i = i +1
end

if cntArr.empty?()
  print cnt
else
  print cntArr.max
end

arrSize = gets.chomp.to_i
arr = gets.chomp.split

cnt = 1
i = 0
res =0

while i < (arr.length - 1)
  if arr[i].to_i <= arr[i+1].to_i
    cnt = cnt + 1
  else
    cnt = 1
  end
  if res < cnt
    res = cnt
  end
  i = i +1
end

print res

n = gets.to_i
m = gets.split.map(&:to_i)
j=0;max=0
for i in(1..(n-1))
    if(m[i]<m[i-1] && i-j>max)
        max=i-j
        j=i
    end
end
if i-j+1>max
    max = i-j+1
end
p max

n = gets.to_i
ans = 1
l = 1
num = gets.to_i

for i in 2..n
  x = gets.to_i

  if x >= num
    l += 1
  else
    l = 1
  end
  ans = [l,ans].max
  num = x
end

puts ans

dayNumber = gets.chomp.to_i
input = gets.chomp.split(' ').map {|item| item.to_i}
index = 0
ans = 1
best = 0
for i in (0...(input.length - 1))
	#puts "ans : #{ans}"
	ans += 1 if input[i] <= input[i + 1]
	ans = 1 if input[1] > input[i + 1]
	best = ans if best <= ans
end

puts best

dayNumber = gets.chomp.to_i
input = gets.chomp.split(' ').map {|item| item.to_i}
index = 0
ans = 0
best = 0
for i in (0...(input.length - 1))
	#puts "ans : #{ans}"
	ans += 1 if input[i] <= input[i + 1]
	ans = 0 if input[1] > input[i + 1]
	best = ans if best < ans
end

puts best + 1

dayNumber = gets.chomp.to_i
input = gets.chomp.split(' ').map {|item| item.to_i}
ans = 1
best = 0
for i in (0...(input.length - 1))
	#puts "ans : #{ans}"
	ans += 1 if input[i] <= input[i + 1]
	ans = 1 if input[i] > input[i + 1]
	best = ans if best <= ans
end

puts best


Vasya is choosing a laptop. The shop has n laptops to all tastes.Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties.If all three properties of a laptop are strictly less than those properties of some other laptop, then the first laptop is considered outdated by Vasya. Among all laptops Vasya does not consider outdated, he chooses the cheapest one.There are very many laptops, which is why Vasya decided to write a program that chooses the suitable laptop. However, Vasya doesn't have his own laptop yet and he asks you to help him.

The first line contains number n (1 ≤ n ≤ 100). Then follow n lines. Each describes a laptop as speed ram hdd cost. Besides,    speed, ram, hdd and cost are integers  1000 ≤ speed ≤ 4200 is the processor's speed in megahertz  256 ≤ ram ≤ 4096 the RAM volume in megabytes  1 ≤ hdd ≤ 500 is the HDD in gigabytes  100 ≤ cost ≤ 1000 is price in tugriks  All laptops have different prices.

Print a single number — the number of a laptop Vasya will choose. The laptops are numbered with positive integers from 1 to n in the order in which they are given in the input data.

NoteIn the third sample Vasya considers the first and fifth laptops outdated as all of their properties cannot match those of the third laptop. The fourth one is the cheapest among the laptops that are left. Thus, Vasya chooses the fourth laptop.

n=gets.to_i
computer=Struct.new("Computer",:cpu,:ram,:hdd,:cost)
c=[]
for i in 1..n
    input=gets.split.map(&:to_i)
    c.push(computer.new(input[0],input[1],input[2],input[3]))
end
u=Array.new(n,0)
for i in 0..n-1
    for j in 0..n-1
        if c[i].cpu<c[j].cpu && c[i].ram < c[j].ram && c[i].hdd < c[j].hdd then
            u[i]=1
        end
    end
end
mincost = 999999999
for i in 0..n-1
    if u[i]==0 then
        if mincost>c[i].cost then
            mincost=c[i].cost
            res=i+1
        end
    end
end
puts res

n = STDIN.readline.to_i
laptops = []
n.times {|i| laptops.push(STDIN.readline.split.map {|s| s.to_i } + [i] ) }
consider = []
n.times do |i|
  a = laptops[i]
  okay = true
  n.times do |j|
    b = laptops[j]
    if a[0] < b[0] and a[1] < b[1] and a[2] < b[2]
      okay = false
      break
    end
  end
  consider.push(a) if okay
end
consider.sort_by! {|a| a[3] }
puts consider[0][4] + 1

#!/usr/bin/ruby
count = gets.chop.to_i
laptops = Array.new(count){Array.new(5)}
i = 0
while line = gets
        line.chomp!
        laptop = line.split(' ')
        laptops[i][0] = laptop[0].to_i
        laptops[i][1] = laptop[1].to_i
        laptops[i][2] = laptop[2].to_i
        laptops[i][3] = laptop[3].to_i
        laptops[i][4] = 1;
        i = i+1
end
for i in 0..laptops.count-1
        for i2 in 0..laptops.count-1
                trues = 0
                for i3 in 0..2
                        if laptops[i][i3] < laptops[i2][i3]
                                trues = trues+1
                        end
                end
                if trues == 3
                        laptops[i][4] = 0
                        #puts "vyhozen " + i.to_s
                        break
                end
        end
end
minprice = -1
minindex = -1
for a in 0..laptops.count-1
        if laptops[a][3] < minprice || minprice == -1
                if laptops[a][4] == 1
                        minprice = laptops[a][3];
                        minindex = a;
                end
        end
        #puts min.to_s
end
puts (minindex+1).to_s

n = gets.to_i
a = readlines.map(&:chomp).map(&:split).each {|x| x.map!(&:to_i)}
ok = a.find_all { |i| !a.any? { |x| i[0]<x[0] and i[1]<x[1] and i[2]<x[2] and i[3]<x[3] } }
puts a.index(ok.min_by {|x| x[3]})+1

#$stdin = File.open("./input", "r")

Notebook = Struct.new(:id, :speed, :ram, :hdd, :cost)

n=gets.to_i

data=[]
n.times{|i|
	speed, ram, hdd, cost=gets.split.map(&:to_i)
	id=i+1
	data << Notebook.new(id, speed, ram , hdd, cost)
}

n.times{|i|
	n.times{|j|
		next if i==j || data[i].nil? || data[j].nil?

		a, b = data[i], data[j]

		if a.speed<b.speed && a.ram<b.ram && a.hdd<b.hdd
			data[i]=nil
		end
	}
}

puts data.keep_if{|v| !v.nil?}.sort!{|a,b| (a.cost<b.cost)?-1:1}[0].id

#!/usr/bin/ruby
count = gets.chop.to_i
laptops = Array.new(count){Array.new(5)}
i = 0
while line = gets
	line.chomp!
	laptop = line.split(' ')
	laptops[i][0] = laptop[0].to_i
        laptops[i][1] = laptop[1].to_i
        laptops[i][2] = laptop[2].to_i
        laptops[i][3] = laptop[3].to_i
	laptops[i][4] = 1;
	i = i+1
end
for i in 0..laptops.count-1
	for i2 in 0..laptops.count-1
		trues = 0
		for i3 in 0..2
			if laptops[i][i3] < laptops[i2][i3]
				trues = trues+1
			end
		end
		if trues == 3
			laptops[i][4] = 0
			#puts "vyhozen " + i.to_s
			break
		end
	end
end
for a in  0..laptops.count-1
        if laptops[a][4] == 1
                min = a;
		break
        end
end
#puts min.to_s
for a in 0..laptops.count-1
	if laptops[a][3] < laptops[min][3]
		if laptops[a][4] == 1
			min = a;
		end
	end
	#puts min.to_s
end
puts (min+1).to_s

class Comp
  attr_accessor :hdd, :ram, :cpu, :cost, :id

  def greater_than(other)
    if (@hdd > other.hdd and @ram > other.ram and @cpu > other.cpu)
      return true
    end
    return false
  end
end

comps = Hash.new
count = gets.to_i
count.times { |i|
  cpus, rams, hdds, costs = gets.chop.split(/\s+/)
  comp = Comp.new
  comp.hdd = hdds.to_i
  comp.cpu = cpus.to_i
  comp.ram = rams.to_i
  comp.cost = costs.to_i
  comp.id = i+1
  comps[comp.id] = comp
}
lastCount = 0
currCount = count
while (lastCount != currCount) do
  lastCount = comps.length

  comps.each { |id1, comp1|
    comps.each { |id2, comp2|
      if (id1 != id2 and comp1 != nil and comp2 != nil)
        if (comp1.greater_than(comp2))
          comps[id2] = nil
        elsif (comp2.greater_than(comp1))
          comps[id1] = nil
        end
      end
    }
  }
  currCount = comps.length
 # p comps
end

mincomp = nil
comps.each { |id, comp|
  if comp != nil
    if (mincomp == nil)
      mincomp = comp
    end
    if (comp.cost < mincomp.cost)
      mincomp = comp
    end
  end
}

puts mincomp.id

def choosing_laptop
  specs = []
  gets.to_i.times do
    specs << gets.split(' ').map{|i| i.to_i}
  end

  (0...specs.size).each do |i|
    (0...specs.size).each do |j|
      next if specs[j].nil? or specs[i].nil?

      if specs[i][0] > specs[j][0] and specs[i][1] > specs[j][1] and specs[i][2] > specs[j][2]
        specs[j] = nil
      end
    end
  end

  min = min_ind = nil
  (0...specs.size).each do |i|
    next if specs[i].nil?

    if min.nil? or specs[i][3] < min
      min, min_ind = specs[i][3], i
    end
  end

  puts min_ind+1
end

choosing_laptop

#!/usr/bin/env ruby

n = gets.chomp.to_i
arr = []
n.times do |i|
    arr.push gets.chomp.split(/ /).map{|n| n.to_i} + [i+1]
end

n.times do |i|
    n.times do |j|
        if arr[i][0] < arr[j][0] and arr[i][1] < arr[j][1] and arr[i][2] < arr[j][2]
            arr[i][4] = 0
        end
    end
end

puts arr.select{|a| a[4] != 0}.min{|a,b| a[3] <=> b[3]}[4]

#!/usr/bin/env ruby

n = gets.chomp.to_i
arr = []
n.times do |i|
    arr.push gets.chomp.split(/ /).map{|n| n.to_i} + [i+1]
end

n.times do |i|
    n.times do |j|
        if arr[i][0] < arr[j][0] and arr[i][1] < arr[j][1] and arr[i][2] < arr[j][2]
            arr[i][4] = 0
        end
    end
end

id = 0
minv = 10000
arr.select{|a| a[4] != 0}.each do |a|
    if a[3] < minv
        minv = a[3]
        id = a[4]
    end
end
puts id

laptops=[]
gets.to_i.times{laptops<<gets.split.map(&:to_i)}
l=laptops.each_with_index.to_a.map.sort_by{|(a,b,c,d),i|d}
l.each_with_index{|((a,b,c,d),i),j|
	if l[j+1..-1].any?{|(aa,bb,cc,dd),ii|aa>a&&bb>b&&cc>c&&dd>d}
		next
	else
		puts i+1
		break
	end
}

#!/usr/bin/env ruby

n = STDIN.gets.to_i
laptops=[]
n.times do
  laptops << STDIN.gets.split(" ").map {|i| i.to_i}
end

flag = (0..n-1).map {|i| true}
(laptops.length-1).times do |i|
  (i+1..laptops.length-1).each do |j|
    flag[i] = nil if laptops[i][0] < laptops[j][0] and laptops[i][1] < laptops[j][1] and laptops[i][2] < laptops[j][2]
    flag[j] = nil if laptops[j][0] < laptops[i][0] and laptops[j][1] < laptops[i][1] and laptops[j][2] < laptops[i][2]
  end
end

min = 10000
id = 0
flag.length.times do |i|
  #p [i,flag[i]]
  if flag[i] and laptops[i][3] < min
    #p [i,flag[i]]
      id = i
      min = laptops[i][3]
  end
end
puts id+1

gets; laptops, old = STDIN.read.split("\n").map {|l| l.split.map! &:to_i }, []

laptops.each do |l|
  laptops.each do |a|
    (old.push l; break) if l[0] < a[0] && l[1] < a[1] && l[2] < a[2]
  end
end

min = 1001
(laptops - old).each { |l| min = l[3] if l[3] < min }

laptops.each.with_index { |l, i| (print i + 1 ;break) if l[3] == min }

n = gets.to_i
a = readlines.map(&:chomp).map(&:split).each {|x| x.map!(&:to_i)}
puts a.find_all { |i| !a.any? { |x| i[0]<x[0] and i[1]<x[1] and i[2]<x[2] and i[3]<x[3] } }.min_by {|x| x[3]}[3]

#$stdin = File.open("./input", "r")

Notebook=Struct.new(:id, :speed, :ram, :hdd, :cost)

data=[]

n=gets.to_i
n.times{|i|
	speed, ram, hdd, cost=gets.split.map(&:to_i)
	id=i+1
	data << Notebook.new(id, speed, ram, hdd, cost)
}

data.sort!{|a, b|
	(a.speed<b.speed && a.ram<b.ram && a.hdd<b.hdd)? -1 : 1
}

for i in 0..data.size-2
	a,b=data[i], data[i+1]

	if a.speed<b.speed && a.ram<b.ram && a.hdd<b.hdd
		tmp=data[(i+1)..data.size-1].sort!{|a,b| (a.cost<b.cost)? -1 : 1}
		puts tmp[0].id
		exit
	end
end

tmp=data.sort!{|a,b| (a.cost<b.cost)? -1 : 1}
puts tmp[0].id

#$stdin = File.open("./input", "r")

Notebook=Struct.new(:id, :speed, :ram, :hdd, :cost)

data=[]

n=gets.to_i
n.times{|i|
	speed, ram, hdd, cost=gets.split.map(&:to_i)
	id=i+1
	data << Notebook.new(id, speed, ram, hdd, cost)
}

data.sort!{|a, b|
	(a.speed<b.speed && a.ram<b.ram && a.hdd<b.hdd)? -1 : 1
}

puts data

for i in 0..data.size-1
	a,b=data[i], data[i+1]

	if a.speed<b.speed && a.ram<b.ram && a.hdd<b.hdd
		tmp=data[(i+1)..data.size-1].sort!{|a,b| (a.cost<b.cost)? -1 : 1}
		puts tmp[0].id
		break
	end
end

#$stdin = File.open("./input", "r")

Notebook=Struct.new(:speed, :ram, :hdd, :cost)

data=[]

n=gets.to_i
n.times{
	speed, ram, hdd, cost=gets.split.map(&:to_i)
	data << Notebook.new(speed, ram, hdd, cost)
}

data.sort!{|a, b|
	(a.speed<b.speed && a.ram<b.ram && a.hdd<b.hdd)? -1 : 1
}

fin_index=-1
min_cost=999999

for i in 0..data.size-2
	a,b=data[i], data[i+1]

	if a.speed<b.speed && a.ram<b.ram && a.hdd<b.hdd
		[*(i+1)..data.size-1].each{|index|
			notebook=data[index]

			if notebook.cost<min_cost
				min_cost=notebook.cost
				fin_index=index
			end
		}
		break
	end
end

puts "#{fin_index+1}"

#!/usr/bin/env ruby

n = gets.chomp.to_i
arr = []
n.times do
    arr.push gets.chomp.split(/ /).map{|n| n.to_i}
end

speed = arr.map{|a| a[0]}.max
ram = arr.map{|a| a[1]}.max
hdd = arr.map{|a| a[2]}.max

n.times do |i|
    unless arr[i][0] == speed or arr[i][1] == ram or arr[i][2] == hdd
        3.times do |j|
            arr[i][j] = 0
        end
    end
end

id = 0
minv = 10000
n.times do |i|
    if arr[i][0] != 0 and arr[i][1] != 0 and arr[i][2] != 0
        if arr[i][3] < minv
            minv = arr[i][3]
            id = i
        end
    end
end

puts id + 1

#!/usr/bin/env ruby

n = gets.chomp.to_i
arr = []
n.times do
    arr.push gets.chomp.split(/ /).map{|n| n.to_i}
end

speed = arr.map{|a| a[0]}.max
ram = arr.map{|a| a[1]}.max
hdd = arr.map{|a| a[2]}.max

n.times do |i|
    if arr[i][0] < speed and arr[i][1] < ram and arr[i][2] < hdd
        3.times do |j|
            arr[i][j] = 0
        end
    end
end

id = 0
minv = 10000
n.times do |i|
    if arr[i][0] != 0 and arr[i][1] != 0 and arr[i][2] != 0
        if arr[i][3] < minv
            minv = arr[i][3]
            id = i
        end
    end
end

puts id + 1

#!/usr/bin/env ruby

n = gets.chomp.to_i
arr = []
n.times do
    arr.push gets.chomp.split(/ /).map{|n| n.to_i}
end

speed = arr.map{|a| a[0]}.max
ram = arr.map{|a| a[1]}.max
hdd = arr.map{|a| a[2]}.max

n.times do |i|
    if arr[i][0] < speed and arr[i][1] < ram and arr[i][2] < hdd
        3.times do |j|
            arr[i][j] = 0
        end
    end
end

id = 0
minv = 10000
n.times do |i|
    if arr[i][0] != 0 and arr[i][1] != 0 and arr[i][2] != 0
        if arr[i][3] <= minv
            minv = arr[i][3]
            id = i
        end
    end
end

puts id + 1

#!/usr/bin/env ruby

n = STDIN.gets.to_i
laptops=[]
n.times do
  laptops << STDIN.gets.split(" ").map {|i| i.to_i}
end

flag = (0..n-1).map {|i| true}
(laptops.length-1).times do |i|
  (i+1..laptops.length-1).each do |j|
    flag[i] = false if laptops[i][0] < laptops[j][0] and laptops[i][1] < laptops[j][1] and laptops[i][2] < laptops[j][2]
    flag[j] = false if laptops[j][0] < laptops[i][0] and laptops[j][1] < laptops[i][1] and laptops[j][2] < laptops[i][2]
  end
end

min = 10000
id = 0
flag.length.times do |i|
  if flag and laptops[i][3] < min
    id = i
    min = laptops[i][3]
  end
end
puts id

gets; laptops = STDIN.read.split("\n").map {|l| l.split.map! &:to_i }
d = laptops.dup

laptops.each.with_index do |l, i|
  laptops.each do |a|
    next if l == a
    laptops.delete_at(i) if l[0] < a[0] && l[1] < a[1] && l[2] < a[2]
  end
end

min = 1001
laptops.each { |i| min = i[3] if i[3] < min }

d.each.with_index do |l, i|
  if l[3] == min
    print i + 1
    break
  end
end


You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.

The first line of the input contains following integers:   n: the number of towers in the building (1 ≤ n ≤ 108),  h: the number of floors in each tower (1 ≤ h ≤ 108),  a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h),  k: total number of queries (1 ≤ k ≤ 104).  Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.

For each query print a single integer: the minimum walking time between the locations in minutes.

N, H, A, B, K = gets.split.map(&:to_i)
K.times do
    ta, fa, tb, fb = gets.split.map(&:to_i)
    if ta == tb
        dh = (fa-fb).abs
    elsif fa<A && fb<A
        dh = 2*A - fa - fb
    elsif fa>B && fb>B
        dh = fa+fb - 2*B
    else
        dh = (fa-fb).abs
    end
    puts dh + (ta-tb).abs
end

n,h,a,b,k = gets.strip.split.map(&:to_i)

k.times do
  ta,fa,tb,fb = gets.strip.split.map(&:to_i)
  # ta,fa,tb,fb=[tb,fb,ta,fa] if ta>tb
  if(ta==tb)
    puts (fa-fb).abs
  else
    tt = (ta-tb).abs
    if fa>b && fb>b
      tt += ( (fa-b).abs + (fb-b).abs )
    elsif fa<a && fb<a
      tt += ( (fa-a).abs + (fb-a).abs )
    else
      tt += ( (fa-fb).abs )
    end
    puts tt
  end
end

n,h,a,b,k = gets.chomp.split(" ").map(&:to_i)
k.times do
  o,p,q,r = gets.chomp.split(" ").map(&:to_i)
  ans = 0
  ans += (o-q).abs
  if ((p < a && r < a) || (p > b && r > b)) && o != q
    ans += [(p-a).abs,(p-b).abs].min
    ans += [(r-a).abs,(r-b).abs].min
  else
    ans += (p-r).abs
  end
  puts ans
end

n, h, a, b, k = gets.split.map(&:to_i)
k.times do
    ta, fa, tb, fb = gets.split.map(&:to_i)
    if ta == tb
        puts (fa - fb).abs
        next
    end
    ans = (ta - tb).abs
    if fa > fb
        fa, fb = fb, fa
    end
    if fa <= b && fb >= a
        ans += fb - fa
    elsif fa > b
        ans += (fa - b) + (fb - b)
    elsif fb < a
        ans += (a - fb) + (a - fa)
    end
    puts ans
end

nhabk = gets.chomp.split(" ").map(&:to_i)
n = nhabk[0]
h = nhabk[1]
a = nhabk[2]
b = nhabk[3]
k = nhabk[4]

arr = []
k.times {arr.push gets.chomp.split(" ").map(&:to_i)}

arr.each do |z|
  ta = z[0]
  fa = z[1]
  tb = z[2]
  fb = z[3]

  if ta == tb
    puts (fa-fb).abs
    next
  end

  ans = 0
  floor = fa

  if fa<a
    floor = a
    ans += a-fa
  elsif fa>b
    floor = b
    ans += fa-b
  end

  ans += (tb-ta).abs
  ans += (floor-fb).abs

  puts ans
end

N, H, A, B, K = gets.split.map(&:to_i)
K.times do
    ta, fa, tb, fb = gets.split.map(&:to_i)
    if fa<A && fb<A
        dh = 2*A - fa - fb
    elsif fa>B && fb>B
        dh = fa+fb - 2*B
    else
        dh = (fa-fb).abs
    end
    puts dh + (ta-tb).abs
end

n,h,a,b,k = gets.chomp.split(" ").map(&:to_i)
k.times do
  o,p,q,r = gets.chomp.split(" ").map(&:to_i)
  ans = 0
  ans += (o-q).abs
  if (p < a && r < a) || (p > b && r > b)
    ans += [(p-a).abs,(p-b).abs].min
    ans += [(r-a).abs,(r-b).abs].min
  else
    ans += (p-r).abs
  end
  puts ans
end

nhabk = gets.chomp.split(" ").map(&:to_i)
n = nhabk[0]
h = nhabk[1]
a = nhabk[2]
b = nhabk[3]
k = nhabk[4]

arr = []
k.times {arr.push gets.chomp.split(" ").map(&:to_i)}

arr.each do |z|
  ta = z[0]
  fa = z[1]
  tb = z[2]
  fb = z[3]

  ans = 0
  floor = fa

  if fa<a
    floor = a
    ans += a-fa
  elsif fa>b
    floor = b
    ans += fa-b
  end

  ans += tb-ta
  ans += (floor-fb).abs

  puts ans
end

nhabk = gets.chomp.split(" ").map(&:to_i)
n = nhabk[0]
h = nhabk[1]
a = nhabk[2]
b = nhabk[3]
k = nhabk[4]

arr = []
k.times {arr.push gets.chomp.split(" ").map(&:to_i)}

arr.each do |z|
  ta = z[0]
  fa = z[1]
  tb = z[2]
  fb = z[3]

  ans = 0
  floor = fa

  if fa<a
    floor = a
    ans += a-fa
  elsif fa>b
    floor = b
    ans += fa-b
  end

  ans += (tb-ta).abs
  ans += (floor-fb).abs

  puts ans
end