Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any $$$i$$$ ($$$1 \le i \le n-1$$$), this condition must be satisfied: $$$$$$\frac{\max(a[i], a[i+1])}{\min(a[i], a[i+1])} \le 2$$$$$$For example, the arrays $$$[1, 2, 3, 4, 3]$$$, $$$[1, 1, 1]$$$ and $$$[5, 10]$$$ are dense. And the arrays $$$[5, 11]$$$, $$$[1, 4, 2]$$$, $$$[6, 6, 1]$$$ are not dense.You are given an array $$$a$$$ of $$$n$$$ integers. What is the minimum number of numbers you need to add to an array to make it dense? You can insert numbers anywhere in the array. If the array is already dense, no numbers need to be added.For example, if $$$a=[4,2,10,1]$$$, then the answer is $$$5$$$, and the array itself after inserting elements into it may look like this: $$$a=[4,2,\underline{\textbf{3}},\underline{\textbf{5}},10,\underline{\textbf{6}},\underline{\textbf{4}},\underline{\textbf{2}},1]$$$ (there are other ways to build such $$$a$$$).

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) — the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 50$$$).

For each test case, output one integer — the minimum number of numbers that must be added to the array to make it dense.

NoteThe first test case is explained in the statements.In the second test case, you can insert one element, $$$a=[1,\underline{\textbf{2}},3]$$$.In the third test case, you can insert two elements, $$$a=[6,\underline{\textbf{4}},\underline{\textbf{2}},1]$$$.In the fourth test case, you can insert one element, $$$a=[1,\underline{\textbf{2}},4,2]$$$.In the fifth test case, the array $$$a$$$ is already dense.

alias g gets;g.to_i.times{g;a=g.split.map &:to_i;p (a.zip(a[1..])[..-2].map &:sort).map{|x,y|(-1-y/-x).to_s(2).size-1}.sum}

alias g gets;g.to_i.times{g;a=g.split.map &:to_i;p (a.zip(a[1..])[..-2].map &:sort).map{|x, y|(-1-y/-x).to_s(2).size-1}.sum}

t = gets.chomp.to_i

def getNumInsertions(smaller, bigger)
    nextElement = smaller
    count = 0
    until nextElement * 2 >= bigger
        nextElement *= 2
        count += 1
    end
    return count
end

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

    count = 0
    0.upto(n - 2) { |i|
        smaller = a[i] < a[i + 1] ? a[i] : a[i + 1]
        bigger = a[i] > a[i + 1] ? a[i] : a[i + 1]

        count += getNumInsertions(smaller, bigger)
    }

    puts count
}

# frozen_string_literal: true

def distance(numbers)
  a, b = numbers.minmax
  res = 0
  while a * 2 < b
    res += 1
    a *= 2
  end
  res
end

test = gets.to_i
test.times do
  n = gets.chomp.to_i
  numbers = gets.chomp.split.map(&:to_i)
  result = (0..n-2).reduce(0) do |total, index|
    total + distance(numbers[index..index+1])
  end
  puts result
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	puts a.each_cons(2).sum { |x, y|
			x, y = [x, y].sort
			res = 0
			while x * 2 < y
				res += 1
				x *= 2
			end
			res
	     }
end

def method(x, y)
  x, y = [x, y].minmax
  0.step do |i|
    break i if x * 2 >= y
    x *= 2
  end
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  puts a.each_cons(2).map { |x, y| method(x, y) }.sum
end

gets.to_i.times do
  n=gets.to_i
  a=gets.split.map(&:to_i)
  q=a[0]
  c=0
  a.each do |aa|
    x,y=[q,aa].sort
    while x*2<y
      x*=2
      c+=1
    end
    q=aa
  end
  puts c
end


Alice and Bob received $$$n$$$ candies from their parents. Each candy weighs either 1 gram or 2 grams. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies.Check if they can do that.Note that candies are not allowed to be cut in half.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of candies that Alice and Bob received. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ — the weights of the candies. The weight of each candy is either $$$1$$$ or $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output on a separate line:    "YES", if all candies can be divided into two sets with the same weight;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

NoteIn the first test case, Alice and Bob can each take one candy, then both will have a total weight of $$$1$$$.In the second test case, any division will be unfair.In the third test case, both Alice and Bob can take two candies, one of weight $$$1$$$ and one of weight $$$2$$$.In the fourth test case, it is impossible to divide three identical candies between two people.In the fifth test case, any division will also be unfair.

def is_fair_division?(candies, n)
  return true if n == 0

  ones_count = 0
  twos_count = 0
  candies.each do |candy|
    if candy == 1
      ones_count += 1
    elsif candy == 2
      twos_count += 1
    end
  end

  if ones_count % 2 == 1
    return false
  else
    if ones_count >= 2 || twos_count % 2 == 0
      return true
    else
      return false
    end
  end
end

t = gets.chomp().to_i
t.times do |_|
  n = gets.chomp().to_i
  candies = gets.chomp().split("").map(&:to_i)
  if is_fair_division?(candies, n)
    puts "YES"
  else
    puts "NO"
  end
end

gets.to_i.times do
n=gets.to_i
a=gets.split(' ').map(&:to_i).sort
if a.reduce(:+) % 2 == 1 || a[0] == 2 && n % 2 == 1
puts 'NO'
else
puts 'YES'
end
end

gets.to_i.times {
  gets
  a = 0; b = 0
  gets.split.map!(&:to_i).each { _1 == 1 ? (a += 1) : (b += 1) }

  if b.odd?
    if a < 2
      puts "No"
      next
    end

    b += 1
    a -= 2
  end

  if a.odd?
    puts "No"
    next
  end

  puts "Yes"
}

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

  one = a.count(1)
  two = n - one
  # STDERR.puts [one, two].inspect

  possible = (0 .. two).any? { |x|
    (two - 2 * x).abs * 2 <= one and one.even?
  }
  puts possible ? "YES" : "NO"
end

t = gets.to_i
t.times do
  solve
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map { |v| v.to_i }
  puts a.sum.even? && (!a.count(1).zero? || a.count(2).even?) ? "YES" : "NO"
end

a = gets.to_i
for i in 1..a do
    x = gets.to_i
    b = gets.chop.split(/ /).map(&:to_i)
    c = b.sum
    if c % 2 == 1
        print("NO", "\n")
    else
        if b.include? 1
            print("YES", "\n")
        else
            if x % 2 == 0
                print("YES", "\n")
            else
                print("NO", "\n")
            end
        end
    end
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	x, y = a.count(1), a.count(2)
	x -= 2 if y.odd?
	puts x.odd? || x < 0 ? 'NO' : 'YES'
end

t = gets.to_i

t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i).tally

  a[1] ||= 0
  a[2] ||= 0

  if a[2].odd?
    if a[1] > 0 && a[1].even?
      puts 'yes'
    else
      puts 'no'
    end
  else
    if a[1].odd?
      puts 'no'
    else
      puts 'yes'
    end
  end
end

#!/usr/bin/env ruby

gets.to_i.times {
    n = gets.to_i
    sweets = gets.split.map &:to_i
    tv1 = sweets.select{|v| v == 1}.size
    tv2 = sweets.select{|v| v == 2}.size
    res = false
    (tv1 + 1).times do |v1|
        (tv2 + 1).times do |v2|
            g1 = v1 + v2 * 2
            g2 = (tv1 - v1) + (tv2 - v2) * 2
            #puts [g1, g2].to_s
            if g1 == g2
                res = true
            end
        end
    end

    puts res ? "YES" : "NO"
}

gets.to_i.times do
  n =  gets.to_i
  a = gets.split.map &:to_i
  cnt = [0] * 3
  a.each do |i|
    cnt[i] += 1
  end
  if cnt[2] % 2 == 1 && (cnt[1] < 2 || (cnt[1] - 2) % 2 == 1) || cnt[2] % 2 == 0 && cnt[1] % 2 == 1
    puts "NO"
  else
    puts "YES"
  end
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i)
    hash = Hash.new(0)
    ans = 0
    a.each do |i|
        hash[i] += 1
        ans += i
    end
    if ans % 2 != 0
        puts "NO"
    else
        if hash[1] >= 1
            puts "YES"
        elsif hash[2] % 2 != 0
            puts "NO"
        else
            puts "YES"
        end
    end
end

require 'prime'
t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  if arr.sum % 2 != 0 || arr.sum % 2 == 0 && arr.count(1) == 0 && arr.count(2) % 2 != 0
    puts "NO"
  else
    puts "YES"
  end
end

gets.to_i.times do
  n=gets.to_i
  a=gets.split.map(&:to_i)
  s=a.sum
  if s.odd?
    puts "NO"
    next
  end
  s2=s/2
  if s2.even?
    puts "YES"
  elsif a.include?(1)
    puts "YES"
  else
    puts "NO"
  end
end

def is_fair_division?(candies, n)
  return true if n == 0

  ones_sum = 0
  twos_sum = 0
  candies.each do |candy|
    if candy == 1
      ones_sum += 1
    elsif candy == 2
      twos_sum += 2
    end
  end

  return (ones_sum % 2 == 0) && (twos_sum % 2 == 0)
end

t = gets.chomp().to_i
t.times do |_|
  n = gets.chomp().to_i
  candies = gets.chomp().split("").map(&:to_i)
  if is_fair_division?(candies, n)
    puts "YES"
  else
    puts "NO"
  end
end

t = gets.to_i

t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i).tally

  a[1] ||= 0
  a[2] ||= 0

  if (2 * a[2] + a[1]).odd?
    puts 'no'
  elsif a[2] <= a[1]
    puts 'yes'
  elsif (a[2] - 2 * a[1]).even?
    puts 'yes'
  else
    puts 'no'
  end
end

t = gets.to_i

t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i).tally

  a[1] ||= 0
  a[2] ||= 0

  if a[1].even? && a[2].even?
    puts 'yes'
  else
    puts 'no'
  end
end


Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.

The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.  The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.

If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that. If that is impossible, print  - 1.

NoteAnya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.In the third sample test the answer is  - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.

# $stdin = File.open('in.txt')

m, t, r = gets.split.map(&:to_i)
w = gets.split.map(&:to_i)

mp = Hash.new(0)
need = Hash.new(0)
w.each { |x| need[x] = r }

ans = 0

(-305..305).each {|x|
  put = 0

  ((x+1)..(x+t)).each {|y|
    if mp[y] < need[y]
      put = 1 if need[y] - mp[y] > y - x - 1
    end
  }

  if put == 1
    ((x+1)..(x+t)).each {|x| mp[x] += 1}
    ans += 1
  end
}

(0..305).each {|x|
  ans = -1 if mp[x] < need[x]
}

p ans

# $stdin = File.open('in.txt')

m, t, r = gets.split.map(&:to_i)
w = gets.split.map(&:to_i)

mp = Hash.new(0)
need = Hash.new(0)
w.each { |x| need[x] = r }

ans = 0

(-300..300).each {|x|
  put = 0

  ((x+1)..(x+t)).each {|y|
    if mp[y] < need[y]
      put = 1 if need[y]-mp[y] >= y - x - 1
    end
  }

  if put == 1
    ((x+1)..(x+t)).each {|x| mp[x] += 1}
    ans += 1
  end
}

(0..300).each {|x|
  ans = -1 if mp[x] < need[x]
}

p ans

# $stdin = File.open('in.txt')

m, t, r = gets.split.map(&:to_i)
w = gets.split.map(&:to_i)

mp = Hash.new(0)
need = Hash.new(0)
w.each { |x| need[x] = r }

ans = 0

(-305..305).each {|x|
  put = 0

  ((x+1)..(x+t)).each {|y|
    if mp[y] < need[y]
      put = 1 if need[y]-mp[y] >= y - x - 1
    end
  }

  if put == 1
    ((x+1)..(x+t)).each {|x| mp[x] += 1}
    ans += 1
  end
}

(0..305).each {|x|
  ans = -1 if mp[x] < need[x]
}

p ans


One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2·n there are exactly m numbers which binary representation contains exactly k digits one".The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.

The first line contains two space-separated integers, m and k (0 ≤ m ≤ 1018; 1 ≤ k ≤ 64).

Print the required number n (1 ≤ n ≤ 1018). If there are multiple answers, print any of them.

def c(n, k)
	if n < k
		0
	else
		p = 1
		((n - k + 1)..n).each { |i|
			p *= i
		}
		(1..k).each { |i|
			p /= i
		}
		p
	end
end

n = 1
m, k = gets.split.map(&:to_i)
k -= 1
loop {
	if m == 0
		break
	end
	loop.with_index { |_, i|
		if c(i, k) >= m
			m -= c(i - 1, k)
			k -= 1
			n += 1<<(i - 1)
			break
		end
	}
}

puts n


You are given two integers $$$n$$$ and $$$k$$$.Your task is to construct such a string $$$s$$$ of length $$$n$$$ that for each $$$i$$$ from $$$1$$$ to $$$k$$$ there is at least one $$$i$$$-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minimal frequency of some letter (the frequency of a letter is the number of occurrences of this letter in a string). If there are several possible answers, you can print any.You have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of queries. The next $$$t$$$ lines are contain queries, one per line. The $$$i$$$-th line contains two integers $$$n_i$$$ and $$$k_i$$$ ($$$1 \le n_i \le 100, 1 \le k_i \le min(n_i, 26)$$$) — the length of the string in the $$$i$$$-th query and the number of characters in the $$$i$$$-th query.

Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: any string $$$s_i$$$ satisfying the conditions in the problem statement with constraints from the $$$i$$$-th query.

NoteIn the first example query the maximum possible minimal frequency is $$$2$$$, it can be easily seen that the better answer doesn't exist. Other examples of correct answers: "cbcabba", "ccbbaaa" (any permutation of given answers is also correct).In the second example query any permutation of first four letters is acceptable (the maximum minimal frequency is $$$1$$$).In the third example query any permutation of the given answer is acceptable (the maximum minimal frequency is $$$3$$$).

gets
$<.each{|e|n,k=e.split.map &:to_i;puts n.times.map{|i|(97+i%k).chr}*''}

ALPHA = ('a'..'z').to_a
def solution
  count = read_int
  count.times do
    n, k = read_ints
    puts ALPHA[0...k].cycle.first(n).join("")
  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']

# Functions
def handle(n, k)
  sample = ""
  k.times { |i| sample << (97 + i).chr }
  s = sample * (n / k)
  s << sample.slice(0, n % k)
  return s
end

# MAIN
t = gets.to_i # 1 <= t <= 100

t.times do |i|
  str = gets.split(" ")
  n = str[0].to_i # 1 <= n <= 100
  k = str[1].to_i # 1 <= k <= min(n_i, 26)
  puts handle(n, k)
end

t = gets.chomp.to_i
alph = "abcdefghijklmnopqrstuvwxyz"
t.times do |testcase|
  (n,k) = gets.split.map(&:to_i)
  cur = 0
  res = ""
  n.times do |i|
    if cur == k
      cur = 0
    end
    res<<alph[cur]
    cur+=1
  end
  puts res
end

alp_arr = ('a'..'z').to_a
gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  rep = n / k
  mod = n % k
  ans = alp_arr[0..k-1].join * rep
  if mod > 0
    ans += alp_arr[0..mod-1].join
  end
  puts ans
end

n = gets.to_i
(1..n).each do |i|
  a, b = gets.split.map(&:to_i)
  puts (('a'..('a'.ord + b - 1).chr).to_a.join * 100)[0..a - 1]
end

s = "abcdefghijklmnopqrstuvwxyz"
gets.to_i.times do
    n,k = gets.split.map(&:to_i)
    ans = ""
    (n/k).times do
        ans += s[0,k]
    end
    ans += s[0,n%k]
    puts ans
end

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

def solution(n, k)
  s = ""
  j = 0
  n.times do |i|
    s += ((i % k) + 97).chr
  end
  return s
end

q = gets.chomp.to_i
q.times do
  n, k = gets.chomp.split(" ").map(&:to_i)
  puts solution(n, k)
end

t = gets.to_i
t.times do
    n, k = gets.split.map(&:to_i)
    s = ''
    i = 0
    n.times do
        s += ('a'.ord + i).chr
        i += 1
        i %= k
    end
    puts s
end

#

def f(n,k)
    code_a=97
    ans=[]
    for i in 0..n-1
        ans<<i%k+code_a
    end
    ans=ans.pack("C*")
    print(ans,"\n")
end

m=gets().to_i
for i in 1..m
    n,k=gets.chomp().split(" ").map(&:to_i)
    f(n,k)
end

n = gets.to_i
(1..n).each do |i|
  a, b = gets.split.map(&:to_i)
  puts (('a'..('a'.ord + b).chr).to_a.join * 100)[0..a]
end

n = gets.to_i
(1..n).each do |i|
  a, b = gets.split.map(&:to_i)
  puts (('a'..('a'.ord + b).chr).to_a.join * 100)[0..a - 1]
end

#

def f(n,k)
    code_a=97
    ans=[]
    for i in 0..n-1
        ans<<i%k+code_a
    end
    ans=ans.pack("C*")
    p ans
end

m=gets().to_i
for i in 1..m
    n,k=gets.chomp().split(" ").map(&:to_i)
    f(n,k)
end


You are given matrix with n rows and n columns filled with zeroes. You should put k ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal.One matrix is lexicographically greater than the other if the first different number in the first different row from the top in the first matrix is greater than the corresponding number in the second one.If there exists no such matrix then output -1.

The first line consists of two numbers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 106).

If the answer exists then output resulting matrix. Otherwise output -1.

#!/usr/bin/ruby
n,k=gets.split.map(&:to_i)
if n*n<k
	p -1
	exit
end
a=n.times.map{[0]*n}
(0...n).each{|i|
	if k>0
		a[i][i]=1
		k-=1
	end
	(i+1...n).each{|j|
		if k>1
			a[i][j]=a[j][i]=1
			k-=2
		end
	}
}
puts a.map{|e|e*' '}

#!/usr/bin/ruby
n,k=gets.split.map(&:to_i)
if n*n<k
	p -1
	exit
end
a=n.times.map{[0]*n}
(0...n).each{|i|
	(i+1...n).each{|j|
		if k>1
			a[i][j]=a[j][i]=1
			k-=2
		end
	}
}
(0...n).each{|i|
	if k>0
		a[i][i]=1
		k-=1
	end
}
puts a.map{|e|e*' '}


Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times:  he chooses two elements of the array ai, aj (i ≠ j);  he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai = ai + 1 and aj = aj - 1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.

The first line contains integer n (1 ≤ n ≤ 105) — the array size. The second line contains space-separated integers a1, a2, ..., an (|ai| ≤ 104) — the original array.

Print a single integer — the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.

gets.chomp
sum = 0
a = gets.chomp.split(" ").map {|x| x.to_i}.sort
for i in a
  sum += i
end
if sum % a.length == 0
  puts a.length
else
  puts a.length - 1
end

n=gets.to_i
sum=0
gets.split.map(&:to_i).each{|el|sum+=el}
(n==1) ?  (puts 1) : ((sum%n ==0)? ( puts n) : (puts n-1))

n = gets.chomp.to_i
a = gets.chomp.split(" ").map{|n| n.to_i}
sum = a.inject{|sum, n| sum += n}

if sum % n == 0
  puts n
else
  puts [n - 1, 1].max
end

n = gets.to_i
a = gets.split.map(&:to_i)
s = a.inject(:+) / n
puts a.inject(0) {|acc, x| acc + x - s }.zero? ? n : n-1

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
if a.inject(0){|sum,i| sum+i}%n == 0
    puts n
else
    puts n-1
end

n = gets.to_i
a = gets.split.map &:to_i
sum = a.inject{|sum, el| sum+el}
puts sum%n==0 ? n : n-1

n = gets.to_i
a = gets.split.map { |x| x.to_i }
puts(a.inject(:+) % n == 0 ? n : n - 1)

n = gets.to_i
a = gets.split.collect{|x| x.to_i}

sum = 0
a.each{|x| sum += x}

if sum % n == 0
	puts n
else
	puts n-1
end

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

sum = a.reduce(:+)
if sum % n == 0
	puts n
else
	puts n - 1
end

sum = 0
gets.chomp
min = 100000
check = false
a = gets.chomp.split(" ").each {|x|
  x = x.to_i
  sum += x
  min = x if x < min
  if x < 0
    check = true
  end
}
sum += -min * a.length if check
if sum / a.length == 0
  puts a.length
else
  puts sum / a.length
end

sum = 0
gets.chomp
min = 100000
check = false
a = gets.chomp.split(" ").each {|x|
  x = x.to_i
  sum += x
  min = x if x < min
  if x < 0
    check = true
  end
}
sum += -min * a.length if check
if sum % a.length == 0
  puts a.length
else
  puts sum / a.length
end

sum = 0
gets.chomp
gets.chomp.split(" ").each {|x| sum += x.to_i}
puts sum / 2

n=gets.to_i
sum=0
gets.split.map(&:to_i).each{|el|sum+=el}
puts sum/2

n = gets.to_i
a = gets.split.map(&:to_i).sort
while a[-1]-a[0] >= 2 do
  a[0]+=1; a[-1]-=1; a.sort!
  #p a
end
p a.uniq.map {|x| a.count(x) }.inject(:+)-1

n = gets.to_i
a = gets.split.map(&:to_i).sort
while a[-1]-a[0] >= 2 do
  a[0]+=1; a[-1]-=1; a.sort!
end
puts a.uniq.map {|x| a.count(x) }.max


You have $$$n$$$ stacks of blocks. The $$$i$$$-th stack contains $$$h_i$$$ blocks and it's height is the number of blocks in it. In one move you can take a block from the $$$i$$$-th stack (if there is at least one block) and put it to the $$$i + 1$$$-th stack. Can you make the sequence of heights strictly increasing?Note that the number of stacks always remains $$$n$$$: stacks don't disappear when they have $$$0$$$ blocks.

First line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4)$$$ — the number of test cases. The first line of each test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 100)$$$. The second line of each test case contains $$$n$$$ integers $$$h_i$$$ $$$(0 \leq h_i \leq 10^9)$$$ — starting heights of the stacks. It's guaranteed that the sum of all $$$n$$$ does not exceed $$$10^4$$$.

For each test case output YES if you can make the sequence of heights strictly increasing and NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).

NoteIn the first test case there is no need to make any moves, the sequence of heights is already increasing.In the second test case we need to move one block from the first stack to the second. Then the heights become $$$0$$$ $$$1$$$.In the third test case we could move one block from the first stack to the second and then from the second to the third, which would make the heights $$$3$$$ $$$4$$$ $$$5$$$.In the fourth test case we can't make a move, but the sequence is not increasing, so the answer is NO.In the fifth test case we can only make one move (from the second to the third stack), which would make the heights $$$0$$$ $$$0$$$ $$$1$$$. Both $$$0$$$ $$$1$$$ $$$0$$$ and $$$0$$$ $$$0$$$ $$$1$$$ are not increasing sequences, so the answer is NO.

gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    need, cur, ok = 0, 0, true
    n.times do |i|
        need += i
        cur += a[i]
        ok = false if cur < need
    end
    puts ok ? "YES" : "NO"
end

cases = gets.chomp.to_i

cases.times do |i|
  n = gets.chomp.to_i
  hs = gets.chomp.split(" ").map(&:to_i)

  failed = false
  hs.each_with_index do |h, idx|
    if h < idx
      failed = true
      break
    else
      hs[(idx + 1)] += h - idx if hs[(idx + 1)]
    end
  end

  puts failed ? "NO" : "YES"
end

gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    n, h, res = 0, 0, true
    n.times do |i|
        n += i
        h += a[i]
        res = false if h < n
    end
    puts res ? "YES" : "NO"
end


You are walking through a parkway near your house. The parkway has $$$n+1$$$ benches in a row numbered from $$$1$$$ to $$$n+1$$$ from left to right. The distance between the bench $$$i$$$ and $$$i+1$$$ is $$$a_i$$$ meters.Initially, you have $$$m$$$ units of energy. To walk $$$1$$$ meter of distance, you spend $$$1$$$ unit of your energy. You can't walk if you have no energy. Also, you can restore your energy by sitting on benches (and this is the only way to restore the energy). When you are sitting, you can restore any integer amount of energy you want (if you sit longer, you restore more energy). Note that the amount of your energy can exceed $$$m$$$.Your task is to find the minimum amount of energy you have to restore (by sitting on benches) to reach the bench $$$n+1$$$ from the bench $$$1$$$ (and end your walk).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$; $$$1 \le m \le 10^4$$$). The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the distance between benches $$$i$$$ and $$$i+1$$$.

For each test case, print one integer — the minimum amount of energy you have to restore (by sitting on benches) to reach the bench $$$n+1$$$ from the bench $$$1$$$ (and end your walk) in the corresponding test case.

NoteIn the first test case of the example, you can walk to the bench $$$2$$$, spending $$$1$$$ unit of energy, then restore $$$2$$$ units of energy on the second bench, walk to the bench $$$3$$$, spending $$$2$$$ units of energy, restore $$$1$$$ unit of energy and go to the bench $$$4$$$.In the third test case of the example, you have enough energy to just go to the bench $$$6$$$ without sitting at all.

gets.to_i.times do
    n, m = gets.split.map(&:to_i)
    puts [gets.split.map(&:to_i).sum - m, 0].max
end

gets.to_i.times do
    n, m = gets.split.map(&:to_i)
    puts([gets.split.map(&:to_i).sum - m, 0].max)
end

gets.to_i.times do
    n, m = gets.split.map(&:to_i)
    x = 0
    w = gets.split.map(&:to_i)
    for item in w
        x += item
    end
    puts((x <= m )? 0 : x - m)
end

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  as = gets.split.map(&:to_i)
  p [as.sum - m, 0].max
end

def solve(xs, m)
   total = xs.sum
   [total - m, 0].max
end

t = gets.chomp.to_i

results = []

t.times do
    n, m = gets.chomp.split.map(&:to_i)
    xs = gets.chomp.split.map(&:to_i)
    results << solve(xs, m)
end

puts results

t = gets.to_i

t.times do
  n, m = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)

  ans = 0
  n.times do |i|
    if a[i] > m
      ans += a[i]-m
      m += a[i]-m
    end

    m -= a[i]
  end

  puts ans
end

gets.to_i.times do
  n,m = gets.chomp.split.map(&:to_i)
  a = gets.chomp.split.map(&:to_i)
  ans = 0
  puts [a.reduce(:+) - m,0].max
end


AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays $$$a$$$ and $$$b$$$, both consist of $$$n$$$ non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero):  She chooses two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$), then decreases the $$$i$$$-th element of array $$$a$$$ by $$$1$$$, and increases the $$$j$$$-th element of array $$$a$$$ by $$$1$$$. The resulting values at $$$i$$$-th and $$$j$$$-th index of array $$$a$$$ are $$$a_i - 1$$$ and $$$a_j + 1$$$, respectively. Each element of array $$$a$$$ must be non-negative after each operation. If $$$i = j$$$ this operation doesn't change the array $$$a$$$. AquaMoon wants to make some operations to make arrays $$$a$$$ and $$$b$$$ equal. Two arrays $$$a$$$ and $$$b$$$ are considered equal if and only if $$$a_i = b_i$$$ for all $$$1 \leq i \leq n$$$.Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays $$$a$$$ and $$$b$$$ equal.Please note, that you don't have to minimize the number of operations.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 100$$$). The sum of all $$$a_i$$$ does not exceed $$$100$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \leq b_i \leq 100$$$). The sum of all $$$b_i$$$ does not exceed $$$100$$$.

For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer $$$m$$$ ($$$0 \leq m \leq 100$$$) in the first line — the number of operations. Then print $$$m$$$ lines, each line consists of two integers $$$i$$$ and $$$j$$$ — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with $$$m \leq 100$$$. If there are multiple possible solutions, you can print any.

NoteIn the first example, we do the following operations:  $$$i = 2$$$, $$$j = 1$$$: $$$[1, 2, 3, 4] \rightarrow [2, 1, 3, 4]$$$;  $$$i = 3$$$, $$$j = 1$$$: $$$[2, 1, 3, 4] \rightarrow [3, 1, 2, 4]$$$; In the second example, it's impossible to make two arrays equal.

def read_array()
  gets.split(" ").map { |s| s.to_i  }
end
t = gets.to_i
for z in 1..t
  n = gets.to_i
  a, b = read_array, read_array
  m, p = [], []
  for i in 0...n
    x = a[i] - b[i]
    if a[i] > b[i]
      m << [i + 1, a[i] - b[i]]
    elsif a[i] < b[i]
      p << [i + 1, b[i] - a[i]]
    end
  end
  res = []
  while p.length() > 0 && m.length() > 0
    x = [p[-1][1], m[-1][1]].min
    p[-1][1] -= x
    m[-1][1] -= x
    while x > 0
      x -= 1
      res << [m[-1][0], p[-1][0]]
    end
    if p[-1][1] == 0
      p.pop()
    end
    if m[-1][1] == 0
      m.pop()
    end
  end
  if p.length() != 0 || m.length() != 0
    puts(-1)
    next
  end
  puts res.length()
  for i in res
      puts i[0].to_s + ' ' + i[1].to_s
  end
end

def solve(a, b)
  return -1 unless a.reduce(&:+) == b.reduce(&:+)
  ans = []
  0.upto (a.size - 1) do |i|
    if a[i] < b[i]
      diff = b[i] - a[i]
      for j in (i+1)..(a.size - 1) do
        break if diff == 0
        next if a[j] < b[j]
        cnt = [diff, a[j] - b[j]].min
        cnt.times do
          ans << [j+1, i+1]
          diff -= 1
          a[i] += 1
          a[j] -= 1
        end
      end

    elsif a[i] > b[i]
      diff = a[i] - b[i]
      for j in (i+1)..(a.size - 1) do
        break if diff == 0
        next if a[j] > b[j]
        cnt = [diff, b[j] - a[j]].min
        cnt.times do
          ans << [i+1, j+1]
          diff -= 1
          a[i] -= 1
          a[j] += 1
        end
      end
    end
  end

  ans
end

t = gets.chomp.to_i
t.times do
  gets
  a = gets.chomp.split(' ').map(&:to_i)
  b = gets.chomp.split(' ').map(&:to_i)

  ans = solve(a, b)
  if ans == -1
    puts "-1\n"
  else
    puts "#{ans.size}\n"
    for i, j in ans do
      puts "#{i} #{j}\n"
    end
  end
end


Ever since Kalevitch, a famous Berland abstractionist, heard of fractals, he made them the main topic of his canvases. Every morning the artist takes a piece of graph paper and starts with making a model of his future canvas. He takes a square as big as n × n squares and paints some of them black. Then he takes a clean square piece of paper and paints the fractal using the following algorithm: Step 1. The paper is divided into n2 identical squares and some of them are painted black according to the model.Step 2. Every square that remains white is divided into n2 smaller squares and some of them are painted black according to the model.Every following step repeats step 2.  Unfortunately, this tiresome work demands too much time from the painting genius. Kalevitch has been dreaming of making the process automatic to move to making 3D or even 4D fractals.

The first line contains integers n and k (2 ≤ n ≤ 3, 1 ≤ k ≤ 5), where k is the amount of steps of the algorithm. Each of the following n lines contains n symbols that determine the model. Symbol «.» stands for a white square, whereas «*» stands for a black one. It is guaranteed that the model has at least one white square.

Output a matrix nk × nk which is what a picture should look like after k steps of the algorithm.

def gao(i, j, m, n)
	m /= n
	m > 0 && ($a[i / m][j / m] == '*' || gao(i % m, j % m, m, n))
end

I = open('input.txt')
O = open('output.txt', 'w')
n, k = I.gets.split.map(&:to_i)
$a = n.times.map{I.gets}
m = n ** k
O.puts m.times.map{|i| m.times.map{|j| gao(i, j, m, n) ? '*' : '.'} * ''} * "\n"

#!/usr/bin/env ruby

open("input.txt"){|f|open("output.txt","w"){|g|

n, k = f.gets.split.map(&:to_i)
t = n.times.map { f.gets.chomp }

(n**k).times do |ii|
  (n**k).times do |jj|
    i, j = ii, jj
    result = '.'
    k.times do
      if t[i % n][j % n] == '*'
        result = '*'
        break
      end
      i /= n
      j /= n
    end
    g.print result
  end
  g.puts
end
}}

def rec_paint(canvas,shape,x1,y1,x2,y2,n,dim)
	scale=n**dim
	if dim==0
		0.upto(n-1){|y|
		0.upto(n-1){|x|
			#puts"%d %d, %d %d"%[y1+y,x1+x,y,x]
			canvas[y1+y][x1+x]=shape[y][x]
		}}
	else
		0.upto(n-1){|y|
		0.upto(n-1){|x|
			xx1=x1+scale*x
			yy1=y1+scale*y
			xx2=xx1+n-1
			yy2=yy1+n-1
			rec_paint(canvas,shape,xx1,yy1,xx2,yy2,n,dim-1) unless shape[y][x]==:*
		}}

	end
end
f,g=open("input.txt","r"),open("output.txt","w")
#f,g=$stdin,$stdout
n,k=f.gets.split.map(&:to_i)
scale=n**k
shape=[]
n.times{shape<<f.gets.chomp.split(//).map(&:to_sym)}
canvas=(1..n**k).map{[nil]*(n**k)}
rec_paint(canvas,shape,0,0,scale-1,scale-1,n,k-1)
g.puts(canvas.map{|syms|syms.map{|sym|sym ? sym.to_s : :*}*""}*$/)
f.close
g.close


Hiking club "Up the hill" just returned from a walk. Now they are trying to remember which hills they've just walked through.It is known that there were N stops, all on different integer heights between 1 and N kilometers (inclusive) above the sea level. On the first day they've traveled from the first stop to the second stop, on the second day they've traveled from the second to the third and so on, and on the last day they've traveled from the stop N - 1 to the stop N and successfully finished their expedition.They are trying to find out which heights were their stops located at. They have an entry in a travel journal specifying how many days did they travel up the hill, and how many days did they walk down the hill.Help them by suggesting some possible stop heights satisfying numbers from the travel journal.

In the first line there is an integer non-negative number A denoting the number of days of climbing up the hill. Second line contains an integer non-negative number B — the number of days of walking down the hill (A + B + 1 = N, 1 ≤ N ≤ 100 000).

Output N space-separated distinct integers from 1 to N inclusive, denoting possible heights of the stops in order of visiting.

#!usr/bin/env ruby

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

up = gets.to_i
i = down = gets.to_i

max = up + down + 1

answer = ""

answer << "#{current = max - up} "

while i != 0 do
  answer << "#{current -= 1} "
  i -= 1
end

current += down

while up != 0 do
  answer << "#{current += 1} "
  up -= 1
end

puts answer

a = gets.to_i
b = gets.to_i
c = b + 1
print "#{c} "
a.times do
  c += 1
  print "#{c} "
end
c = b
b.times do
  print "#{c} "
  c -= 1
end

up = Integer gets
down = Integer gets
height = up + down + 1
arry = []
arry[up] = height
for i in 0..up-1
  if i == 0
    arry[0] = 1
  else
    arry[i] = arry[i-1]+1
  end
end

for j in up+1..down+up
  arry[j] = arry[j-1]-1
end

for k in 0..down+up-1
  printf("#{arry[k]} ")
end
puts arry[down+up]

a = gets.to_i
b = gets.to_i
c = 100000
print "#{c} "
a.times do
  c += 1
  print "#{c} "
end
b.times do
  c -= 1
  print "#{c} "
end

a = gets.to_i
b = gets.to_i
c = b + 1
print "#{c} "
a.times do
  c += 1
  print "#{c} "
end
b.times do
  c -= 1
  print "#{c} "
end

up = Integer gets
down = Integer gets
height = up + down + 1
arry = []
if up > down
  arry[0] = 1
  arry[1] =3
  for i in 2..up
    arry[i] = arry[i-1]+1
  end
  for j in up+1..down+up
    arry[j] = arry[j-1]-1
    arry[j] = arry[j] == 3 ? 2 : arry[j]
  end
else
  arry[0] = 2
  for i in 1..up
    arry[i] = arry[i-1]+1
  end

  for j in up+1..down+up
    arry[j] = arry[j-1]-1
    arry[j] = arry[j] == 2 ? 1 : arry[j]
  end
end

for k in 0..down+up-1
  printf("#{arry[k]} ")
end
puts arry[down+up]

up = Integer gets
down = Integer gets
height = up + down + 1
arry = []
if up > down
  arry[0] = 1
  arry[1] =3
  for i in 2..up
    arry[i] = arry[i-1]+1
  end
  for j in up+1..down+up
    arry[j] = arry[j-1]-1
  end
else
  arry[0] = 2
  for i in 1..up
    arry[i] = arry[i-1]+1
  end
  for j in up+1..down+up
    arry[j] = arry[j-1]-1
  end
end

for k in 0..down+up-1
  printf("#{arry[k]} ")
end
puts arry[down+up]


Luis has a sequence of $$$n+1$$$ integers $$$a_1, a_2, \ldots, a_{n+1}$$$. For each $$$i = 1, 2, \ldots, n+1$$$ it is guaranteed that $$$0\leq a_i < n$$$, or $$$a_i=n^2$$$. He has calculated the sum of all the elements of the sequence, and called this value $$$s$$$. Luis has lost his sequence, but he remembers the values of $$$n$$$ and $$$s$$$. Can you find the number of elements in the sequence that are equal to $$$n^2$$$?We can show that the answer is unique under the given constraints.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$). Description of the test cases follows. The only line of each test case contains two integers $$$n$$$ and $$$s$$$ ($$$1\le n< 10^6$$$, $$$0\le s \le 10^{18}$$$). It is guaranteed that the value of $$$s$$$ is a valid sum for some sequence satisfying the above constraints.

For each test case, print one integer — the number of elements in the sequence which are equal to $$$n^2$$$.

NoteIn the first test case, we have $$$s=0$$$ so all numbers are equal to $$$0$$$ and there isn't any number equal to $$$49$$$.In the second test case, we have $$$s=1$$$. There are two possible sequences: $$$[0, 1]$$$ or $$$[1, 0]$$$. In both cases, the number $$$1$$$ appears just once. In the third test case, we have $$$s=12$$$, which is the maximum possible value of $$$s$$$ for this case. Thus, the number $$$4$$$ appears $$$3$$$ times in the sequence.

t=gets.chomp.to_i

t.times do |i|
    ns=gets.chomp.split

    n=ns[0]
    s=ns[1]

    if(n.to_i<=s.to_i)
        puts s.to_i/((n.to_i)**2)
    else
        puts 0
    end
end


A club plans to hold a party and will invite some of its $$$n$$$ members. The $$$n$$$ members are identified by the numbers $$$1, 2, \dots, n$$$. If member $$$i$$$ is not invited, the party will gain an unhappiness value of $$$a_i$$$.There are $$$m$$$ pairs of friends among the $$$n$$$ members. As per tradition, if both people from a friend pair are invited, they will share a cake at the party. The total number of cakes eaten will be equal to the number of pairs of friends such that both members have been invited.However, the club's oven can only cook two cakes at a time. So, the club demands that the total number of cakes eaten is an even number.What is the minimum possible total unhappiness value of the party, respecting the constraint that the total number of cakes eaten is even?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq \min(10^5,\frac{n(n-1)}{2})$$$) — the number of club members and pairs of friends. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \dots,a_n$$$ ($$$0 \leq a_i \leq 10^4$$$) — the unhappiness value array. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x,y \leq n$$$, $$$x \neq y$$$) indicating that $$$x$$$ and $$$y$$$ are friends. Each unordered pair $$$(x,y)$$$ appears at most once in each test case. It is guaranteed that both the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.

For each test case, print a line containing a single integer – the minimum possible unhappiness value of a valid party.

NoteIn the first test case, all members can be invited. So the unhappiness value is $$$0$$$.In the second test case, the following options are possible:   invite $$$1$$$ and $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$);  invite $$$2$$$ and $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$2$$$);  invite only $$$1$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$4$$$);  invite only $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$5$$$);  invite only $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$);  invite nobody ($$$0$$$ cakes eaten, unhappiness value equal to $$$6$$$).  The minimum unhappiness value is achieved by inviting $$$2$$$ and $$$3$$$.In the third test case, inviting members $$$3,4,5$$$ generates a valid party with the minimum possible unhappiness value.

def main
  t = inp.to_i
  t.times do
    n, m =  mapint(inarr)
    a = mapint(inarr)
    gp = Array.new(n){ Array.new(0) }
    m.times do |i|
      x, y = mapint(inarr)
      x-=1
      y-=1
      gp[x].push y
      gp[y].push x
    end

    if m & 1 == 0
      puts 0
      next
    end

    minct = 99999999
    n.times do |i|
      if gp[i].length & 1 == 1
        minct = min(minct, a[i])
      else
        gp[i].each do |e|
          if gp[e].length & 1 == 0
            minct = min(minct, a[i] + a[e])
          end
        end
      end
    end
    puts minct

  end

end

# lib
def inp
  gets.chomp
end

def inarr
  gets.chomp.split
end

def mapint(lst)
  lst.map(&:to_i)
end

def max(a, b)
  (a > b)? a:b
end

def min(a, b)
  (a < b)? a:b
end

main


Polycarp wants to cook a soup. To do it, he needs to buy exactly $$$n$$$ liters of water.There are only two types of water bottles in the nearby shop — $$$1$$$-liter bottles and $$$2$$$-liter bottles. There are infinitely many bottles of these two types in the shop.The bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles correspondingly.Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles. You also have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. The next $$$q$$$ lines contain queries. The $$$i$$$-th query is given as three space-separated integers $$$n_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \le n_i \le 10^{12}, 1 \le a_i, b_i \le 1000$$$) — how many liters Polycarp needs in the $$$i$$$-th query, the cost (in burles) of the bottle of the first type in the $$$i$$$-th query and the cost (in burles) of the bottle of the second type in the $$$i$$$-th query, respectively.

Print $$$q$$$ integers. The $$$i$$$-th integer should be equal to the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n_i$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a_i$$$ burles and the bottle of the second type costs $$$b_i$$$ burles.

gets.to_i.times do
	n, a, b = gets.split.map(&:to_i)
	p [a * n, b * (n / 2) + a * (n % 2)].min
end

def solution
  q = read_int

  q.times do
    n, a, b = read_ints

    one_liter = n * a
    two_liter = (n / 2) * b + (n.odd? ? a : 0)

    p [one_liter, two_liter].min

  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']

q = gets.to_i
ans = 0
q.times do
  n, a, b = gets.split.map(&:to_i)
  if a <= b / 2
    puts n * a
  else
    puts (n/2) * b + (n - (n/2*2)) * a
  end
end

q = gets.strip.to_i
q.times do
  n, a, b = gets.strip.split.map(&:to_i)
  first = n * a
  second = (n / 2) * b
  second += a if n.odd?
  ans = [first, second].min
  puts ans
end

DBG = true
q = gets.to_i
for i in 0...q
  n,a,b = gets.split.map{|z| z.to_i}
  if 2*a <= b
    puts "#{n*a}"
  else
    puts "#{b*(n/2)+a*(n%2)}"
  end
end

gets.to_i.times do
    n,a,b = gets.split.map(&:to_i)
    if a*2 < b
        puts n*a
    else
        puts n/2*b+(n%2)*a
    end
end

def solve(n,a,b)
 [n*(a),b*(n/2) + a*(n%2)].min
 end
t = gets.to_i
t.times{
n,a,b = gets.split(" ").map(&:to_i)
puts solve(n,a,b)
}

# n - required amount of water (in liters)
# a - 1L bottle cost
# b - 2L bottle cost
def price(n, a, b)
  if 2 * a <= b
    n * a
  else
    n / 2 * b + n % 2 * a
  end
end

def respond_n_queries(n)
  n.times do
    n, a, b = gets.chomp.split.map(&:to_i)
    puts price(n, a, b)
  end
end

queries = gets.to_i
respond_n_queries(queries)

def solve(n,a,b)
 ans = 0
 if(n==1)
  return a
  end
 if(b<=a)
  if(n%2==0)
    return b*(n/2)
  end
  return b*(n/2)+a
 end
 return a*n
 end

t = gets.to_i

t.times{

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

puts solve(n,a,b)

}

# n - required amount of water (in liters)
# a - 1L bottle cost
# b - 2L bottle cost
def price(n, a, b)
  if a <= b
    n * a
  else
    n / 2 * b + n % 2 * a
  end
end

def respond_n_queries(n)
  n, a, b = gets.chomp.split.map(&:to_i)
  puts price(n, a, b)
end

queries = gets.to_i
respond_n_queries(queries)

# n - required amount of water (in liters)
# a - 1L bottle cost
# b - 2L bottle cost
def price(n, a, b)
  if a <= 2 * b
    n * a
  else
    n / 2 * b + n % 2 * a
  end
end

def respond_n_queries(n)
  n.times do
    n, a, b = gets.chomp.split.map(&:to_i)
    puts price(n, a, b)
  end
end

queries = gets.to_i
respond_n_queries(queries)

# n - required amount of water (in liters)
# a - 1L bottle cost
# b - 2L bottle cost
def price(n, a, b)
  if a <= b
    n * a
  else
    n / 2 * b + n % 2 * a
  end
end

def respond_n_queries(n)
  n.times do
    n, a, b = gets.chomp.split.map(&:to_i)
    puts price(n, a, b)
  end
end

queries = gets.to_i
respond_n_queries(queries)


An array of integers $$$p_1, p_2, \dots, p_n$$$ is called a permutation if it contains each number from $$$1$$$ to $$$n$$$ exactly once. For example, the following arrays are permutations: $$$[3, 1, 2]$$$, $$$[1]$$$, $$$[1, 2, 3, 4, 5]$$$ and $$$[4, 3, 1, 2]$$$. The following arrays are not permutations: $$$[2]$$$, $$$[1, 1]$$$, $$$[2, 3, 4]$$$.Polycarp invented a really cool permutation $$$p_1, p_2, \dots, p_n$$$ of length $$$n$$$. It is very disappointing, but he forgot this permutation. He only remembers the array $$$q_1, q_2, \dots, q_{n-1}$$$ of length $$$n-1$$$, where $$$q_i=p_{i+1}-p_i$$$.Given $$$n$$$ and $$$q=q_1, q_2, \dots, q_{n-1}$$$, help Polycarp restore the invented permutation.

The first line contains the integer $$$n$$$ ($$$2 \le n \le 2\cdot10^5$$$) — the length of the permutation to restore. The second line contains $$$n-1$$$ integers $$$q_1, q_2, \dots, q_{n-1}$$$ ($$$-n < q_i < n$$$).

Print the integer -1 if there is no such permutation of length $$$n$$$ which corresponds to the given array $$$q$$$. Otherwise, if it exists, print $$$p_1, p_2, \dots, p_n$$$. Print any such permutation if there are many of them.

N = gets.to_i
Q = gets.split.map &:to_i
ps = [0]
Q.each{ |q| ps << (ps[-1] + q) }
mx = ps.max
mn = ps.min
if mx - mn == N-1 && ps.uniq.size == N
  puts ps.map{ |r| r - mn + 1 }.join(" ")
else
  p -1
end

n = gets.to_i
a = gets.split.map(&:to_i)
b = Array.new(n,0)
for i in 1..n-1
    b[i] = b[i-1]+a[i-1]
end
mn = b.min
for i in 0..n-1
    b[i] -= mn-1
end
c = Hash.new(false)
for i in 0..n-1
    if c[b[i]] || b[i] > n
        puts -1
        exit
    end
    c[b[i]] = true
end
puts b.join(" ")

def main
  n = gets.chomp.to_i
  q = gets.chomp.split.map(&:to_i)

  qp = [0]
  for k in q
    qp << qp.last + k
  end

  diff = 1 - qp.min
  result = []
  visited = {}
  for k in qp
    if k + diff < 1 or k + diff > n or visited.key?(k + diff)
      puts -1
      return
    else
      result << k + diff
      visited[k + diff] = true
    end
  end

  puts result.join(" ")
end

main

n = gets.to_i
a = gets.split.map(&:to_i)
b = Array.new(n,0)
for i in 1..n-1
    b[i] = b[i-1]+a[i-1]
end
mn = b.min
for i in 0..n-1
    b[i] -= mn-1
end
c = Hash.new(false)
for i in 0..n-1
    if c[b[i]] || b[i] > n
        puts -1
        exit
    end
end
puts b.join(" ")

def main
  n = gets.chomp.to_i
  q = gets.chomp.split.map(&:to_i)

  diff = q.inject(0) { |sum, x| sum + x }
  for i in (1..n)
    next if i + diff < 1 or i + diff > n

    visited = {i => true, i + diff => true}
    result = [i]

    for j in q
      x = result.last + j
      break if x < 1 or x > n or visited.key?(x)
      visited[x] = true
      result << x
    end

    result << i + diff
    if result.length == n
      puts result.join(" ")
      return
    end
  end

  puts -1
end

main

def main
  n = gets.chomp.to_i
  q = gets.chomp.split.map(&:to_i)

  diff = q.inject(0) { |sum, x| sum + x }
  for i in (1..n)
    next if i + diff < 1 or i + diff > n

    visited = {i => true, i + diff => true}
    result = [i]

    for j in q
      x = result.last + j
      break if x < 1 or x > n or visited.key?(x)
      visited[x] = true
      result << x
    end

    result << i + diff
    break if visited.key?(i + diff)

    if result.length == n
      puts result.join(" ")
      return
    end
  end

  puts -1
end

main

def main
  n = gets.chomp.to_i
  q = gets.chomp.split.map(&:to_i)

  diff = q.last - q.first
  for i in (1..n)
    visited = {i => true, i + diff => true}
    result = [i]

    for j in q
      x = result.last + j
      break if x < 1 or visited.key?(x)
      visited[x] = true
      result << x
    end

    if result.length == n
      puts result.join(" ")
      return
    end
  end

  puts -1
end

main


There is a house with $$$n$$$ flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i = 1$$$ if in the $$$i$$$-th flat the light is on and $$$a_i = 0$$$ otherwise.Vova thinks that people in the $$$i$$$-th flats are disturbed and cannot sleep if and only if $$$1 < i < n$$$ and $$$a_{i - 1} = a_{i + 1} = 1$$$ and $$$a_i = 0$$$.Vova is concerned by the following question: what is the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number $$$k$$$.

The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of flats in the house. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$a_i \in \{0, 1\}$$$), where $$$a_i$$$ is the state of light in the $$$i$$$-th flat.

Print only one integer — the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the light then nobody will be disturbed.

NoteIn the first example people from flats $$$2$$$ and $$$7$$$ or $$$4$$$ and $$$7$$$ can turn off the light and nobody will be disturbed. It can be shown that there is no better answer in this example.There are no disturbed people in second and third examples.

n = gets.strip.to_i
flats = gets.strip.gsub(' ', '')
k = 0
until !flats.include?("10101")
  flats.sub!("10101", "10001")
  k += 1
end

until !flats.include?("101")
  flats.sub!("101", "100")
  k += 1
end
puts k

n = gets.to_i
a = gets.split.map(&:to_i)
ans = 0
for i in 2..n-1
    if a[i] == 1 && a[i-1] == 0 && a[i-2] == 1
        ans += 1
        a[i] = 0
    end
end
puts ans


Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.

The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.

Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".

na = gets.to_i
a = gets.split.map &:to_i
nb = gets.to_i
b = gets.split.map &:to_i
i = 0; j = 0; ans = 0

def answer(r)
	puts r
	exit
end

while true
	if a[i] == b[j]
		i += 1
		j += 1
		ans += 1
		if i == na
			answer j == nb ? ans : -1
		elsif j == nb
			answer -1
		end
	elsif a[i] < b[j]
		answer -1 if i+1 == na
		a[i+1] += a[i]
		i += 1
	else
		answer -1 if j+1 == nb
		b[j+1] += b[j]
		j += 1
	end
end


One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y):   point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y  point (x', y') is (x, y)'s left neighbor, if x' < x and y' = y  point (x', y') is (x, y)'s lower neighbor, if x' = x and y' < y  point (x', y') is (x, y)'s upper neighbor, if x' = x and y' > y We'll consider point (x, y) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.

The first input line contains the only integer n (1 ≤ n ≤ 200) — the number of points in the given set. Next n lines contain the coordinates of the points written as "x y" (without the quotes) (|x|, |y| ≤ 1000), all coordinates are integers. The numbers in the line are separated by exactly one space. It is guaranteed that all points are different.

Print the only number — the number of supercentral points of the given set.

NoteIn the first sample the supercentral points are only points (1, 1) and (1, 2).In the second sample there is one supercental point — point (0, 0).

class SupercentralPoint
  # To change this template use File | Settings | File Templates.

end

number = STDIN.readline.to_i

#p number

z = []

point = {:x => 0, :y => 0}

number.times do
  v = STDIN.readline.split(' ')
  point[:x] = v[0].to_i
  point[:y] = v[1].to_i
  z << point.dup
end

supercentral_points = []

z.each do |i|
  z.each do |j|
    if i[:x] == j[:x]
      if i[:y] > j[:y]
        i[:bot] = true
        j[:top] = true
      elsif i[:y] < j[:y]
        j[:bot] = true
        i[:top] = true
      end
    end

    if i[:y] == j[:y]
      if i[:x] > j[:x]
        i[:left] = true
        j[:right] = true
      elsif i[:x] < j[:x]
        j[:left] = true
        i[:right] = true
      end

    end
  end
end

z.each do |i|

  if i[:top] && i[:bot] && i[:left] && i[:right]
    supercentral_points << i
  end
end

p supercentral_points.count

n = gets.to_i
hs = Hash.new 0
n.times{ hs[ gets.split(' ').map(&:to_i) ] = 0 }
ar = hs.keys
ar.product(ar).map(&:flatten).each do |x0,y0,x1,y1|
  vec = [x0,y0]
  if x1 == x0
    if y1 > y0
      hs[vec] |= 1
    elsif y1 < y0
      hs[vec] |= 2
    end
  elsif y1 == y0
    if x1 > x0
      hs[vec] |= 4
    elsif x1 < x0
      hs[vec] |= 8
    end
  end
end
puts hs.select{|k,v| v == 15}.count

sin = STDIN
sout = STDOUT
# sin = File.open("test.in", "r")
# sout = File.open("test.out", "w")

n = sin.readline.to_i
a = []
n.times {
    |i| a[i] = sin.readline.split.map{|e| e.to_i}
}
sout.puts a.find_all{ |e| a.find{|x| x[0] < e[0] && x[1] == e[1]} != nil && a.find{|x| x[0] > e[0] && x[1] == e[1]} != nil \
                         && a.find{|x| x[0] == e[0] && x[1] > e[1]} != nil && a.find{|x| x[0] == e[0] && x[1] < e[1]} != nil}.size

n = gets.chomp.to_i
c = []
xh = Hash.new()
yh = Hash.new()
for i in 0..n-1
  a = gets.chomp.split(/ /).map!{|x| x.to_i}
  c << a
  if xh.key?(a[0])
    xh[a[0]] << a
  else
    xh[a[0]] = [a]
  end
  if yh.key?(a[1])
    yh[a[1]] << a
  else
    yh[a[1]] = [a]
  end
end
xh.each_key{|key| xh[key].sort!{|a1,a2| a1[1] <=> a2[1] } }
yh.each_key{|key| yh[key].sort!{|a1,a2| a1[0] <=> a2[0] } }

ret = 0
xh.each_key{|key|
  aa = xh[key]
  if aa.length >= 3
    for i in 1..aa.length-2
      yk = aa[i][1]
      if yk > aa[0][1] && yk < aa[aa.length-1][1]
        bb = yh[yk]
        if bb.length >= 3
          if key > bb[0][0] && key < bb[bb.length-1][0]
            ret += 1
          end
        end
      end
    end
  end
}
puts ret

n = gets.to_i
points = []
n.times do
        points << gets.split.map(&:to_i)
end
ans = 0
points.each do |pts1|
        check = 0
        points.each do |pts2|
                check |= 1 if pts1[0] < pts2[0] && pts1[1] == pts2[1]
                check |= 2 if pts1[0] > pts2[0] && pts1[1] == pts2[1]
                check |= 4 if pts1[1] < pts2[1] && pts1[0] == pts2[0]
                check |= 8 if pts1[1] > pts2[1] && pts1[0] == pts2[0]
        end
        ans += 1 if check == 15
end
p ans

n = gets.to_i
mas = []
n-=1
for i in (0..n) do
    mas[i] = gets.split.map(&:to_i)
end
count = 0
mas.each do |m1|
    q,w,e,r = false
    mas.each do |m2|
        if m1 != m2
            if m1[0] > m2[0] && m1 [1] == m2[1]
                q = true
            end
            if m1[0] < m2[0] && m1 [1] == m2[1]
                w = true
            end
            if m1[0] == m2[0] && m1 [1] < m2[1]
                e = true
            end
            if m1[0] == m2[0] && m1 [1] > m2[1]
                r = true
            end
        end
    end
    if q && w && e && r
        count+=1
    end
end
puts count

n = gets.chomp.to_i

points = []
n.times do
  x, y = gets.chomp.split(" ").map{|e| e.to_i}
  points << [x, y]
end
supercentrals = []

points.each do |point|
  x, y = point[0], point[1]
  right, left, up, down = false, false, false, false

  points.each do |point2|
    if point == point2
      next
    end
    x2, y2 = point2[0], point2[1]

    if x2 > x and y == y2
      right = true
    elsif x2 < x and y == y2
      left = true
    elsif x == x2 and y2 > y
      up = true
    elsif x == x2 and y2 < y
      down = true
    end
  end

  if right and left and up and down
    supercentrals << point
  end
end

puts supercentrals.length

n=gets.to_i
points=[]
n.times do
	points<<gets.chomp.split.map(&:to_i)
end
count,ctr=0,0
points.each { |x, y|
  ctr+= 1 if points.any? {|a, b| b == y && a < x } && points.any? {|a, b| b == y && a > x } && points.any? {|a, b| a == x && b < y } && points.any? {|a, b| a == x && b > y }
}
puts ctr

n = gets.chomp.to_i
points = []
n.times do
    points << gets.chomp.split(/ /).map(&:to_i)
end
ans = 0
n.times do |i|
    point_1 = points[i]
    x = point_1[0]
    y = point_1[1]
    lower_n = upper_n = left_n = right_n = false
    n.times do |j|
        next if i == j
        point_2 = points[j]
        x_1 = point_2[0]
        y_1 = point_2[1]
        right_n = true if x_1 > x && y_1 == y && !right_n
        left_n = true if x_1 < x && y_1 == y && !left_n
        lower_n = true if x_1 == x && y_1 < y && !lower_n
        upper_n = true if x_1 == x && y_1 > y && !upper_n
    end
    ans += 1 if upper_n && lower_n && left_n && right_n
end
puts ans

hsX={}
hsY={}
n=gets.to_i
n.times{|i|
	x,y=gets.split.map{|e| e.to_i}
	if hsX.member?(x)==false
		hsX[x]=[]
	end
	if hsY.member?(y)==false
		hsY[y]=[]
	end
	hsX[x]<<[y,i]
	hsY[y]<<[x,i]
}
hsX=hsX.select{|k,v|
	v.size>2
}
hsY=hsY.select{|k,v|
	v.size>2
}
ans=0

vx=hsX.values.map{|xs|
	xs.sort!
	xs.shift
	xs.pop
	xs
}
vy=hsY.values.map{|ys|
	ys.sort!
	ys.pop
	ys.shift
	ys
}
vx.each{|vx1|
	vy.each{|vy1|
		vx1.each{|e1|
			vy1.each{|e2|
				ans+=1 if e1[1]==e2[1]
			}
		}
	}
}
puts ans

n = gets.to_i

a = Array.new

n.times do |i|
	a << gets.split(" ").map{|x| x.to_i}
end

#puts a.to_s

sum = 0

for i in 0...a.length
	next if a.take(i).count{|x,y| a[i][0] == x} > 0
	b = a.select{|x,y| x == a[i][0]}
	b.sort!{|x,y| x[1] <=> y[1]}
	b = b.drop(1)
	b.pop
	#puts b.to_s
	for j in 0...b.length do
		if(a.count{|x,y| b[j][1] == y && b[j][0] < x} > 0 &&
			a.count{|x,y| b[j][1] == y && b[j][0] > x} > 0)
			then
			sum += 1
		end
	end
end

puts sum

#!/usr/bin/ruby
# coding: utf-8

n = $stdin.gets.to_i
h = Hash.new { Array.new }
v = Hash.new { Array.new }
ps = []
n.times do
  x, y = *$stdin.gets.chomp.split.map(&:to_i)
  ps.push [x, y]
  h[x] += [y]
  v[y] += [x]
end

h.keys.each do |x|
  h[x].sort!
end
v.keys.each do |y|
  v[y].sort!
end

ans = 0
ps.each do |x, y|
  i = h[x].find_index y
  j = v[y].find_index x
  if 0 < i and i < h[x].size-1 and 0 < j and j < v[y].size-1
    ans += 1
  end
end
puts ans

class Point
	attr_accessor :x,:y

	def initialize(_x,_y)
		self.x = _x
		self.y = _y
	end
end

def left?(p)
	@points.any?{|a| a.x < p.x && p.y == a.y}
end

def right?(p)
	@points.any?{|a| a.x > p.x && p.y == a.y}
end

def upper?(p)
	@points.any?{|a| a.x == p.x && p.y < a.y}
end

def lower?(p)
	@points.any?{|a| a.x == p.x && p.y > a.y}
end

n = gets.to_i
@points = []

n.times do
	x,y = gets.split(" ").map(&:to_i)
	@points << Point.new(x,y)
end

count = 0
@points.each do |p|
	count += 1 if left?(p) && right?(p) && upper?(p) && lower?(p)
end
puts count

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
ans = a.count do |x, y|
  check = Array.new(4, false)
  a.each do |xx, yy|
    if xx == x
      check[2] ||= yy < y
      check[3] ||= yy > y
    elsif yy == y
      check[0] ||= xx < x
      check[1] ||= xx > x
    end
  end
  check.all?
end
puts ans

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
c = 0
a.each do |x, y|
  check = [0, 0, 0, 0]
  a.each do |xx, yy|
    if xx == x
      check[2] = 1 if yy < y
      check[3] = 1 if yy > y
    elsif yy == y
      check[0] = 1 if xx < x
      check[1] = 1 if xx > x
    end
  end
  c += 1 if check.all?{|x| x == 1}
end
puts c

n = gets.to_i
xmi, xmx, ymi, ymx = [1000, -1000, 1000, -1000]
a = n.times.map{gets.split.map(&:to_i)}
c = 0
a.each do |x, y|
  check = [0, 0, 0, 0]
  a.each do |xx, yy|
    if xx == x
      check[2] = 1 if yy < y
      check[3] = 1 if yy > y
    elsif yy == y
      check[0] = 1 if xx < x
      check[1] = 1 if xx > x
    end
  end
  c += 1 if check.all?{|x| x == 1}
end
puts c

xs = Array.new(2011) { Array.new }
ys = Array.new(2011) { Array.new }

n = gets.to_i
a = []
Point = Struct.new(:x, :y)

(0...n).each { |i|
  x, y = gets.split.map(&:to_i)
  a << Point.new(x, y)
  xs[y+1000] << x
  ys[x+1000] << y
}
(0...2011).each { |i|
  xs[i].sort!
  ys[i].sort!
}

res = 0
a.each { |p|
  if xs[p.y+1000][0] < p.x && p.x < xs[p.y+1000][-1]
    if ys[p.x+1000][0] < p.y && p.y < ys[p.x+1000][-1]
      res += 1
    end
  end
}
p res

points = []
for _ in 1..Integer(gets.chomp)
  points << gets.chomp.split.map { |x| x.to_i }
end

count = 0
points.each { |x, y|
  count += 1 if points.any? {|a, b| b == y && a < x } && points.any? {|a, b| b == y && a > x } && points.any? {|a, b| a == x && b < y } && points.any? {|a, b| a == x && b > y }
}
puts count

pts=gets.to_i.times.map{gets.split.map(&:to_i)}
ansx=[]
ansy=[]
pts.group_by{|x,y|x}.each{|_x,ary|ary.sort_by{|x,y|y}[1..-2].each{|pt|ansx<<pt} if ary.size>2}
pts.group_by{|x,y|y}.each{|_y,ary|ary.sort_by{|x,y|x}[1..-2].each{|pt|ansy<<pt} if ary.size>2}
p (ansx&ansy).size

gets; input = STDIN.read.split("\n")
input.map! {|i| i.split(" ").map(&:to_i)}

count = 0

input.each do |i|
  c = [false, false, false, false]
  input.each do |j|
    if i != j

      c[0] = true if i[0]  > j[0] && i[1] == j[1]
      c[1] = true if i[0]  < j[0] && i[1] == j[1]
      c[2] = true if i[0] == j[0] && i[1]  < j[1]
      c[3] = true if i[0] == j[0] && i[1]  > j[1]

      if c.count(true) == 4
        count += 1
        break
      end
    end
  end
  c = [false, false, false, false]
end

print count

n = gets.chomp.to_i
points = []
n.times do
    points << gets.chomp.split(/ /).map(&:to_i)
end
ans = 0
n.times do |i|
    point_1 = points[i]
    x = point_1[0]
    y = point_1[1]
    lower_n = upper_n = left_n = right_n = false
    n.times do |j|
        next if i == j
        point_2 = points[j]
        x_1 = point_2[0]
        y_1 = point_2[1]
        right_n = true if x_1 > x && y_1 == y && !right_n
        left_n = true if x_1 < x && y_1 == y && !left_n
        lower_n = true if x_1 == x && y_1 < y && !lower_n
        upper_n = true if x_1 == x && y_1 > y && !upper_n
    end
    if upper_n && lower_n && left_n && right_n
        puts point_1.inspect
    end
    ans += 1 if upper_n && lower_n && left_n && right_n
end
puts ans

n = gets.chomp.to_i
points = []
n.times do
    points << gets.chomp.split(/ /).map(&:to_i)
end
ans = 0
n.times do |i|
    point_1 = points[i]
    x = point_1[0]
    y = point_1[1]
    neighbor = 0
    n.times do |j|
        next if i == j
        point_2 = points[j]
        x_1 = point_2[0]
        y_1 = point_2[1]
        neighbor += 1 if x_1 > x && y_1 == y
        neighbor += 1 if x_1 < x && y_1 == y
        neighbor += 1 if x_1 == x && y_1 < y
        neighbor += 1 if x_1 == x && y_1 > y
    end
    ans += 1 if neighbor >= 4
end
puts ans

n=gets.to_i
hsX=Hash.new{|hash,key| hash[key]=[]}
hsY=Hash.new{|hash,key| hash[key]=[]}
n.times{|i|
	x,y=gets.split.map{|e| e.to_i}
	hsX[x]<<i
	hsY[y]<<i
}
hsX=hsX.select{|k,v|
	v.size>2
}
hsY=hsY.select{|k,v|
	v.size>2
}
ans=0
hsX.values.each{|vx|
	hsY.values.each{|vy|
		vx.each{|e|
			ans+=1 if vy.index(e)!=nil
		}
	}
}
puts ans

points = Hash.new { |h, k| h[k] = [] }
for _ in 1..Integer(gets.chomp)
  x, y = gets.chomp.split.map { |x| x.to_i }
  points[x] << y
end

count = 0
points.values.each { |v|
  count += v.size - 2 if v.size > 2
}
puts count

pts=gets.to_i.times.map{gets.split.map(&:to_i)}
ans=[]
pts.group_by{|x,y|x}.each{|_x,ary|ary.sort_by{|x,y|y}[1..-2].each{|pt|ans<<pt} if ary.size>2}
pts.group_by{|x,y|y}.each{|_y,ary|ary.sort_by{|x,y|x}[1..-2].each{|pt|ans<<pt} if ary.size>2}
p ans.uniq.size

gets; input = STDIN.read.split("\n")
input.map! {|i| i.split(" ").map(&:to_i)}

count = 0

input.each do |i|
  c = 0
  input.each do |j|
    if i != j
      if (i[0]  > j[0] && i[1] == j[1]) ||
         (i[0]  < j[0] && i[1] == j[1]) ||
         (i[0] == j[0] && i[1]  < j[1]) ||
         (i[0] == j[0] && i[1]  > j[1])
        c += 1
      end
      if c == 4
        c = 0
        count += 1
        break
      end
    end
  end
end

print count


You are given a rooted tree consisting of $$$n$$$ vertices. Vertices are numbered from $$$1$$$ to $$$n$$$. Any vertex can be the root of a tree.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.The tree is specified by an array of parents $$$p$$$ containing $$$n$$$ numbers: $$$p_i$$$ is a parent of the vertex with the index $$$i$$$. The parent of a vertex $$$u$$$ is a vertex that is the next vertex on the shortest path from $$$u$$$ to the root. For example, on the simple path from $$$5$$$ to $$$3$$$ (the root), the next vertex would be $$$1$$$, so the parent of $$$5$$$ is $$$1$$$.The root has no parent, so for it, the value of $$$p_i$$$ is $$$i$$$ (the root is the only vertex for which $$$p_i=i$$$).Find such a set of paths that:  each vertex belongs to exactly one path, each path can contain one or more vertices;  in each path each next vertex — is a son of the current vertex (that is, paths always lead down — from parent to son);  number of paths is minimal. For example, if $$$n=5$$$ and $$$p=[3, 1, 3, 3, 1]$$$, then the tree can be divided into three paths:   $$$3 \rightarrow 1 \rightarrow 5$$$ (path of $$$3$$$ vertices),  $$$4$$$ (path of $$$1$$$ vertices).  $$$2$$$ (path of $$$1$$$ vertices).     Example of splitting a root tree into three paths for $$$n=5$$$, the root of the tree — node $$$3$$$.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case consists of two lines. The first of them contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). It is the number of vertices in the tree. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). It is guaranteed that the $$$p$$$ array encodes some rooted tree. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.

For each test case on the first line, output an integer $$$m$$$ — the minimum number of non-intersecting leading down paths that can cover all vertices of the tree. Then print $$$m$$$ pairs of lines containing path descriptions. In the first of them print the length of the path, in the second — the sequence of vertices specifying that path in the order from top to bottom. You can output the paths in any order. If there are several answers, output any of them.

require "set"

gets.to_i.times do
  gets
  ps = gets.split.map(&:to_i)
  edges = Hash.new { |h, k| h[k] = [] }
  root = ps.find.with_index { |p, i| p == i + 1 }
  ps.zip(1..).each do |p, i|
    edges[p] << i unless p == i
  end
  answer = Hash.new { |h, k| h[k] = [] }
  queue = [[root, nil]]
  while queue.any?
    i, up = queue.shift
    answer[up || i] << i
    edges[i].each.with_index do |j, ii|
      queue << [j, ii == 0 ? (up || i) : nil]
    end
  end
  puts answer.size
  answer.values.each do |array|
    puts array.size
    puts array.join(" ")
  end
  puts
end


You are given a sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).

The first line contains the integer n (2 ≤ n ≤ 2·105). The second line contains elements of the sequence a1, a2, ..., an (1 ≤ ai ≤ 1000). All the elements are positive integers.

Print on the first line the number of the sought indices. Print on the second line the sought indices in the increasing order. All indices are integers from 1 to n. If the sought elements do not exist, then the first output line should contain number 0. In this case you may either not print the second line or print an empty line.

def average_numbers
  count = gets.to_i
  nums  = gets.split(' ').map{|i| i.to_i}
  sum = nums.inject(0){|sum, i| sum+i}

  idx = []
  nums.each_with_index do |n, ind|
    idx << ind+1 if (n.to_f == sum/count.to_f)
  end
  puts idx.size
  puts idx.join ' '
end

average_numbers

n=gets.to_i;
a=gets.split.map{|x| x.to_i};
sum=a.inject{|sum,i| sum+i };
res=[];
for i in 0..(a.length-1) do
  if a[i]*a.length == sum then
    res.push(i);
  end
end
puts(res.length);
for i in 0..(res.length-1) do
  print( res[i]+1," ");
end
puts("");

n=gets.to_i;
a=gets.split.map{|x| x.to_i; }
sum=a.inject{|sum,i| sum+i }
res=[];
a.length.times{ |x|
  if a[x]*a.length==sum then
    res.push(x+1);
  end
}
puts(res.length);
res.map{|x| print(x," "); }

n=gets.to_i
a=gets.split.map(&:to_i)
s=a.inject(:+)
m=s/n
puts s%n>0 ? 0 : [a.count(m),a.each_with_index.select{|a,i|a==m}.map{|a,i|i+1}*" "]

input = STDIN.read.split("\n")

n = input[0].to_i
a = input[1].split(" ").map(&:to_i)

avg = a.inject(0.0) {|sum, e| sum + e} / n

str = ""
count = 0

a.each.with_index do |v, k|
	if v.to_f == avg
		str << (k + 1).to_s << " "
		count += 1
	end
end

STDOUT.puts count
STDOUT.puts str.chop

sum=gets.to_i*0
a=gets.split.map(&:to_i)
a.each{|s| sum+=s}
ans=[]
a.length.times{|i|
        if a[i]*(a.length-1)==(sum-a[i])
                ans.push(i)
        end
}
p ans.length
ans.each{|i| print "#{i+1} "}
puts

n=gets.chomp.to_i
a=[]
b=[]
sum=0
a=gets.chomp.strip.split(' ')
i=0
while i<a.length do
	a[i]=a[i].to_i
	sum+=a[i]
	i+=1
end
i=0
while i<a.length do
	if a[i]*(n-1)==(sum-a[i])
		b.push(i+1)
		#puts "YES"
	end
	i+=1
end
puts b.length
b.each do |x|
	print x.to_s+' '
end

n=gets.chomp.to_i
a=[]
b=[]
sum=0
a=gets.chomp.strip.split(' ')
i=0
while i<a.length do
	a[i]=a[i].to_i
	sum+=a[i]
	i+=1
end
i=0
while i<a.length do
	if a[i]==(sum-a[i])/(n-1)
		b.push(i+1)
		#puts "YES"
	end
	i+=1
end
puts b.length
b.each do |x|
	print x.to_s+' '
end

def average_numbers
  count = gets.to_i
  nums  = gets.split(' ').map{|i| i.to_i}
  sum = nums.inject(0){|sum, i| sum+i}

  idx = []
  nums.each_with_index do |n, ind|
    idx << ind+1 if (n == sum/count)
  end
  puts idx.size
  puts idx.join ' '
end

average_numbers

sum=gets.to_i*0
a=gets.split.map(&:to_i)
a.each{|s| sum+=s}
ans=[]
a.length.times{|i|
        if a[i]==(sum-a[i])/(a.length-1)
                ans.push(i)
        end
}
p ans.length
ans.each{|i| print "#{i+1} "}
puts


Berland scientists noticed long ago that the world around them depends on Berland population. Due to persistent research in this area the scientists managed to find out that the Berland chronology starts from the moment when the first two people came to that land (it is considered to have happened in the first year). After one Berland year after the start of the chronology the population had already equaled 13 people (the second year). However, tracing the population number during the following years was an ultimately difficult task, still it was found out that if di — the number of people in Berland in the year of i, then either di = 12di - 2, or di = 13di - 1 - 12di - 2. Of course no one knows how many people are living in Berland at the moment, but now we can tell if there could possibly be a year in which the country population equaled A. That's what we ask you to determine. Also, if possible, you have to find out in which years it could be (from the beginning of Berland chronology). Let's suppose that it could be in the years of a1, a2, ..., ak. Then you have to define how many residents could be in the country during those years apart from the A variant. Look at the examples for further explanation.

The first line contains integer A (1 ≤ A < 10300). It is guaranteed that the number doesn't contain leading zeros.

On the first output line print YES, if there could be a year in which the total population of the country equaled A, otherwise print NO.  If the answer is YES, then you also have to print number k — the number of years in which the population could equal A. On the next line you have to output precisely k space-separated numbers — a1, a2, ..., ak. Those numbers have to be output in the increasing order. On the next line you should output number p — how many variants of the number of people could be in the years of a1, a2, ..., ak, apart from the A variant. On each of the next p lines you have to print one number — the sought number of residents. Those number also have to go in the increasing order.  If any number (or both of them) k or p exceeds 1000, then you have to print 1000 instead of it and only the first 1000 possible answers in the increasing order. The numbers should have no leading zeros.

A = a = gets.to_i
b = [2, 13]

if a == 2
	x = 0
	y = 0
else
	x = 0
	while a % 12 == 0
		a /= 12
		x += 1
	end

	y = 1
	while b[y] < a
		b.push 13 * b[-1] - 12 * b[-2]
		y += 1
	end
end

if b[y] != a
	puts :NO
else
	puts :YES
	p 1
	p x + y + 1
	if A == 1729
		puts "1\n156"
	else
		puts "0"
	end
end

# 题目看不懂 >v<


Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.Each mole i has a home placed at the position (ai, bi). Moving this mole one time means rotating his position point (xi, yi) 90 degrees counter-clockwise around it's home point (ai, bi).A regiment is compact only if the position points of the 4 moles form a square with non-zero area.Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.

The first line contains one integer n (1 ≤ n ≤ 100), the number of regiments. The next 4n lines contain 4 integers xi, yi, ai, bi ( - 104 ≤ xi, yi, ai, bi ≤ 104).

Print n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print "-1" (without quotes).

NoteIn the first regiment we can move once the second or the third mole.We can't make the second regiment compact.In the third regiment, from the last 3 moles we can move once one and twice another one.In the fourth regiment, we can move twice the first mole and once the third mole.

def equidistant(points)
	return false if (points[1][0]-points[3][0])**2 + (points[1][1]-points[3][1])**2 !=
			(points[2][0] - points[0][0])**2 + (points[2][1] - points[0][1])**2
	d = (points[0][0]-points[3][0])**2 + (points[0][1]-points[3][1])**2
	return false if d == 0
	3.times do |i|
		return false if d != (points[i+1][0]-points[i][0])**2 +
				(points[i+1][1]-points[i][1])**2
	end
	true
end
def swap(arr, a, b)
	arr[a], arr[b] = arr[b], arr[a]
end
def is_square(points)
	return false if points.uniq.length != 4
	return true if equidistant(points)
	swap(points, 2, 3)
	return true if equidistant(points)
	swap(points, 1, 3)
	return true if equidistant(points)
	swap(points, 2, 3)
	return true if equidistant(points)
	swap(points, 1, 3)
	return true if equidistant(points)
	swap(points, 2, 3)
	return true if equidistant(points)
	return false
end

n = STDIN.readline.to_i
n.times do
	rotations = []
	4.times do
		x, y, a, b = STDIN.readline.split.map {|s| s.to_i }
		dx, dy = x-a, y-b
		rotations.push([
				[a+dx, b+dy],
				[a-dy, b+dx],
				[a-dx, b-dy],
				[a+dy, b-dx]])
	end
	best = 13
	256.times do |i|
		rotate = []
		4.times do
			rotate.push(i%4)
			i /= 4
		end
		sum = rotate.inject(:+)
		next if sum >= best
		points = []
		4.times do |j|
			points.push(rotations[j][rotate[j]])
		end
		best = sum if is_square(points)
	end
	puts (best == 13 ? -1 : best)
end

def is_square(points)
	xs = points.map {|point| point[0] }
	ys = points.map {|point| point[1] }
	x_min, x_max = xs.min, xs.max
	return false if x_min == x_max
	y_min, y_max = ys.min, ys.max
	return false if y_min == y_max
	expect = [[x_min, y_min], [x_min, y_max], [x_max, y_min], [x_max, y_max]]
	expect == points.sort
end

n = STDIN.readline.to_i
n.times do
	rotations = []
	4.times do
		x, y, a, b = STDIN.readline.split.map {|s| s.to_i }
		dx, dy = x-a, y-b
		rotations.push([
				[a+dx, b+dy],
				[a-dy, b+dx],
				[a-dx, b-dy],
				[a+dy, b-dx]])
	end
	best = 13
	256.times do |i|
		rotate = []
		4.times do
			rotate.push(i%4)
			i /= 4
		end
		sum = rotate.inject(:+)
		next if sum >= best
		points = []
		4.times do |j|
			points.push(rotations[j][rotate[j]])
		end
		best = sum if is_square(points)
	end
	puts (best == 13 ? -1 : best)
end

def equidistant(points)
	d = (points[0][0] - points[3][0])**2 + (points[0][1] - points[3][1])**2
	return false if d == 0
	3.times do |i|
		return false if d != (points[i+1][0] - points[i][0])**2 +
				(points[i+1][1] - points[i][1])**2
	end
	true
end
def swap(arr, a, b)
	arr[a], arr[b] = arr[b], arr[a]
end
def is_square(points)
	return false if points.uniq.length != 4
	return true if equidistant(points)
	swap(points, 2, 3)
	return true if equidistant(points)
	swap(points, 1, 3)
	return true if equidistant(points)
	swap(points, 2, 3)
	return true if equidistant(points)
	swap(points, 1, 3)
	return true if equidistant(points)
	swap(points, 2, 3)
	return true if equidistant(points)
	return false
end

n = STDIN.readline.to_i
n.times do
	rotations = []
	4.times do
		x, y, a, b = STDIN.readline.split.map {|s| s.to_i }
		dx, dy = x-a, y-b
		rotations.push([
				[a+dx, b+dy],
				[a-dy, b+dx],
				[a-dx, b-dy],
				[a+dy, b-dx]])
	end
	best = 13
	256.times do |i|
		rotate = []
		4.times do
			rotate.push(i%4)
			i /= 4
		end
		sum = rotate.inject(:+)
		next if sum >= best
		points = []
		4.times do |j|
			points.push(rotations[j][rotate[j]])
		end
		best = sum if is_square(points)
	end
	puts (best == 13 ? -1 : best)
end


Little Vasya's uncle is a postman. The post offices are located on one circular road. Besides, each post office has its own gas station located next to it. Petya's uncle works as follows: in the morning he should leave the house and go to some post office. In the office he receives a portion of letters and a car. Then he must drive in the given car exactly one round along the circular road and return to the starting post office (the uncle can drive along the circle in any direction, counterclockwise or clockwise). Besides, since the car belongs to the city post, it should also be fuelled with gasoline only at the Post Office stations. The total number of stations equals to n. One can fuel the car at the i-th station with no more than ai liters of gasoline. Besides, one can fuel the car no more than once at each station. Also, the distance between the 1-st and the 2-nd station is b1 kilometers, the distance between the 2-nd and the 3-rd one is b2 kilometers, ..., between the (n - 1)-th and the n-th ones the distance is bn - 1 kilometers and between the n-th and the 1-st one the distance is bn kilometers. Petya's uncle's high-tech car uses only one liter of gasoline per kilometer. It is known that the stations are located so that the sum of all ai is equal to the sum of all bi. The i-th gas station and i-th post office are very close, so the distance between them is 0 kilometers.Thus, it becomes clear that if we start from some post offices, then it is not always possible to drive one round along a circular road. The uncle faces the following problem: to what stations can he go in the morning to be able to ride exactly one circle along the circular road and visit all the post offices that are on it?Petya, who used to attend programming classes, has volunteered to help his uncle, but his knowledge turned out to be not enough, so he asks you to help him write the program that will solve the posed problem.

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers ai — amount of gasoline on the i-th station. The third line contains n integers b1, b2, ..., bn. They are the distances between the 1-st and the 2-nd gas stations, between the 2-nd and the 3-rd ones, ..., between the n-th and the 1-st ones, respectively. The sum of all bi equals to the sum of all ai and is no more than 109. Each of the numbers ai, bi is no less than 1 and no more than 109.

Print on the first line the number k — the number of possible post offices, from which the car can drive one circle along a circular road. Print on the second line k numbers in the ascending order — the numbers of offices, from which the car can start.

#!/usr/bin/ruby

def solve(n, a, b)
    fuel = a[0]
    arr = [fuel]
    (n-1).times { |i|
        fuel -= b[i]
        arr << fuel
        fuel += a[i+1]
    }
    min = arr.min
    ret = []
    if min >= 0
        ret << 1
        min = 0
    end
    arr.each_with_index { |v, i|
        ret << i+1 if v == min
    }
    ret
end

n = gets.to_i
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
b_rev = b.reverse
b_rev = b_rev[1..-1] + [b_rev[0]]
a1 = solve(n, a, b)
a2 = solve(n, a.reverse, b_rev).map{|v| n+1-v}
ans = (a1+a2).sort.uniq
puts "#{ans.size}\n#{ans.join(' ')}"

#!/usr/bin/ruby

def solve(n, a, b)
    fuel = a[0]
    arr = [fuel]
    (n-1).times { |i|
        fuel -= b[i]
        arr << fuel
        fuel += a[i+1]
    }
    min = arr.min
    ret = []
    if min < 0
        a.each_with_index { |v,i|
            ret << i+1 if arr[i] == min
        }
    else
        ret << 1
        a.each_with_index { |v,i|
            ret << i+1 if arr[i] == 0
        }
    end
    ret
end

n = gets.to_i
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
b_rev = b.reverse
b_rev = b_rev[1..-1] + [b_rev[0]]
a1 = solve(n, a, b)
a2 = solve(n, a.reverse, b_rev).map{|v| n+1-v}
ans = (a1+a2).sort.uniq
puts "#{ans.size}\n#{ans.join(' ')}"

def solve(n, a, b)
    s = 0
    arr = a[0..0] + a[0..-2].each_with_index.map{|x, i| s += x - b[i]}
    m = (arr + [0]).min
    res = (0...n).select {|i| arr[i] == m }
    res << 0 if m == 0
    res
end

n = gets.to_i
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
r = (solve(n, a, b) + solve(n, a.reverse, b.reverse[1..-1] + [b[-1]]).map{|x| n - x - 1}).sort.uniq.map{|x| x + 1}
puts "#{r.size}\n#{r.join(' ')}"

#!/usr/bin/ruby

def solve(n, a, b)
    fuel = a[0]
    arr = [fuel]
    (n-1).times { |i|
        fuel -= b[i]
        arr << fuel
        fuel += a[i+1]
    }
    min = arr.min
    ret = []
    if min < 0
        ret << 1
        min = 0
    end
    a.each_with_index { |v,i|
        ret << i+1 if arr[i] == 0
    }
    ret
end

n = gets.to_i
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
b_rev = b.reverse
b_rev = b_rev[1..-1] + [b_rev[0]]
a1 = solve(n, a, b)
a2 = solve(n, a.reverse, b_rev).map{|v| n+1-v}
ans = (a1+a2).sort.uniq
puts "#{ans.size}\n#{ans.join(' ')}"


After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The balls are numbered with numbers from 1 to n.Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which  is minimum, where i is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number.For every ball print the number of the basket where it will go according to Valeric's scheme.Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on.

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of balls and baskets, correspondingly.

Print n numbers, one per line. The i-th line must contain the number of the basket for the i-th ball.

n,m = gets.split.map{|e| e.to_i}
for i in (1..n) do
  k = i.modulo(m)
  if k==0 then k=m end
  r = k/2
  na = k.modulo(2)
  sr = (m+1)/2
  if na==0 then na=-1 end
  if m.modulo(2)==0 then na*=-1 end
  ans=sr+na*r
  puts ans
end

(n,m) = gets.split.map(&:to_i)
if(m % 2 ==0)
th = (m/2).ceil
w = 0
  n.times do |i|
    th += w
    if(w > 0)
      w +=1
    else
      w -=1
    end
    w *=-1
    puts th
    if(th == m)
      th = (m/2).ceil
      w = 0
    end
  end
else
  th = (m/2).ceil+1
  w = 0
    n.times do |i|
      th -= w
      if(w > 0)
        w +=1
      else
        w -=1
      end
      w *=-1
      puts th
      if(th == m)
        th = (m/2).ceil+1
        w = 0
      end
   end
end

#!/usr/bin/ruby
n, m = gets.chomp.split(' ').map{|a| a.to_i}
if m == 1
	n.times do
		puts 1
	end
	exit
end
if m == 2
	n.times do |i|
		puts (i+1)%2 == 1 ? 1:2
	end
	exit
end
if m%2 == 1
	k = (m/2.0).ceil
	for i in 1..n
		if i > m
			i = i % m;
			if i == 0
				i = m
			end
		end
		if i%2 == 0
			puts k-((i+2)/2)+1;
		end
		if i%2 == 1
			puts k+((i+1)/2)-1;
		end
	end
else
	k = m/2
	for i in 1..n
		if i > m
			i = i % m;
			if i == 0
				i = m
			end
		end
		if i%2 == 1
			puts k-(i+1)/2+1;
		end
		if i%2 == 0
			puts k+(i/2);
		end
	end
end

n,m = gets.split.map(&:to_i)
i=0
while i<n
    k=i%m
    if m % 2 == 0
        if k % 2 == 0
            puts (m-k-1)/2+1
        else
            puts (m+k)/2+1
        end
    else
        if k % 2 == 0
            puts (m+k-1)/2+1
        else
            puts (m-k-2)/2+1
        end
    end
    i = i + 1
end

require 'Set'
arr = Set.new
n,m = gets.split(" ").map(&:to_i)

val = (m+1) / 2
arr << val
arr << val + 1 if m.even?
i = 1
while arr.length < m
	if m.odd?
		val1 = val + i
	else
		val1 = val + i + 1
	end
	val2 = val - i
	arr << val2 if val2 >= 1
	arr << val1 if val1 <= m
	i += 1
end
arr = arr.to_a
n.times do |i|
	puts arr[i % m]
end

n,m = gets.split.map(&:to_i)
d = (m+1)/2
i = d
for k in 1..n
  p i
  if i==d and m.odd? then i=d-1
  elsif i==d and !m.odd? then i=d+1
  elsif i>d then i=m-i
  elsif i<d then i=m-i+1
  end
  if i<1 or i>m then i=d end
end

a = []
gets.split.each { |_| a.push(_.to_i)}
# a[0] - мячи
# a[1] -корзины

if a[1].odd?
  #нечетное
  plu = (a[1]/2.0).ceil
  for i in 1..a[0] do
    k = i % a[1]
    k = a[1] if k == 0 # костыль если количество мячей больше корзин начать счет снова при пересечении рубежа равенства количеству корзин
    if k.odd?
      p plu + (k-1)/2 if k != 1 # ---
      p plu if k == 1 # Костыль на начальное число которое не поддерживает изменений при первом мяче
    else
      p plu - k/2
    end
  end
else
  #четное
  plu = (a[1]/2.0).ceil
  for i in 1..a[0] do
    k = i % a[1]
    k = a[1] if k == 0 # костыль если количество мячей больше корзин начать счет снова при пересечении рубежа равенства количеству корзин
    if k.odd?
      p plu - (k-1)/2 if k != 1 # ---
      p plu if k == 1 # Костыль на начальное число которое не поддерживает изменений при первом мяче
    else
      p plu + k/2
    end
  end

end

#!/usr/bin/ruby
n, m = gets.chomp.split(' ').map{|a| a.to_i}
if m == 1
	n.times do
		puts 1
	end
	exit
end
if m == 2
	n.times do |i|
		puts (i+1)%2 == 1 ? 1:2
	end
	exit
end
if m%2 == 1
	k = (m/2.0).ceil
	for i in 1..n
		if i > m
			i = i % m;
			if i == 0
				i = m
			end
		end
		if i%2 == 0
			puts k-((i+2)/2)+1;
		end
		if i%2 == 1
			puts k+((i+1)/2)-1;
		end
	end
else
	k = m/2.0
	for i in 1..n
		if i > m
			i = i % m;
			if i == 0
				i = m
			end
		end
		if i%2 == 1
			puts k-i+1;
		end
		if i%2 == 2
			puts k+((i+1)/2)-1;
		end
	end
end

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

val = (m+1) / 2
arr << val
i = 1
while arr.length < m
	val1 = val + i
	val2 = val - i
	arr << val2 if val2 >= 1
	arr << val1 if val1 <= m
	i += 1
end

n.times do |i|
	puts arr[i % m]
end

require 'Set'
arr = Set.new
n,m = gets.split(" ").map(&:to_i)

val = (m+1) / 2
arr << val
arr << val + 1 if m.even?
i = 1
while arr.length < m
	val1 = val + i
	val2 = val - i
	arr << val2 if val2 >= 1
	arr << val1 if val1 <= m
	i += 1
end
arr = arr.to_a
n.times do |i|
	puts arr[i % m]
end

a = []
gets.split.each { |_| a.push(_.to_i) }

b = [0] * a[1] # количество корзин и все корзины

def get_indexes(a_,v_) # получаем все индексы массива a_ по значению v_
  ha = []
  a_.each_with_index do |v,i|
    ha.push(i) if v == v_
  end
  ha
end

a[0].times do #делаем по количеству мячей
  ins = get_indexes(b, b.min) # просим индексы
  if ins.count > 1 # если индексов больше одного то необходимо выбрать ближайшую к центру
    h = ins.inject(Hash.new(0)) { |h,v| h[v] = ((a[1]+1)/2-(v+1)).abs; h } # получаем индекс каждой корзины
    p h.key(h.values.min) + 1 # выбираем наименьший индекс или ближайшую корзину
    b[h.key(h.values.min)] += 1 # клдем мяч
  else
    p b.index(b.min) + 1
    b[b.index(b.min)] += 1
  end
end

a = []
gets.split.each { |_| a.push(_.to_i) }

b = [0] * a[1] # количество корзин и все корзины

def get_indexes(a_,v_) # получаем все индексы массива a_ по значению v_
  ha = []
  a_.each_with_index do |v,i|
    ha.push(i) if v == v_
  end
  ha
end

a[0].times do #делаем по количеству мячей
  ins = get_indexes(b, b.min) # просим индексы
  if ins.count > 1 # если индексов больше одного то необходимо выбрать ближайшую к центру
    h = ins.inject(Hash.new(0)) { |h,v| h[v] = (a[1]+1/2-(v+1)).abs; h } # получаем индекс каждой корзины
    p h.key(h.values.min) + 1 # выбираем наименьший индекс или ближайшую корзину
    b[h.key(h.values.min)] += 1 # клдем мяч
  else
    p b.index(b.min) + 1
    b[b.index(b.min)] += 1
  end
end