PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.How many trees are there in the forest?

The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest. The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id. It's guaranteed that the sequence p corresponds to some valid forest. Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format: In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows: 5 31 23 44 5

You should output the number of trees in the forest where PolandBall lives.

NoteIn the first sample testcase, possible forest is: 1-2 3-4-5. There are 2 trees overall.In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.

require 'set'
n = gets.to_i
list = [0] + gets.chomp.split(" ").map(&:to_i)
set = Set.new
for i in 1..n
  if(list[list[i]] == i)
    set.add([i,list[i]].min)
  end
end
print set.length

#!/usr/bin/env ruby

livings_count = gets.chop.to_i

livings_relation = {}
trees = []

relations = gets.chop.split

relations.each.with_index do |b , a|
  a += 1
  b = b.to_i

  if !livings_relation[b] && !livings_relation[a]
    trees.push(Array.new)
    trees_index = trees.size - 1
    livings_relation[a] = trees_index
    livings_relation[b] = trees_index
    trees[trees_index] << a
    trees[trees_index] << b
  elsif !livings_relation[b] && livings_relation[a]
    tree_index = livings_relation[a]
    livings_relation[b] = livings_relation[a]
    trees[tree_index] << b
  elsif livings_relation[b] && !livings_relation[a]
    tree_index = livings_relation[b]
    livings_relation[a] = livings_relation[b]
    trees[tree_index] << a
  elsif livings_relation[a] != livings_relation[b]
    # merge
    tree_index = livings_relation[a]
    tree_index_del = livings_relation[b]
    #livings_relation[b] = livings_relation[a]
    trees[tree_index_del].each do |living|
      livings_relation[living] = tree_index
      trees[tree_index] << living
    end
    trees[tree_index_del] = nil
  end
end

puts trees.compact.size


It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.

The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.

In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form. If there are multiple possible answers, you can print any of them.

NoteIn the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.

#!/usr/bin/env ruby

n = gets.to_i
h = gets.split.map(&:to_i)
sol = []
100.times do
  x = h.map{|x| x * 10 + rand(10)}.map.with_index(1).sort.map(&:last)
  sol << x if !sol.include?(x)
  break if sol.size == 3
end

if sol.size == 3
  puts 'YES'
  puts sol.map{|x| x.map(&:to_s).join(' ')}
else
  puts 'NO'
end

n = STDIN.readline.to_i
values = STDIN.readline.split.map {|s| s.to_i }
value_indices = {}
values.each_with_index do |value, index|
	value_indices[value] ||= []
	value_indices[value].push(index+1)
end
perturb_two, perturb_three = [], nil
value_indices.each do |value, indices|
	if indices.length >= 3
		perturb_three = value
		break
	elsif indices.length == 2
		perturb_two.push(value)
		break if perturb_two.length == 2
	end
end
orders = 3.times.map { [] }
if perturb_three != nil
	value_indices.keys.sort.each do |value|
		indices = value_indices[value]
		if value == perturb_three
			orders[0].push(indices[0])
			orders[0].push(indices[1])
			orders[0].push(indices[2])
			orders[1].push(indices[1])
			orders[1].push(indices[2])
			orders[1].push(indices[0])
			orders[2].push(indices[2])
			orders[2].push(indices[0])
			orders[2].push(indices[1])
			indices[3..-1].each {|index| 3.times {|p| orders[p].push(index) } }
		else
			indices.each {|index| 3.times {|p| orders[p].push(index) } }
		end
	end
elsif perturb_two.length == 2
	value_indices.keys.sort.each do |value|
		indices = value_indices[value]
		if perturb_two.index(value) == 0
			orders[0].push(indices[0])
			orders[0].push(indices[1])
			orders[1].push(indices[0])
			orders[1].push(indices[1])
			orders[2].push(indices[1])
			orders[2].push(indices[0])
		elsif perturb_two.index(value) == 1
			orders[0].push(indices[0])
			orders[0].push(indices[1])
			orders[1].push(indices[1])
			orders[1].push(indices[0])
			orders[2].push(indices[1])
			orders[2].push(indices[0])
		else
			indices.each {|index| 3.times {|p| orders[p].push(index) } }
		end
	end
else
	puts 'NO'
	exit
end
puts 'YES'
3.times {|i| puts orders[i].join(' ') }

n = gets.to_i
h = gets.split.map(&:to_i)
if h.uniq.size > n - 2
  puts "NO"
else
  puts "YES"
  h.map!.with_index { |d, i| [d, i + 1] }.sort_by! { |d, i| d }

  puts h.map { |d, i| i }.join(" ")

  1.upto(n - 1).each do |i|
    if h[i - 1][0] == h[i][0]
      h[i - 1], h[i] = h[i], h[i - 1]
      break
    end
  end

  puts h.map { |d, i| i }.join(" ")

  (n - 1).downto(1).each do |i|
    if h[i - 1][0] == h[i][0]
      h[i - 1], h[i] = h[i], h[i - 1]
      break
    end
  end

  puts h.map { |d, i| i }.join(" ")
end

require 'pp'

n = STDIN.gets.chomp.to_i
os = STDIN.gets.chomp.split(/ /).map(&:to_i)

ss = [(1..n).to_a, os].transpose
ss.sort!{|a, b| a.last <=> b.last }

s = os.sort
count=1
leg = -1
same3 = nil
same2 = []
(n-1).times do |i|
  if s[i] == s[i+1]
    count+=1
    if count >=3
      same3 = s[i]
      break
    elsif count >=2
      same2.push s[i]
    end
  else
    count = 1
  end
end

if same3
  ans = []
  ans.push ss.map{|a,b| a}

  pos = []
  ss.each_with_index do |sse,i|
    pos.push i if sse.last == same3
  end
  ss[pos[0]], ss[pos[1]], ss[pos[2]] = ss[pos[1]], ss[pos[2]], ss[pos[0]]
  ans.push ss.map{|a,b| a}
  ss[pos[0]], ss[pos[1]], ss[pos[2]] = ss[pos[1]], ss[pos[2]], ss[pos[0]]
  ans.push ss.map{|a,b| a}

  puts "YES"
  ans.each{|a| puts a.join(" ")}
elsif same2.length >= 2
  ans = []
  ans.push ss.map{|a,b| a}

  pos0 = []
  pos1 = []
  ss.each_with_index do |sse,i|
    pos0.push i if sse.last == same2[0]
    pos1.push i if sse.last == same2[1]
  end
  ss[pos0.first], ss[pos0.last] = ss[pos0.last], ss[pos0.first]
  ans.push ss.map{|a,b| a}
  ss[pos1.first], ss[pos1.last] = ss[pos1.last], ss[pos1.first]
  ans.push ss.map{|a,b| a}

  puts "YES"
  ans.each{|a| puts a.join(" ")}
else
  puts "NO"
end

a=gets.chomp.to_i
b=gets.chomp.split(" ").map {|i|  i.to_i }
inde=Hash.new {|hash,key|  hash[key]=[]  }
count=Array.new(2001,0)
0.upto(a-1) do |i|
inde[b[i]]<<i+1
count[b[i]]+=1
end
keys=inde.keys.sort
cp=count.max

if cp<2
puts "NO"

elsif cp>2
puts "YES"
p=count.index(cp)
3.times do
keys.each do |i|
print "#{inde[i].join(" ")} "
end
puts
temp=inde[p][0]
temp2=inde[p][1]
inde[p][1]=inde[p][2]
inde[p][2]=temp
inde[p][0]=temp2
end

elsif cp==2

if count.count(cp)<2
puts "NO"

else
index1=count.index(cp)
count.delete_at(index1)
index2=count.index(cp)+1

it=0
puts "YES"
3.times do

keys.each do |i|
print "#{inde[i].join(" ")} "
end
puts
if it==0
temp=inde[index1][0]
inde[index1][0]=inde[index1][1]
inde[index1][1]=temp
it+=1
else
temp=inde[index2][0]
inde[index2][0]=inde[index2][1]
inde[index2][1]=temp
end

end

end

end


I wonder, does the falling rain Forever yearn for it's disdain?Effluvium of the MindYou are given a positive integer $$$n$$$.Find any permutation $$$p$$$ of length $$$n$$$ such that the sum $$$\operatorname{lcm}(1,p_1) + \operatorname{lcm}(2, p_2) + \ldots + \operatorname{lcm}(n, p_n)$$$ is as large as possible. Here $$$\operatorname{lcm}(x, y)$$$ denotes the least common multiple (LCM) of integers $$$x$$$ and $$$y$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1\,000$$$). Description of the test cases follows. The only line for each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_n$$$ — the permutation with the maximum possible value of $$$\operatorname{lcm}(1,p_1) + \operatorname{lcm}(2, p_2) + \ldots + \operatorname{lcm}(n, p_n)$$$. If there are multiple answers, print any of them.

NoteFor $$$n = 1$$$, there is only one permutation, so the answer is $$$[1]$$$.For $$$n = 2$$$, there are two permutations:   $$$[1, 2]$$$ — the sum is $$$\operatorname{lcm}(1,1) + \operatorname{lcm}(2, 2) = 1 + 2 = 3$$$.  $$$[2, 1]$$$ — the sum is $$$\operatorname{lcm}(1,2) + \operatorname{lcm}(2, 1) = 2 + 2 = 4$$$.

gets.to_i.times {
	n = gets.to_i
	a = n.odd? ? 1 : 0
	if n.odd? ; print '1 '; end
	(n/2).times{|i| print i*2+2+a, ' ', i*2+1+a, ' '} ; puts ''
}

gets.to_i.times do
    n = gets.to_i
    puts n.downto(1).each_slice(2).to_a.reverse.join(' ')
end

gets.to_i.times do
  n = gets.to_i
  if n % 2 == 0
    puts 1.upto(n).map { |i| i + (i % 2 == 0 ? -1 : 1) }.join(" ")
  else
    puts ([1] + (2.upto(n).map { |i| i + (i % 2 == 0 ? 1 : -1) })).join(" ")
  end
end

gets.to_i.times {
	n = gets.to_i
	if n.even?
		n.times{|i| print n-i, ' '}; puts ''
	else
		(n/2).times{|i| print n-i*2-1 , ' ', n-i*2, ' '}; puts 1
	end
}

gets.to_i.times { gets.to_i.times{|i| print i+1, ' '}; puts ''}

gets.to_i.times do
  n=gets.to_i
  puts ((2..n).to_a+[1])*' '
end

gets.to_i.times do
  n=gets.to_i
  puts ([n]+(1...n).to_a)*' '
end

gets.to_i.times do
    n = gets.to_i
    n.downto(1).each_slice(2).to_a.reverse.join(' ')
end


Arkady coordinates rounds on some not really famous competitive programming platform. Each round features $$$n$$$ problems of distinct difficulty, the difficulties are numbered from $$$1$$$ to $$$n$$$.To hold a round Arkady needs $$$n$$$ new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from $$$1$$$ to $$$n$$$ and puts it into the problems pool.At each moment when Arkady can choose a set of $$$n$$$ new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it.You are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of difficulty levels and the number of problems Arkady created. The second line contains $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \le a_i \le n$$$) — the problems' difficulties in the order Arkady created them.

Print a line containing $$$m$$$ digits. The $$$i$$$-th digit should be $$$1$$$ if Arkady held the round after creation of the $$$i$$$-th problem, and $$$0$$$ otherwise.

NoteIn the first example Arkady held the round after the first three problems, because they are of distinct difficulties, and then only after the last problem.

n,m = gets.split.map(&:to_i)
cnt = Array.new(n,0)
d = 0
e = 0
a = gets.split.map{|i|i.to_i-1}
a.each do |num|
    cnt[num] += 1
    d += 1 if cnt[num]-1 == e
    if d == n
        print "1"
        e += 1
        for i in 0..n-1
            d -= 1 if cnt[i] == e
        end
    else
        print "0"
    end
end

n,m = gets.split.map(&:to_i)
cnt = Array.new(n,0)
d = 0
e = 0
a = gets.split.map{|i|i.to_i-1}
a.each do |num|
    cnt[num] += 1
    d += 1 if cnt[num]-1 == e
    if d == n
        print "1"
        e += 1
        d = 0
    else
        print "0"
    end
end


Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help.Filya is given an array of non-negative integers a1, a2, ..., an. First, he pick an integer x and then he adds x to some elements of the array (no more than once), subtract x from some other elements (also, no more than once) and do no change other elements. He wants all elements of the array to be equal.Now he wonders if it's possible to pick such integer x and change some elements of the array using this x in order to make all elements equal.

The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the number of integers in the Filya's array. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — elements of the array.

If it's impossible to make all elements of the array equal using the process given in the problem statement, then print "NO" (without quotes) in the only line of the output. Otherwise print "YES" (without quotes).

NoteIn the first sample Filya should select x = 1, then add it to the first and the last elements of the array and subtract from the second and the third elements.

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

max = a.max
min = a.min
mid = (max+min)/2.0

puts a.all?{|x| x==max || x==min || x==mid} ? "YES" : "NO"

gets
a=gets.split.map(&:to_i).group_by{|e|e}.map(&:first).sort
puts a.size<=2 || (a.size==3&&a[2]-a[1]==a[1]-a[0]) ? :YES : :NO

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

puts (a.size <= 2 || (a.size == 3 && a[1]-a[0] == a[2]-a[1])) ? 'YES' : 'NO'

n =gets.to_i ; list = gets.chomp.split(" ").map(&:to_i).uniq.sort
puts (list.length <= 2 || (list.length <=3 && (2*list[1] == list[0] + list[2])))? "YES" : "NO"

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

a = arr[0]
arr.delete(a)
if arr.length > 0
  b = arr[0]
  arr.delete(b)
  if arr.length > 0
    c = arr[0]
    arr.delete(c)
    if arr.length > 0
      puts "NO"
    else
      lol = [a,b,c]
      x = lol.min
      z = lol.max
      lol.delete(x)
      lol.delete(z)
      if lol[0] * 2 == (x + z)
        puts "YES"
      else
        puts "NO"
      end
    end
  else
    puts "YES"
  end
else
  puts "YES"
end

n,*a=$<.read.split.map &:to_i
a.sort!.uniq!
n=a.size
x=a[-1]-a[0]
if n>3 or (n==3 and (x%2==1 or a[1]!=a[0]+x/2))
    puts :NO
else
    puts :YES
end

n = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
k = (a.max-a.min)/2
if a.uniq.count<3 || (a.uniq.count==3&&a.include?(k+a.min)&&a.include?(a.max-k)) then s="YES" else s="NO" end
puts s

n = gets
x = gets.split.map(&:to_i).sort.uniq
if (x.size <= 2) or (x.size == 3 and x[0]+x[2]==x[1]*2)
  puts "YES"
else
  puts"NO"
end

n = gets.to_i
a = gets.split.map(&:to_i)
au = a.uniq
goal = au.size == 1 ? au[0] : au.sort[1]
a1 = a.find{|e| e != goal}
x = a1 ? (goal - a1).abs : 0
puts a.all?{|e| (goal - e).abs == 0 || (goal - e).abs == x} ? 'YES' : 'NO'

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

if a.size <= 2 || (a.size == 3 && a[1]-a[0] == a[2]-a[1])
  puts 'YES'
else
  puts 'NO'
end

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

min = arr.min
max = arr.max

alpha = ((max - min) / 2.0)

ans = 'YES'

correctNum = (min + alpha)
#puts correctNum
arr.each do |i|
	if i != correctNum && i + alpha != correctNum && i - alpha != correctNum
		ans = 'NO'
		break
	end
end

puts ans

gets
a=gets.split.map(&:to_i).group_by{|e|e}.map(&:first).sort
puts (a.size==3&&a[2]-a[1]==a[1]-a[0]) || a.size==2 ? :YES : :NO

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

a = arr[0]
arr.delete(a)
if arr.length > 0
  b = arr[0]
  arr.delete(b)
  if arr.length > 0
    c = arr[0]
    arr.delete(c)
    if arr.length > 0
      puts "NO"
    else
      lol = [a,b,c]
      x = lol.min
      z = lol.max
      lol.delete(x)
      lol.delete(z)
      if lol[0] * 2 == (x + z)
        puts "YES"
      else
        puts "NO"
      end
    end
  else
    puts "NO"
  end
else
  puts "NO"
end

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

if a.uniq.count==3&&a.include?(((a.max-a.min)/2).to_i+a.min) then s="YES" else s="NO" end
puts s

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

if a.uniq.count<3 || (a.uniq.count==3&&a.include?(((a.max-a.min)/2)+a.min)) then s="YES" else s="NO" end
puts s

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

if a.uniq.count==3&&a.include?(((a.max-a.min)/2)+a.min) then s="YES" else s="NO" end
puts s

n = gets.to_i
a = gets.split.map(&:to_i)
sum = a.inject(&:+)
if sum % n == 0
  goal = sum / n
  a1 = a.find{|e| e != goal}
  if a1
    x = (goal - a1).abs
    puts a.all?{|e| (goal - e).abs == 0 || (goal - e).abs == x} ? 'YES' : 'NO'
  else
    puts 'YES'
  end
else
  puts 'NO'
end

n = gets.to_i
a = gets.split.map(&:to_i)
sum = a.inject(&:+)
if sum % n == 0
  goal = sum / n
  a1 = a.find{|e| e != goal}
  if a1
    x = (goal - a1).abs
    pos = a.count{|e| e - x == goal}
    neg = a.count{|e| e + x == goal}
    eq = a.count{|e| e == goal}
    puts pos == neg && pos + neg + eq == n ? 'YES' : 'NO'
  else
    puts 'YES'
  end
else
  puts 'NO'
end

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

if a.size == 1 || (a.size == 3 && a[1]-a[0] == a[2]-a[1])
  puts 'YES'
else
  puts 'NO'
end

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

min = arr.min
max = arr.max

alpha = (max - min) / 2

ans = 'YES'

correctNum = min + alpha
#puts correctNum
arr.each do |i|
	if i != correctNum && i + alpha != correctNum && i - alpha != correctNum
		ans = 'NO'
		break
	end
end

puts ans


As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form "command ip;" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers.  Each ip is of form "a.b.c.d" where a, b, c and d are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has m commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is "command ip;" Dustin has to replace it with "command ip; #name" where name is the name of the server with ip equal to ip.Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.

The first line of input contains two integers n and m (1 ≤ n, m ≤ 1000). The next n lines contain the names and ips of the servers. Each line contains a string name, name of the server and a string ip, ip of the server, separated by space (1 ≤ |name| ≤ 10, name only consists of English lowercase letters). It is guaranteed that all ip are distinct. The next m lines contain the commands in the configuration file. Each line is of form "command ip;" (1 ≤ |command| ≤ 10, command only consists of English lowercase letters). It is guaranteed that ip belongs to one of the n school servers.

Print m lines, the commands in the configuration file after Dustin did his task.

# cook your code here

n,m = gets.chomp.split

n = n.to_i
m = m.to_i

good = Array.new(n)
bad = Array.new(m)

for i in 0...n
    good[i] = gets.chomp.split
end

for i in 0...m
    bad[i] = gets.chomp.split
    #  bad[i][1] = bad[i][1].chop
    for j in 0...n
        if(bad[i][1].chop == good[j][1])
            puts bad[i][0] + " " + bad[i][1] + " #" + good[j][0]
        end
    end
end


The $$$\text{$$$gcdSum$$$}$$$ of a positive integer is the $$$gcd$$$ of that integer with its sum of digits. Formally, $$$\text{$$$gcdSum$$$}(x) = gcd(x, \text{ sum of digits of } x)$$$ for a positive integer $$$x$$$. $$$gcd(a, b)$$$ denotes the greatest common divisor of $$$a$$$ and $$$b$$$ — the largest integer $$$d$$$ such that both integers $$$a$$$ and $$$b$$$ are divisible by $$$d$$$.For example: $$$\text{$$$gcdSum$$$}(762) = gcd(762, 7 + 6 + 2)=gcd(762,15) = 3$$$.Given an integer $$$n$$$, find the smallest integer $$$x \ge n$$$ such that $$$\text{$$$gcdSum$$$}(x) > 1$$$.

The first line of input contains one integer $$$t$$$ $$$(1 \le t \le 10^4)$$$ — the number of test cases.  Then $$$t$$$ lines follow, each containing a single integer $$$n$$$ $$$(1 \le n \le 10^{18})$$$. All test cases in one test are different.

Output $$$t$$$ lines, where the $$$i$$$-th line is a single integer containing the answer to the $$$i$$$-th test case.

def digitSum(num)
  s = 0
  while num > 0
    s += num % 10
    num = num / 10
  end
  s
end

gets.to_i.times {
  n = gets.to_i

  while true
    s = digitSum n
    o = n.gcd s
    if o > 1
      puts n
      break
    end
    n += 1
  end
}

def digitSum(num)
  s = 0
  while num > 0
    s += num % 10
    num = num / 10
  end
  s
end

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

t = gets.to_i
(1..t).each { |i|
  n = gets.to_i

  while true
    s = digitSum n
    o = gcd1(n, s)
    if o > 1
      puts n
      break
    end
    n += 1
  end
}

def gs(n)
  s=n.to_s.chars.map(&:to_i).sum
  return n.gcd(s)
end
gets.to_i.times do
  n=gets.to_i
  i=n
  while
    g=gs(i)
    if g>1
      puts i
      break
    end
    i+=1
  end
end

t = gets.to_i
t.times{
  x = gets.to_i
  (x..x+100).each{|x|if x.gcd(x.digits.sum)>1 then p x;break end}
}


Let $$$a$$$ be a matrix of size $$$r \times c$$$ containing positive integers, not necessarily distinct. Rows of the matrix are numbered from $$$1$$$ to $$$r$$$, columns are numbered from $$$1$$$ to $$$c$$$. We can construct an array $$$b$$$ consisting of $$$r + c$$$ integers as follows: for each $$$i \in [1, r]$$$, let $$$b_i$$$ be the greatest common divisor of integers in the $$$i$$$-th row, and for each $$$j \in [1, c]$$$ let $$$b_{r+j}$$$ be the greatest common divisor of integers in the $$$j$$$-th column. We call the matrix diverse if all $$$r + c$$$ numbers $$$b_k$$$ ($$$k \in [1, r + c]$$$) are pairwise distinct. The magnitude of a matrix equals to the maximum of $$$b_k$$$.For example, suppose we have the following matrix: $$$\begin{pmatrix} 2 & 9 & 7\\ 4 & 144 & 84 \end{pmatrix}$$$ We construct the array $$$b$$$:  $$$b_1$$$ is the greatest common divisor of $$$2$$$, $$$9$$$, and $$$7$$$, that is $$$1$$$;  $$$b_2$$$ is the greatest common divisor of $$$4$$$, $$$144$$$, and $$$84$$$, that is $$$4$$$;  $$$b_3$$$ is the greatest common divisor of $$$2$$$ and $$$4$$$, that is $$$2$$$;  $$$b_4$$$ is the greatest common divisor of $$$9$$$ and $$$144$$$, that is $$$9$$$;  $$$b_5$$$ is the greatest common divisor of $$$7$$$ and $$$84$$$, that is $$$7$$$. So $$$b = [1, 4, 2, 9, 7]$$$. All values in this array are distinct, so the matrix is diverse. The magnitude is equal to $$$9$$$.For a given $$$r$$$ and $$$c$$$, find a diverse matrix that minimises the magnitude. If there are multiple solutions, you may output any of them. If there are no solutions, output a single integer $$$0$$$.

The only line in the input contains two space separated integers $$$r$$$ and $$$c$$$ ($$$1 \leq r,c \leq 500$$$) — the number of rows and the number of columns of the matrix to be found.

If there is no solution, output a single integer $$$0$$$. Otherwise, output $$$r$$$ rows. The $$$i$$$-th of them should contain $$$c$$$ space-separated integers, the $$$j$$$-th of which is $$$a_{i,j}$$$ — the positive integer in the $$$i$$$-th row and $$$j$$$-th column of a diverse matrix minimizing the magnitude. Furthermore, it must hold that $$$1 \leq a_{i,j} \leq 10^9$$$. It can be shown that if a solution exists, there is also a solution with this additional constraint (still having minimum possible magnitude).

NoteIn the first example, the GCDs of rows are $$$b_1 = 4$$$ and $$$b_2 = 1$$$, and the GCDs of columns are $$$b_3 = 2$$$ and $$$b_4 = 3$$$. All GCDs are pairwise distinct and the maximum of them is $$$4$$$. Since the GCDs have to be distinct and at least $$$1$$$, it is clear that there are no diverse matrices of size $$$2 \times 2$$$ with magnitude smaller than $$$4$$$.In the second example, no matter what $$$a_{1,1}$$$ is, $$$b_1 = b_2$$$ will always hold, so there are no diverse matrices.

require 'set'; require 'prime'
INF=Float::INFINITY; MOD=10**9+7
r,c = gets.chomp.split.map(&:to_i)
if r==1 && c==1
  puts 0
  exit
end

if c == 1
  r.times do |i|
    puts i+2
  end
  exit
elsif r == 1
  puts (2..(c+1)).to_a.join(' ')
  exit
end

r.times do |i|
  num = c + 1 + i
  tmp = []
  c.times do |j|
    tmp.push num * (j+1)
  end
  puts tmp.join(' ')
end


Polycarp often uses his smartphone. He has already installed $$$n$$$ applications on it. Application with number $$$i$$$ takes up $$$a_i$$$ units of memory.Polycarp wants to free at least $$$m$$$ units of memory (by removing some applications).Of course, some applications are more important to Polycarp than others. He came up with the following scoring system — he assigned an integer $$$b_i$$$ to each application:   $$$b_i = 1$$$ — regular application;  $$$b_i = 2$$$ — important application. According to this rating system, his phone has $$$b_1 + b_2 + \ldots + b_n$$$ convenience points.Polycarp believes that if he removes applications with numbers $$$i_1, i_2, \ldots, i_k$$$, then he will free $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ units of memory and lose $$$b_{i_1} + b_{i_2} + \ldots + b_{i_k}$$$ convenience points.For example, if $$$n=5$$$, $$$m=7$$$, $$$a=[5, 3, 2, 1, 4]$$$, $$$b=[2, 1, 1, 2, 1]$$$, then Polycarp can uninstall the following application sets (not all options are listed below):   applications with numbers $$$1, 4$$$ and $$$5$$$. In this case, it will free $$$a_1+a_4+a_5=10$$$ units of memory and lose $$$b_1+b_4+b_5=5$$$ convenience points;  applications with numbers $$$1$$$ and $$$3$$$. In this case, it will free $$$a_1+a_3=7$$$ units of memory and lose $$$b_1+b_3=3$$$ convenience points.  applications with numbers $$$2$$$ and $$$5$$$. In this case, it will free $$$a_2+a_5=7$$$ memory units and lose $$$b_2+b_5=2$$$ convenience points. Help Polycarp, choose a set of applications, such that if removing them will free at least $$$m$$$ units of memory and lose the minimum number of convenience points, or indicate that such a set does not exist.

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 two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the number of applications on Polycarp's phone and the number of memory units to be freed. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the number of memory units used by applications. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 2$$$) — the convenience points of each application. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output on a separate line:    -1, if there is no set of applications, removing which will free at least $$$m$$$ units of memory;  the minimum number of convenience points that Polycarp will lose if such a set exists.

NoteIn the first test case, it is optimal to remove applications with numbers $$$2$$$ and $$$5$$$, freeing $$$7$$$ units of memory. $$$b_2+b_5=2$$$.In the second test case, by removing the only application, Polycarp will be able to clear only $$$2$$$ of memory units out of the $$$3$$$ needed.In the third test case, it is optimal to remove applications with numbers $$$1$$$, $$$2$$$, $$$3$$$ and $$$4$$$, freeing $$$10$$$ units of memory. $$$b_1+b_2+b_3+b_4=6$$$.In the fourth test case, it is optimal to remove applications with numbers $$$1$$$, $$$3$$$ and $$$4$$$, freeing $$$12$$$ units of memory. $$$b_1+b_3+b_4=4$$$.In the fifth test case, it is optimal to remove applications with numbers $$$1$$$ and $$$2$$$, freeing $$$5$$$ units of memory. $$$b_1+b_2=3$$$.

INF = 10**18

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

	a1 = (0...n).select { b[_1] == 1 }.map { a[_1] }.sort.reverse
	a2 = (0...n).select { b[_1] == 2 }.map { a[_1] }.sort.reverse

	sum1 = [0] * -~a1.size
	a1.size.times { |i| sum1[i + 1] = sum1[i] + a1[i] }
	sum2 = [0] * -~a2.size
	a2.size.times { |i| sum2[i + 1] = sum2[i] + a2[i] }

	ans =
		sum2.each_with_index.map do |s2, cnt2|
			cnt1 = sum1.bsearch_index { _1 >= m - s2 }
			cnt1 ? cnt2 * 2 + cnt1 : INF
		end.min

	puts ans < INF ? ans : -1
end

#!/usr/bin/env ruby

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

def pfr(ar)
  res = (0..ar.length).map{|x| 0}
  for i in (1..ar.length)
    res[i] = res[i-1] + ar[i-1];
  end
  return res
end

class Opt

  def initialize(mem, cost, units)
    ar = mem.zip(cost)
    @one = pfr(ar.select{|x, y| (y == 1)}.map{|x, y| x}.sort.reverse)
    @two = pfr(ar.select{|x, y| (y == 2)}.map{|x, y| x}.sort.reverse)
    @units = units
  end

  def bsearch(val)
    # find ind of two where two[i] >= val
    if @two[@two.length-1] < val
      return nil
    end
    l,r = [0, @two.length-1]
    while true
      if r-l <= 1
        return(@two[l] >= val ? l : r)
      end
      mid = (l+r).div(2)
      if @two[mid] >= val
        r = mid
      else
        l = mid
      end
    end
  end

  def cost(ones)
    if ones >= @one.length
      return nil
    end
    ind = self.bsearch(@units - @one[ones])
    return (ind ? (ones + 2*ind) : nil)
  end

  def ones
    @one.length
  end

end

tc = getar()[0]

for t in 1..tc
  n, m = getar
  mem = getar
  cost = getar

  opt = Opt.new(mem, cost, m)
  possible = (0..opt.ones).map{|x| opt.cost(x)}.select{|x| x}.min
  puts "#{possible ? possible : -1}"
end

gets.to_i.times do
  n,m=gets.split.map(&:to_i)
  a=gets.split.map(&:to_i)
  b=gets.split.map(&:to_i)
  a1=[]
  a2=[]
  n.times do |i|
    if b[i]==1
      a1 << a[i]
    else
      a2 << a[i]
    end
  end
  a1.sort!.reverse!
  a2.sort!.reverse!
  z1=a1.size
  z2=a2.size
  i=0
  k=0
  while i<z1&&k<m
    k+=a1[i]
    i+=1
  end
  i-=1
  if k<m
    j=0
    while j<z2&&k<m
      k+=a2[j]
      j+=1
    end
    min=i+1+j*2
    if k<m
      puts "-1"
      next
    end
  else
    min=i+1
    j=0
  end
  while i>=0
    k-=a1[i]
    i-=1
    while k<m&&j<z2
      k+=a2[j]
      j+=1
    end
    if k>=m&&(i+1)+j*2<min
      min=(i+1)+j*2
    end
  end
  puts min
end

INF = 10**18

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

	a1 = (0...m).select { b[_1] == 1 }.map { a[_1] }.sort.reverse
	a2 = (0...m).select { b[_1] == 2 }.map { a[_1] }.sort.reverse

	sum1 = [0] * -~a1.size
	a1.size.times { |i| sum1[i + 1] = sum1[i] + a1[i] }
	sum2 = [0] * -~a2.size
	a2.size.times { |i| sum2[i + 1] = sum2[i] + a2[i] }

	ans2 =
		sum2.each_with_index.map do |s2, cnt2|
			cnt1 = sum1.bsearch_index { _1 >= m - s2 }
			cnt1 ? cnt2 * 2 + cnt1 : INF
		end.min
	ans1 =
		sum1.each_with_index.map do |s1, cnt1|
			cnt2 = sum2.bsearch_index { _1 >= m - s1 }
			cnt2 ? cnt2 * 2 + cnt1 : INF
		end.min
	ans = [ans1, ans2].min

	puts ans < INF ? ans : -1
end

INF = 10**18

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

	a1 = (0...m).select { b[_1] == 1 }.map { a[_1] }.sort.reverse
	a2 = (0...m).select { b[_1] == 2 }.map { a[_1] }.sort.reverse

	sum1 = [0] * -~a1.size
	a1.size.times { |i| sum1[i + 1] = sum1[i] + a1[i] }
	sum2 = [0] * -~a2.size
	a2.size.times { |i| sum2[i + 1] = sum2[i] + a2[i] }

	ans =
		sum2.each_with_index.map do |s2, cnt2|
			cnt1 = sum1.bsearch_index { _1 >= m - s2 }
			cnt1 ? cnt2 * 2 + cnt1 : INF
		end.min
	puts ans < INF ? ans : -1
end


Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure:  Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j).  First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored.  Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell.  Now she is wondering how to determine the crop plants in some certain cells.

In the first line there are four positive integers n, m, k, t (1 ≤ n ≤ 4·104, 1 ≤ m ≤ 4·104, 1 ≤ k ≤ 103, 1 ≤ t ≤ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≤ a ≤ n, 1 ≤ b ≤ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≤ i ≤ n, 1 ≤ j ≤ m), which is a query that asks you the kind of crop plants of a cell (i, j).

For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.

Waste
Grapes
Carrots
Kiwis
Carrots
Carrots

NoteThe sample corresponds to the figure in the statement.

input=gets.split.map(&:to_i)
h=input[0]
w=input[1]
k=input[2]
q=input[3]
cnt=Array.new(h,0)
waste=[]
k.times{
    input=gets.split.map(&:to_i)
    input[0]-=1
    input[1]-=1
    waste.push(input)
    cnt[input[0]]+=1
}
q.times{
    input=gets.split.map(&:to_i)
    input[0]-=1
    input[1]-=1
    x=input[1]
    y=input[0]
    no=y*w+x
    is_was=0
    waste.each{|was|
        if was[0]<y then
            no-=1
        end
        if was[0]==y then
            if was[1]<=x then
                no-=1
            end
            if was[1]==x then
                is_was+=1
            end
        end
    }
    if is_was>0 then
        puts "Waste"
    elsif
        puts ["Carrots","Kiwis","Grapes"][no%3]
    end
}

require 'set';def f c,m;x,y=c;(x-1)*m+y;end;n,m,k,t=gets.split.map(&:to_i);d=[];z=Set.new;k.times{p=f gets.split.map(&:to_i), m;d<<p;z<<p};g=[];t.times{g<<(f gets.split.map(&:to_i), m)};g.each{|b| puts(z.include?(b) ? :Waste : [:Carrots,:Kiwis,:Grapes][(b-d.count{|v|v<b})%3-1])}

def f c,m;x,y=c;(x-1)*m+y;end;n,m,k,t=gets.split.map(&:to_i);d=[];k.times{p=f gets.split.map(&:to_i),m;d<<p};g=[];t.times{g<<(f gets.split.map(&:to_i),m)};g.each{|b|puts(d.include?(b) ? :Waste : [:Carrots,:Kiwis,:Grapes][(b-d.count{|v|v<b})%3-1])}

#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
require 'prime'
require 'mathn'
require 'matrix'
require 'set'
include Math
#=================================

def to_single_number coords, m
	x, y=coords
	(x-1)*m+y
end

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

bad_cells=[]
bad_cells_set=Set.new
k.times{
	hash_code = to_single_number gets.split.map(&:to_i), m

	bad_cells << hash_code
	bad_cells_set << hash_code
}
bad_cells.sort!

tests=[]
t.times{
	tests << (to_single_number gets.split.map(&:to_i), m)
}

fr = [:Carrots, :Kiwis, :Grapes]
tests.each{|coord|
	if bad_cells_set.include? coord
		puts :Waste
		next
	end

	bad_cells_before = bad_cells.count{|v| v<coord}
	remaining_cells = coord - bad_cells_before

	puts fr[remaining_cells%3-1]
}

def b_search(a, v)

  x0 = 0
  x1 = a.size - 1
  return nil if a[x0] == v || a[x1] == v

  return 0 if v < a[0]
  return a.size if v > a[x1]

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

  x1
end

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

a = []
k.times  do
  i, j = gets.split.map(&:to_i)
  a << (i-1)*m+(j-1)
end
a.uniq!
a.sort!

t.times do
  i, j = gets.split.map(&:to_i)
  pos = (i-1)*m+(j-1)

  v = b_search(a, pos)
  if v
    puts %w(Carrots Kiwis Grapes)[(pos-v)%3]
  else
    puts "Waste"
  end
end

n, m, k, t = gets.split.map(&:to_i)
A = Hash.new(0)
k.times do
  a, b = gets.split.map { |x| x.to_i - 1}
  A[a * m + b] = 1
end
M = Array.new
(A.keys.sort).each do |key|
  M << key
end
t.times do
  a, b = gets.split.map { |x| x.to_i - 1}
  key = a * m + b
  if A.has_key? key
    puts "Waste"
  else
    u = key - (M.select { |x| x < key }).size
    x = u % 3
    if x == 0
      puts "Carrots"
    elsif x == 1
      puts "Kiwis"
    elsif x == 2
      puts "Grapes"
    end
  end
end

n, m, k, t = gets.split.map(&:to_i)
A = Hash.new(0)
k.times do
  a, b = gets.split.map { |x| x.to_i - 1}
  A[a * m + b] = 1
end
#p A
M = Array.new
(A.keys.sort).each do |key|
  M << key
end
#p M
def search(a, l, h, b)
  #puts "Search l#{l} h#{h} b#{b}"
  mid = l + ((h - l) / 2).to_i

  if l == h
    if b < a[l]
      return (l - 1 < 0) ? 0 : a[l - 1]
    elsif b > a[l]
      return a[l]
    end
  end

  if l - h == 1
    l, h = h, l
  end

  if h - l == 1
    if b < a[l]
      return 0
    elsif b >= a[l] && b < a[h]
      return l + 1
    else
      return h + 1
    end
  elsif b > a[mid]
    return search(a, mid+1, h, b)
  elsif b < a[mid]
    return search(a, l, mid-1, b)
  else
    return 0
  end
end
t.times do
  a, b = gets.split.map { |x| x.to_i - 1}
  key = a * m + b
  if A.has_key? key
    puts "Waste"
  else
#    puts "Key #{key}"
#    bb = search(M, 0, M.size - 1, key)
#    puts "Key = #{key} -> #{bb}"
    u = key - search(M, 0, M.size - 1, key)
    x = u % 3
    if x == 0
      puts "Carrots"
    elsif x == 1
      puts "Kiwis"
    elsif x == 2
      puts "Grapes"
    end
  end
end

n, m, k, t = gets.split.map(&:to_i)
A = Hash.new(0)
k.times do
  a, b = gets.split.map { |x| x.to_i - 1}
  A[a * m + b] = 1
end
#p A
M = Array.new
(A.keys.sort).each do |key|
  M << key
end
#p M
def search(a, l, h, b)
  #puts "Search l#{l} h#{h} b#{b}"
  mid = l + ((h - l) / 2).to_i

  if l > h

    if l >= a.size
      if b < a.last
        return a.size - 1
      else
        return a.size
      end
    end

    if b < a[l]
      return l
    elsif b > a[l]
      return l + 1
    end
  end

  if h - l == 1
    if b < a[l]
      return 0
    elsif b >= a[l] && b < a[h]
      return l + 1
    else
      return h + 1
    end
  elsif b > a[mid]
    return search(a, mid+1, h, b)
  elsif b < a[mid]
    return search(a, l, mid-1, b)
  else
    return 0
  end
end
t.times do
  a, b = gets.split.map { |x| x.to_i - 1}
  key = a * m + b
  if A.has_key? key
    puts "Waste"
  else
#    puts "Key #{key}"
#    bb = search(M, 0, M.size - 1, key)
#    puts "Key = #{key} -> #{bb}"
    u = key - search(M, 0, M.size - 1, key)
    x = u % 3
    if x == 0
      puts "Carrots"
    elsif x == 1
      puts "Kiwis"
    elsif x == 2
      puts "Grapes"
    end
  end
end


Let A = {a1, a2, ..., an} be any permutation of the first n natural numbers {1, 2, ..., n}. You are given a positive integer k and another sequence B = {b1, b2, ..., bn}, where bi is the number of elements aj in A to the left of the element at = i such that aj ≥ (i + k).For example, if n = 5, a possible A is {5, 1, 4, 2, 3}. For k = 2, B is given by {1, 2, 1, 0, 0}. But if k = 3, then B = {1, 1, 0, 0, 0}.For two sequences X = {x1, x2, ..., xn} and Y = {y1, y2, ..., yn}, let i-th elements be the first elements such that xi ≠ yi. If xi < yi, then X is lexicographically smaller than Y, while if xi > yi, then X is lexicographically greater than Y.Given n, k and B, you need to determine the lexicographically smallest A.

The first line contains two space separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ n). On the second line are n integers specifying the values of B = {b1, b2, ..., bn}.

Print on a single line n integers of A = {a1, a2, ..., an} such that A is lexicographically minimal. It is guaranteed that the solution exists.

n,k,*b=gets(p).split.map(&:to_i)
a=[]
b.each_with_index.reverse_each{|c,i|
	j=a.size
	a.each_with_index{|d,l|
		if c<1
			j=l
			break
		end
		c-=1 if d>i+k
	}
	a.insert j,i+1
}
puts a*" "

n, k, *b = gets(p).split.map(&:to_i)
a = []
(0...n).reverse_each { |i|
    x = 0
    while x < a.size
        break if b[i] < 1
        b[i] -= 1 if a[x] > i + k
        x += 1
    end
    a.insert x, i + 1
}
puts a * " "

n,k,*b=gets(p).split.map(&:to_i)
a=[]
(0...n).reverse_each {|i|
    x=0
    while x<a.size
        break if b[i]<1
        b[i]-=1 if a[x]>i+k
        x+=1
    end
    a.insert x,i+1
}
puts a*" "

n, k, *b = gets(p).split.map(&:to_i)
a = []
for i in (n - 1).downto(0)
    x = a.size
    for j in 0...x
        if b[i] < 1
            x = j
            break
        end
        b[i] -= 1 if a[j] > i + k
    end
    a.insert x, i + 1
end
puts a * " "

def generate(a, k)
  1.upto(a.size).map do |i|
    pos = a.index(i)
    (0..pos-1).count{|j| a[j] >= i+k}
  end
end

def ok?(a, b, k)
  generate(a, k) == b
end

def hoge
  n = 1000
  k = 5
  b = generate((1..n).to_a.shuffle, k)
  puts [n, k]*" "
  puts b*" "
  exit
end

def solve(n, k, b)
  o = ((n-k+1)..n).to_a
  (n-k).downto(1) do |i|
    c = 0
    j = 0
    while c < b[i-1]
      c += 1 if o[j] >= i+k
      j += 1
    end
    o[j,0] = i
  end
  o
end

def test
  n = 9
  k = 4
  h = {}
  (1..n).to_a.permutation do |a|
    b = generate(a, k)
    unless h[b]
      a2 = solve(n, k, b)
      p [a, b, a2] unless a == a2
      h[b] = true
    end
  end

  exit
end

#test

n, k = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
o = solve(n, k, b)
puts o*" "


We call two numbers $$$x$$$ and $$$y$$$ similar if they have the same parity (the same remainder when divided by $$$2$$$), or if $$$|x-y|=1$$$. For example, in each of the pairs $$$(2, 6)$$$, $$$(4, 3)$$$, $$$(11, 7)$$$, the numbers are similar to each other, and in the pairs $$$(1, 4)$$$, $$$(3, 12)$$$, they are not.You are given an array $$$a$$$ of $$$n$$$ ($$$n$$$ is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.For example, for the array $$$a = [11, 14, 16, 12]$$$, there is a partition into pairs $$$(11, 12)$$$ and $$$(14, 16)$$$. The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even positive integer $$$n$$$ ($$$2 \le n \le 50$$$) — length of array $$$a$$$. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$).

For each test case print:   YES if the such a partition exists,  NO otherwise.  The letters in the words YES and NO can be displayed in any case.

NoteThe first test case was explained in the statement.In the second test case, the two given numbers are not similar.In the third test case, any partition is suitable.

gets.to_i.times {
    gets
    a, b=gets.split.map(&:to_i).partition(&:odd?)
    puts ((a.size.even? or a.any?{|x| b.index{|y| (y-x).abs==1}}) ? :YES : :NO)
}

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |el|
    ev << el if el.even?
    od << el if el.odd?
  }
  flg = false
  od.each { |el|
    ev.each { |el2|
      if (el - el2).abs == 1
        flg = true
        break
      end
    }
  }
  if od.size.even? && ev.size.even?
    puts "YES"
  elsif flg == true
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |el|
    ev << el if el.even?
    od << el if el.odd?
  }
  od = od.sort
  ev = ev.sort
  flg = false
  od.each { |el|
    ev.each { |el2|
      if (el - el2).abs == 1
        flg = true
        break
      end
    }
  }
  if od.size.even? && ev.size.even?
    puts "YES"
  elsif flg == true
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times do
  solve
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i).sort
  even = []
  odd = []
  for i in 0...n do
    if a[i] % 2 == 0
      even.push(a[i])
    else
      odd.push(a[i])
    end
  end
  ok = false
  if odd.length % 2 == 1
    odd.each do |v|
      if even.include?(v - 1) || even.include?(v + 1)
        ok = true
        break
      end
    end
  else
    ok = true
  end
  puts ok ? "YES" : "NO"
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).sort
	odd = a.count { _1 % 2 == 1 }
	if odd.odd?
		puts a.each_cons(2).any? { _2 - _1 == 1 } ? 'YES' : 'NO'
	else
		puts 'YES'
	end
end

gets.strip.to_i.times do |t|
  _ = gets.strip.to_i
  a = gets.strip.split(' ').map(&:to_i).sort
  # puts a.group_by { |e| e % 2 }.inspect
  diffs = 0
  a.each_with_index do |e, i|
    next if i.zero?
    diffs += 1 if a[i] - a[i-1] == 1
  end
  even = a.select { |e| e.even? }.size
  odd = a.select { |e| e.odd? }.size
  if even == a.size or odd == a.size
    puts "YES"
  elsif even.even? && odd.even?
    puts "YES"
  elsif diffs > 0
    puts "YES"
  else
    puts "NO"
  end
end

gets.to_i.times {
    gets
    a, b=gets.split.map(&:to_i).partition(&:odd?)
    if a.size.even?
        puts :YES
    else
        puts (a.any?{|x| b.index{|y| (y-x).abs==1}} ? :YES : :NO)
    end
}

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = 0
  ev = 0
  mn_ev = 101
  mn_od = 101
  arr.each { |el|
    od += 1 if el.even?
    ev += 1 if el.odd?
    mn_ev = [mn_ev, el].min if el.even?
    mn_od = [mn_od, el].min if el.odd?
  }

  if od.even? && ev.even?
    puts "YES"
  elsif (mn_ev - mn_od).abs == 1
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |vl|
    ev << vl if vl.even?
    od << vl if vl.odd?
  }
  od = od.sort
  ev = ev.sort.reverse
  done = 0
  od.each { |vl|
    if !ev.empty?
      if (ev.last - vl).abs == 1
        ev.pop
        done += 1
        done = od.size if done > od.size
      end
    end
  }
  if ev.size.even? && (od.size - done).even?
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []

  arr.each { |el|
    ev << el if el.even?
    od << el if el.odd?
  }

  od = od.sort
  ev = ev.sort

  flg = false
  od.each_with_index { |el, idx|
    if !ev[idx].nil?
      if (el - ev[idx]).abs == 1
          flg = true
          break
      end
    end
  }

  if od.size.even? && ev.size.even?
    puts "YES"
  elsif flg == true
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |vl|
    ev << vl if vl.even?
    od << vl if vl.odd?
  }
  od = od.sort
  ev = ev.sort.reverse
  done = 0
  od.each { |vl|
    if (od.size - done).even? and ev.size.even?
      puts "YES"
      return nil
    end
    if !ev.empty?
      if (ev.last - vl).abs == 1
        ev.pop
        done += 1
        done = od.size if done > od.size
      end
    end
  }
  puts "NO"
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |vl|
    ev << vl if vl.even?
    od << vl if vl.odd?
  }
  od = od.sort
  ev = ev.sort.reverse
  od.each { |vl|
    if !ev.empty?
      if (ev.last - vl).abs != 1
        puts "NO"
        return nil
      end
      ev.pop
    end
  }
  puts "YES"
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |vl|
    ev << vl if vl.even?
    od << vl if vl.odd?
  }
  od = od.sort
  ev = ev.sort.reverse
  od.each { |vl|
    if !ev.empty?
      if (ev.last - vl).abs == 1
        ev.pop
      end
    end
  }
  puts "YES" if ev.size.even? && od.size.even?
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |vl|
    ev << vl if vl.even?
    od << vl if vl.odd?
  }
  if od.size.even? && ev.size.even?
    puts "YES"
    return nil
  end
  od = od.sort
  ev = ev.sort.reverse
  done = 0
  od.each { |vl|
    if !ev.empty?
      if (ev.last - vl).abs == 1
        ev.pop
        done += 1
        done = od.size if done > od.size
      end
    end
  }
  if ev.size.even? && (od.size - done).even?
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = 0
  ev = 0
  mn_ev = 101
  mn_od = 101
  arr.each { |el|
    od += 1 if el.even?
    ev += 1 if el.odd?
    mn_ev = [mn_ev, el].min if el.even?
    mn_od = [mn_od, el].min if el.odd?
  }
  if od.size.even? && ev.size.even?
    puts "YES"
  elsif (mn_ev - mn_od).abs == 1
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |vl|
    ev << vl if vl.even?
    od << vl if vl.odd?
  }
  od = od.sort
  ev = ev.sort.reverse
  done = 0
  od.each { |vl|
    if (od.size - done).even? && ev.size.even?
      puts "YES"
      return nil
    end
    if !ev.empty?
      if (ev.last - vl).abs == 1
        ev.pop
        done += 1
        done = od.size if done > od.size
      end
    end
  }
  puts "NO"
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  p arr
  od = 0
  ev = 0
  arr.each { |vl|
    ev += 1 if vl.even?
    od += 1 if vl.odd?
  }
  if ev >= od && (ev - od).even?
    puts "YES"
  else
    puts "NO"
  end

end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |vl|
    ev << vl if vl.even?
    od << vl if vl.odd?
  }
  if od.size > ev.size
    puts "NO"
    #return nil
  end
  od = od.sort
  ev = ev.sort.reverse
  od.each { |vl|
    if !ev.empty?
      if (ev.last - vl).abs != 1
        puts "NO"
        return nil
      end
    end
  }
  puts "YES"
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = 0
  ev = 0
  arr.each { |vl|
    ev += 1 if vl.even?
    od += 1 if vl.odd?
  }
  if ev >= od && (ev - od).even?
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |vl|
    ev << vl if vl.even?
    od << vl if vl.odd?
  }
  if od.size > ev.size
    puts "NO"
    return nil
  end
  od = od.sort
  ev = ev.sort.reverse
  od.each { |vl|
    if !ev.empty?
      if (ev.last - vl).abs != 1
        puts "NO"
        return nil
      end
    end
  }
  puts "YES"
end

gets.strip.to_i.times do
  solve
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i).sort
  skip = false
  even = 0
  for i in 0...n do
    if !skip
      if i < n - 1 && a[i + 1] - a[i] == 1
        skip = true
      else
        even += 1 if a[i] % 2 == 0
      end
    else
      skip = false
    end
  end
  puts (even % 2 == 0) ? "YES" : "NO"
end

gets.strip.to_i.times do |t|
  _ = gets.strip.to_i
  a = gets.strip.split(' ').map(&:to_i).sort
  # puts a.group_by { |e| e % 2 }.inspect
  diffs = 0
  a.each_with_index do |e, i|
    next if i.zero?
    diffs += 1 if a[i] - a[i-1] == 1
  end
  even = a.select { |e| e.even? }.size
  odd = a.select { |e| e.odd? }.size
  if even == a.size or odd == a.size
    puts "YES"
  elsif even == odd && even.even?
    puts "YES"
  elsif diffs > 0
    puts "YES"
  else
    puts "NO"
  end
end

gets.to_i.times {
    gets
    a, b=gets.split.map(&:to_i).partition(&:odd?)
    puts (a.size.even? or a.any?{|x| b.index{|y| (y-x).abs==1}} ? :YES : :NO)
}

gets.to_i.times {
    gets
    puts (gets.split.map(&:to_i).sort.each_slice(2).all?{|x,y|y-x==1 or (x+y)%2==0} ? :YES : :NO)
}

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |vl|
    ev << vl if vl.even?
    od << vl if vl.odd?
  }
  od = od.sort
  ev = ev.sort.reverse
  done = 0
  od.each { |vl|
    if !ev.empty?
      if (ev.last - vl).abs == 1
        ev.pop
        done += 1
      end
    end
  }
  if ev.size.even? && (od.size - done).even?
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |vl|
    ev << vl if vl.even?
    od << vl if vl.odd?
  }
  od = od.sort
  ev = ev.sort.reverse
  done = 0
  od.each { |vl|
    if (od.size - done).even? && ev.size.even?
      puts "YES"
      return nil
    end
    if !ev.empty?
      if (ev.last - vl).abs == 1
        ev.pop
        done += 1
        done = od.size if done > od.size
      end
    end
  }
  if (od.size - done).even? && ev.size.even?
    puts "YES"
    return nil
  end
  puts "NO"
end

gets.strip.to_i.times do
  solve
end

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i);
  od = []
  ev = []
  arr.each { |vl|
    ev << vl if vl.even?
    od << vl if vl.odd?
  }
  od = od.sort
  ev = ev.sort.reverse
  done = 0
  od.each { |vl|
    if (od.size - done).even? & ev.size.even?
      puts "YES"
      return nil
    end
    if !ev.empty?
      if (ev.last - vl).abs == 1
        ev.pop
        done += 1
        done = od.size if done > od.size
      end
    end
  }
  puts "NO"
end

gets.strip.to_i.times do
  solve
end


You are given an angle $$$\text{ang}$$$. The Jury asks You to find such regular $$$n$$$-gon (regular polygon with $$$n$$$ vertices) that it has three vertices $$$a$$$, $$$b$$$ and $$$c$$$ (they can be non-consecutive) with $$$\angle{abc} = \text{ang}$$$ or report that there is no such $$$n$$$-gon.  If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed $$$998244353$$$.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 180$$$) — the number of queries.  Each of the next $$$T$$$ lines contains one integer $$$\text{ang}$$$ ($$$1 \le \text{ang} < 180$$$) — the angle measured in degrees.

For each query print single integer $$$n$$$ ($$$3 \le n \le 998244353$$$) — minimal possible number of vertices in the regular $$$n$$$-gon or $$$-1$$$ if there is no such $$$n$$$.

NoteThe answer for the first query is on the picture above.The answer for the second query is reached on a regular $$$18$$$-gon. For example, $$$\angle{v_2 v_1 v_6} = 50^{\circ}$$$.The example angle for the third query is $$$\angle{v_{11} v_{10} v_{12}} = 2^{\circ}$$$.In the fourth query, minimal possible $$$n$$$ is $$$180$$$ (not $$$90$$$).

gets.to_i.times do
    a = gets.to_i
    b = (a*2).gcd(360)
    if 360-a*2 == b
        puts 720/b
    else
        puts 360/b
    end
end

def done(a)
    for i in 3..1000
      if (a * i) % 180 == 0 and (a * i)/180  < i - 1
         return i
      end
    end
    return -1
end
for _ in 1..gets.to_i
    a = gets.to_i
    puts done(a)
    end

gets.to_i.times do
    a = gets.to_i
    if a < 90
        puts 360/(a*2).gcd(360)
    else
        puts 360/(180-a)
    end
end


After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i,  j,  k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!

The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.

Print one number — the quantity of triples (i,  j,  k) such that i,  j and k are pairwise distinct and ai·aj·ak is minimum possible.

NoteIn the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.

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

a = a.sort!
x = 1
y = 0
z = 0
stop = false
for i in 1...n
    if a[i] == a[0]
        x += 1
    else
        y += 1
        for j in i+1...n
            if a[j] == a[i]
                y += 1
            else
                z += 1
                for k in j+1...n
                    if a[k] == a[j]
                        z += 1
                    else
                        stop = true
                        break
                    end
                end
            end
            if stop || x + y + z == n
                break
            end
        end
    end
    if stop || x + y + z == n
        break
    end
end
quantity = 0
if x >= 3
    quantity = x*(x-1)*(x-2)/6
elsif x < 3 && x + y >= 3
    if x == 1
        quantity = y*(y-1)/2
    elsif x == 2
        quantity = y
    end
elsif x + y < 3 && x + y + z >= 3
    if x + y == 1
        quantity = z*(z-1)*(z-2)
    elsif x + y == 2
        quantity = z
    end
end

puts quantity

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

# combination nCr
def combi(n, r)
    q = 1
    1.upto(r){|k|q=q*(n-k+1)/k}
    return q
end

gets
ha = ascan.inject({}){|h,e| h[e]||=0; h[e]+=1; h}.sort

n = 0
a = []
while n < 3
    v,c = ha.shift
    n += c
    a << c
end
s = n-a[-1]
p 3-s <= a[-1] ? combi(a[-1],3-s) : a[-1]

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

gets
ha = ascan.inject({}){|h,e| h[e]||=0; h[e]+=1; h}.sort

n = 0
a = []
while n < 3
    v,c = ha.shift
    n += c
    a << c
end

p a[-1]

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

# combination nCr
def combi(n, r)
    q = 1
    1.upto(r){|k|q=q*(n-k+1)/k}
    return q
end

gets
ha = ascan.inject({}){|h,e| h[e]||=0; h[e]+=1; h}.sort

n = 0
a = []
while n < 3
    v,c = ha.shift
    n += c
    a << c
end

p 3 <= a[-1] ? combi(a[-1],3) : a[-1]


Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?

The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.

Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.

NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".

def isEqualStr(word1, word2)
	nStr = word2.length
	for i in 0 ... nStr
		isEqual = true
		j = 0
		while j < nStr and isEqual
			isEqual &= word1[j] == word2[(i + j) % nStr]
			j += 1
		end
		if isEqual
			return i
		end
	end

	return -1
end

n = gets.chomp.to_i
grid = []
for i in 0 ... n
	grid << gets.chomp
end

answer = true
for i in 0 ... n - 1
	if isEqualStr(grid[i], grid[i + 1]) == -1
		answer = false
	end
end

if not answer
	puts "-1"
else
	answer = (1 << 31)
	for i in 0 ... n

		auxAnswer = 0
		j = (i + 1) % n
		while i != j
			auxAnswer += isEqualStr(grid[i], grid[j])
			j = (j + 1) % n
		end
		answer = [answer, auxAnswer].min
	end
	puts answer
end

a=gets.to_i.times.map{gets.chomp.chars}
l=a[0].size
b=a.map{|e|
	idx=(0...l).select{|i|e.rotate(i)==a[0]}
	if idx.empty?
		p -1
		exit
	end
	idx
}
p (0...l).map{|i|b.map{|e|e.map{|f|(f+i)%l}.min}.reduce(:+)}.min

n = gets.strip.to_i
data = Array.new(n) { gets.strip }

inf = 10 ** 9
ans = data.map { |s|
    data.map do |ss|
        for i in (0..ss.length)
            break i if ss == s
            ss = ss[1..-1] + ss[0]
            break inf if i+1 == ss.length
        end
    end.reduce(:+)
}.min

puts (ans >= inf ? -1 : ans)

a=gets.to_i.times.map{gets.chomp.chars}
l=a[0].size
b=a.map{|e|
	idx=(0...l).find{|i|e.rotate(i)==a[0]}
	if !idx
		p -1
		exit
	end
	idx
}
p (0...l).map{|i|b.map{|e|(e+i)%l}.reduce(:+)}.min


You are given an array a1, a2, ..., an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?Definitions of subsegment and array splitting are given in notes.

The first line contains two integers n and k (1 ≤ k ≤ n ≤  105) — the size of the array a and the number of subsegments you have to split the array to. The second line contains n integers a1,  a2,  ...,  an ( - 109  ≤  ai ≤  109).

Print single integer — the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments.

NoteA subsegment [l,  r] (l ≤ r) of array a is the sequence al,  al + 1,  ...,  ar.Splitting of array a of n elements into k subsegments [l1, r1], [l2, r2], ..., [lk, rk] (l1 = 1, rk = n, li = ri - 1 + 1 for all i > 1) is k sequences (al1, ..., ar1), ..., (alk, ..., ark).In the first example you should split the array into subsegments [1, 4] and [5, 5] that results in sequences (1, 2, 3, 4) and (5). The minimums are min(1, 2, 3, 4) = 1 and min(5) = 5. The resulting maximum is max(1, 5) = 5. It is obvious that you can't reach greater result.In the second example the only option you have is to split the array into one subsegment [1, 5], that results in one sequence ( - 4,  - 5,  - 3,  - 2,  - 1). The only minimum is min( - 4,  - 5,  - 3,  - 2,  - 1) =  - 5. The resulting maximum is  - 5.

def ga
	return gets.split.map &:to_i
end
n,k = ga
a = ga
p [a.min, [a[-1],a[0]].max,a.max][k>2?2:k-1]

n, k = gets.split.map &:to_i
a = gets.split.map &:to_i
p [a.min, [a[0], a[-1]].max, a.max][[k, 3].min - 1]

class Solver2
  def self.solve(arr, k)
    return arr.min if k == 1
    return arr.max if k > 2
    return [arr.first, arr.last].max
  end
end
string = ARGF.read
arr = string.split("\n")
arr.map! { |elem| elem.strip }
arr1 = arr[0].split
arr2 = arr[1].split
arr1.map! { |elem| elem.split }
arr2.map! { |elem| elem.to_i }
puts Solver2.solve(arr2, arr1[1].first.to_i)
exit(true)

def ga
	return gets.split.map &:to_i
end
n,k = ga
a = ga
p [a.min, [a[-1],a[0]].max,a.max][k[0]>2?2:k[0]-1]


You are given three strings $$$s$$$, $$$t$$$ and $$$p$$$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose any character from $$$p$$$, erase it from $$$p$$$ and insert it into string $$$s$$$ (you may insert this character anywhere you want: in the beginning of $$$s$$$, in the end or between any two consecutive characters). For example, if $$$p$$$ is aba, and $$$s$$$ is de, then the following outcomes are possible (the character we erase from $$$p$$$ and insert into $$$s$$$ is highlighted):  aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ ade;  aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ dae;  aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ dea;  aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ bde;  aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ dbe;  aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ deb;  aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ ade;  aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ dae;  aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ dea; Your goal is to perform several (maybe zero) operations so that $$$s$$$ becomes equal to $$$t$$$. Please determine whether it is possible.Note that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Each query is represented by three consecutive lines. The first line of each query contains the string $$$s$$$ ($$$1 \le |s| \le 100$$$) consisting of lowercase Latin letters. The second line of each query contains the string $$$t$$$ ($$$1 \le |t| \le 100$$$) consisting of lowercase Latin letters. The third line of each query contains the string $$$p$$$ ($$$1 \le |p| \le 100$$$) consisting of lowercase Latin letters.

For each query print YES if it is possible to make $$$s$$$ equal to $$$t$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

4
ab
acxb
cax
a
aaaa
aaabbcc
a
aaaa
aabbcc
ab
baaa
aaaaa

NoteIn the first test case there is the following sequence of operation:   $$$s = $$$ ab, $$$t = $$$ acxb, $$$p = $$$ cax;  $$$s = $$$ acb, $$$t = $$$ acxb, $$$p = $$$ ax;  $$$s = $$$ acxb, $$$t = $$$ acxb, $$$p = $$$ a. In the second test case there is the following sequence of operation:   $$$s = $$$ a, $$$t = $$$ aaaa, $$$p = $$$ aaabbcc;  $$$s = $$$ aa, $$$t = $$$ aaaa, $$$p = $$$ aabbcc;  $$$s = $$$ aaa, $$$t = $$$ aaaa, $$$p = $$$ abbcc;  $$$s = $$$ aaaa, $$$t = $$$ aaaa, $$$p = $$$ bbcc.

def subseq(a, b, i, j)
  return true if i.zero?
  return false if j.zero?

  return subseq(a, b, i - 1, j - 1) if a[i-1] == b[j-1]
  return subseq(a, b, i, j - 1)
end

def char_cnt(s)
  s.split('').inject({}) { |m, c| m[c] = (m[c] || 0) + 1; m }
end

def solve(s, t, p)
  t_cnt = char_cnt(t)
  sp_cnt = char_cnt(s + p)
  (!subseq(s, t, s.size, t.size) or t_cnt.any? { |c, v| sp_cnt[c].nil? or sp_cnt[c] < v}) ? "NO" : "YES"
end

gets.strip.to_i.times do
  puts solve(gets.strip, gets.strip, gets.strip)
end

def subseq(a, b, i, j)
  return true if i.zero?
  return false if j.zero?

  return subseq(a, b, i - 1, j - 1) if a[i-1] == b[j-1]
  return subseq(a, b, i, j - 1)
end

def char_cnt(s)
  s.split('').inject({}) { |m, c| m[c] = (m[c] || 0) + 1; m }
end

def solve(s, t, p)
  t_cnt = char_cnt(t)
  sp_cnt = char_cnt(s + p)
  (!subseq(s, t, s.size, t.size) or sp_cnt.any? { |c, v| t_cnt[c] and v < t_cnt[c] }) ? "NO" : "YES"
end

gets.strip.to_i.times do
  puts solve(gets.strip, gets.strip, gets.strip)
end


Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.

In the first line of the input, you are given a single integer n (1 ≤ n ≤ 100) — the length of the side of the cake. Then follow n lines, each containing n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.

Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.

NoteIf we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are:   (1, 2) and (1, 3)  (3, 1) and (3, 3)  Pieces that share the same column are:   (2, 1) and (3, 1)  (1, 3) and (3, 3)

nn=gets.to_i
a = (1..nn).map{gets.strip}

def f(n)
  return 0 unless n
  return 0 if n < 2
  n == 2 ? 1 : (n-1)+f(n-1)
end

g1 = a.map{|x| n = x.gsub(/[^C]/, "").size; f(n)}
#p a
a = (0...nn).map{|i| (0...nn).map{|j| a[j][i] }.join }
#p a
g2 = a.map{|x| n = x.gsub(/[^C]/, "").size; f(n)}
#p g1, g2
g = (g1+g2).reduce(:+)
p g

#!/usr/bin/ruby
gets;a=$<.map{|e|e.chomp.chars}
r=0
[a,a.transpose].each{|b|b.each{|e|n=e.count('C');r+=n*(n-1)/2}}
p r

n = gets.chomp.to_i
rows = []
n.times { rows << gets.chomp.chars }
c = 0
rows.each { |row| c += (0..(row.count('C') - 1)).to_a.combination(2).to_a.length }
rows.transpose.each { |row| c += (0..(row.count('C') - 1)).to_a.combination(2).to_a.length }

puts c

n = gets.to_i
cake = []
n.times do
	cake.push(gets.split(''))
end

t = 0
for i in 0...n
	choc = 0
	for j in 0...n
		choc += 1 if cake[i][j] == 'C'
	end
	t += choc*(choc-1)/2
end

for i in 0...n
	choc = 0
	for j in 0...n
		choc += 1 if cake[j][i] == 'C'
	end
	t += choc*(choc-1)/2
end

puts t

a=gets.chomp.to_i
row=[]
clm=[]
a.times do
clm <<0
end
a.times do
temp=gets.chomp.split("")
t=0
0.upto(a-1) do |i|
if temp[i]=="C"
t+=1
clm[i]+=1
end
end
row << t
end
ans=0
row.each do |i|
if i>1
ans=ans+(i*(i-1))/2
end
end

clm.each do |i|
if i>1
ans=ans+(i*(i-1))/2
end
end
puts "#{ans}"

def combination_count(n, m)
  return 1 if n == m
  (1..n).inject(:*)/((1..m).inject(:*) * (1..n-m).inject(:*))
end

n = gets.to_i
cake = []
n.times do
  cake << gets.chomp.chars
end

cake_t = cake.transpose

ans = 0
(0..n-1).each do |i|
  if (c = cake[i].count('C')) >= 2
    ans += combination_count(c, 2)
  end
  if (c = cake_t[i].count('C')) >= 2
    ans += combination_count(c, 2)
  end
end

puts ans

class Integer
  def combination(k)
    if self < k
      return 0
    end
    self.factorial/(k.factorial*(self-k).factorial)
  end

  def permutation(k)
    self.factorial/(self-k).factorial
  end

  def factorial
    return 1 if self == 0
    (1..self).inject(:*)
  end
end

n = gets.to_i
a = Array.new()

n.times do
  a.push(gets.chomp.split(''))
end
r = Array.new(n, 0)
c = Array.new(n, 0)

n.times do |i|
  n.times do |j|
    if a[i][j] == 'C'
      r[j] += 1
    end
    if a[j][i] == 'C'
      c[j] += 1
    end
  end
end
ans = 0
n.times do |i|
  ans += r[i].combination(2) + c[i].combination(2)
end
puts ans

n = gets.chomp.to_i
cells = []
n.times do
  cells << gets.chomp
end
ans = 0
for i in 0...n
  r = 0
  c = 0
  for j in 0...n
    r += 1 if cells[i][j] == 'C'
    c += 1 if cells[j][i] == 'C'
  end
  ans += r * (r - 1) / 2
  ans += c * (c - 1) / 2
end

puts ans

n = gets.to_i
g = []
for i in 0...n
  r = gets.split('')
  g << r
end

def bin(n, k)
  if n < k
    0
  elsif k == 0 || n == k
    1
  else
    bin(n-1, k-1) + bin(n-1, k)
  end
end

ct = 0
for i in 0...n
  col = 0
  row = 0
  for j in 0...n
    row += g[i][j] == 'C' ? 1 : 0
    col += g[j][i] == 'C' ? 1 : 0
  end

  ct += bin(row, 2) + bin(col, 2)
end

puts ct

n = gets.to_i
a = n.times.map{gets.chomp.split('')}
sum = 0
def calc(arr, sum)
  arr.each do |x|
    c = x.count('C')
    sum += c * (c - 1) / 2
  end
  sum
end
r = calc(a, sum)
c = calc(a.transpose, r)
puts c

n = gets.to_i
a = []
n.times { a << gets.chomp.split('') }
b = a.transpose
joy = 0
(0...n).each do |i|
  c = a[i].count('C') - 1
  joy += (1 + c)*c/2
  c = b[i].count('C') - 1
  joy += (1 + c)*c/2
end
puts joy

def combination_count(n, m)
  (1..n).inject(:*)/(1..m).inject(:*)
end

n = gets.to_i
cake = []
n.times do
  cake << gets.chomp.chars
end

cake_t = cake.transpose

ans = 0
(0..n-1).each do |i|
  if (c = cake[i].count('C')) > 0
    ans += combination_count(c, 2)
  end
  if (c = cake_t[i].count('C')) > 0
    ans += combination_count(c, 2)
  end
end

puts ans


In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1, a2, ..., an. He remembered that he calculated gcd(ai, ai + 1, ..., aj) for every 1 ≤ i ≤ j ≤ n and put it into a set S. gcd here means the greatest common divisor.Note that even if a number is put into the set S twice or more, it only appears once in the set.Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.

The first line contains a single integer m (1 ≤ m ≤ 1000) — the size of the set S. The second line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 106) — the elements of the set S. It's guaranteed that the elements of the set are given in strictly increasing order, that means s1 < s2 < ... < sm.

If there is no solution, print a single line containing -1. Otherwise, in the first line print a single integer n denoting the length of the sequence, n should not exceed 4000. In the second line print n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the sequence. We can show that if a solution exists, then there is a solution with n not exceeding 4000 and ai not exceeding 106. If there are multiple solutions, print any of them.

NoteIn the first example 2 = gcd(4, 6), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among gcd(ai, ai + 1, ..., aj) for every 1 ≤ i ≤ j ≤ n.

n = gets.to_i
a = gets.split.map &:to_i
if a.any?{|i|i % a[0] > 0} then p -1 else puts 2 * n - 1, a * (" %d " % a[0]) end


There are $$$n$$$ districts in the town, the $$$i$$$-th district belongs to the $$$a_i$$$-th bandit gang. Initially, no districts are connected to each other.You are the mayor of the city and want to build $$$n-1$$$ two-way roads to connect all districts (two districts can be connected directly or through other connected districts).If two districts belonging to the same gang are connected directly with a road, this gang will revolt.You don't want this so your task is to build $$$n-1$$$ two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and each pair of directly connected districts belong to different gangs, or determine that it is impossible to build $$$n-1$$$ roads to satisfy all the conditions.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of districts. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the gang the $$$i$$$-th district belongs to. It is guaranteed that the sum of $$$n$$$ does not exceed $$$5000$$$ ($$$\sum n \le 5000$$$).

For each test case, print:   NO on the only line if it is impossible to connect all districts satisfying the conditions from the problem statement.  YES on the first line and $$$n-1$$$ roads on the next $$$n-1$$$ lines. Each road should be presented as a pair of integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n; x_i \ne y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are two districts the $$$i$$$-th road connects.  For each road $$$i$$$, the condition $$$a[x_i] \ne a[y_i]$$$ should be satisfied. Also, all districts should be reachable from each other (possibly, using intermediate districts).

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  au = a.uniq

  if au.size == 1
    puts 'NO'
  else
    v1 = a.index(au[0])
    v2 = a.index(au[1])
    edges = []
    edges << [v1, v2]

    a.each.with_index do |x, i|
      next if i == v1
      next if i == v2

      if x == a[v1]
        edges << [v2, i]
      else
        edges << [v1, i]
      end
    end

    puts 'YES'
    edges.each do |u, v|
      puts "#{u + 1} #{v + 1}"
    end
  end
end

gets.to_i.times do
  n = gets.to_i
  v = gets.split.map(&:to_i)
  p = (0...n).sort { |i, j| v[i] <=> v[j] }
  w = p.chunk { |i| v[i] }.map(&:last)
  if w.length == 1
    puts 'NO'
  else
    puts 'YES'
    w.drop(1).flatten.each do |x|
      puts "#{p[0] + 1} #{x + 1}"
    end
    w[0].drop(1).each do |x|
      puts "#{w[1][0] + 1} #{x + 1}"
    end
  end
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  hash = Hash.new(0)
  max = 0
  a.each do |v|
    hash[v] += 1
    if max < hash[v]
      max = hash[v]
    end
  end
  if max > n-1
    ans << "NO"
  else
    ans << "YES"
    one = 1
    two = 0
    for i in 1..n-1
      next if a[i] == a[0]
      two = i+1
      break
    end
    ans << "#{one} #{two}"
    for i in 1..n-1
      next if i+1 == two
      if a[i] != a[one-1]
        ans << "#{one} #{i+1}"
      else
        ans << "#{two} #{i+1}"
      end
    end
  end
end

puts ans

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  next puts 'NO' if a.count(a[0]) == n
  puts 'YES'
  i = 0
  j = a.index { |x| x != a[i] }
  puts "#{i + 1} #{j + 1}"
  n.times do |k|
    if i != k and j != k
      if a[i] == a[k]
        puts "#{j + 1} #{k + 1}"
      else
        puts "#{i + 1} #{k + 1}"
       end
    end
  end
end

def solve(n, a)
  result = []
  first = a.first
  second = -1
  a.each_with_index do |element, i|
    second = 1+i if element!=first
  end
  if second!=-1
    1.upto(n-1) do |i|
      if(a[i]!=first)
        result.push([1,i+1])
      else
        result.push([second, i+1])
      end
    end
  end
  result
end

(gets.to_i).times do
  n = gets.to_i
  a = gets.split(' ').map(&:to_i)
  b = solve(n,a)
  if(b.length == 0)
    puts "NO"
  else
    puts "YES"
    b.each do |i|
      puts "#{i[0]} #{i[1]}"
    end
  end
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  hash = Hash.new(0)
  max = 0
  city = 0
  a.each do |v|
    hash[v] += 1
    if max < hash[v]
      max = hash[v]
      city = v
    end
  end
  if max > n/2
    ans << "NO"
  else
    ans << "YES"
    pre = 0
    dist = Array.new(n+1,0)
    arr = Array.new(n,0)
    e = []
    n.times do |i|
      if a[i] == city
        e << i+1
        dist[i+1] = 1
      end
    end
    max.times do |i|
      arr[i*2] = e[i]
    end
    pre = 0
    for i in (max*2-1)..n-1
      for j in 0..n-1
        if a[j] != pre && dist[j+1] == 0
          arr[i] = j+1
          dist[j+1] = 1
          pre = a[j]
          break
        end
      end
    end
    (max-1).times do |i|
      for j in 0..n-1
        if dist[j+1] == 0
          arr[i*2+1] = j+1
          dist[j+1] = 1
          break
        end
      end
    end
    (n-1).times do |i|
      ans << "#{arr[i]} #{arr[i+1]}"
    end
  end
end

puts ans

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  hash = Hash.new(0)
  max = 0
  a.each do |v|
    hash[v] += 1
    if max < hash[v]
      max = hash[v]
    end
  end
  if max > (n+1)/2
    ans << "NO"
  else
    ans << "YES"
    one = 1
    two = 0
    for i in 1..n-1
      next if a[i] == a[0]
      two = i+1
      break
    end
    ans << "#{one} #{two}"
    for i in 1..n-1
      next if i+1 == two
      if a[i] != one
        ans << "#{one} #{i+1}"
      else
        ans << "#{two} #{i+1}"
      end
    end
  end
end

puts ans

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  hash = Hash.new(0)
  max = 0
  a.each do |v|
    hash[v] += 1
    if max < hash[v]
      max = hash[v]
    end
  end
  if max > n-1
    ans << "NO"
  else
    ans << "YES"
    one = 1
    two = 0
    for i in 1..n-1
      next if a[i] == a[0]
      two = i+1
      break
    end
    ans << "#{one} #{two}"
    for i in 1..n-1
      next if i+1 == two
      if a[i] != one
        ans << "#{one} #{i+1}"
      else
        ans << "#{two} #{i+1}"
      end
    end
  end
end

puts ans

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  hash = Hash.new(0)
  max = 0
  a.each do |v|
    hash[v] += 1
    if max < hash[v]
      max = hash[v]
    end
  end
  if max > n-1
    ans << "NO"
  else
    ans << "YES"
    one = 1
    two = 0
    for i in 1..n-1
      next if a[i] == a[0]
      two = i+1
      break
    end
    ans << "#{one} #{two}"
    for i in 1..n-1
      next if i+1 == two
      if a[i+1] != one
        ans << "#{one} #{i+1}"
      else
        ans << "#{two} #{i+1}"
      end
    end
  end
end

puts ans

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  hash = Hash.new(0)
  max = 0
  city = 0
  a.each do |v|
    hash[v] += 1
    if max < hash[v]
      max = hash[v]
      city = v
    end
  end
  if max > (n+1)/2
    ans << "NO"
  else
    ans << "YES"
    pre = 0
    dist = Array.new(n+1,0)
    arr = Array.new(n,0)
    e = []
    n.times do |i|
      if a[i] == city
        e << i+1
        dist[i+1] = 1
      end
    end
    max.times do |i|
      arr[i*2] = e[i]
    end
    pre = 0
    for i in (max*2-1)..n-1
      for j in 0..n-1
        if a[j] != pre && dist[j+1] == 0
          arr[i] = j+1
          dist[j+1] = 1
          pre = a[j]
          break
        end
      end
    end
    (max-1).times do |i|
      for j in 0..n-1
        if dist[j+1] == 0
          arr[i*2+1] = j+1
          dist[j+1] = 1
          break
        end
      end
    end
    (n-1).times do |i|
      ans << "#{arr[i]} #{arr[i+1]}"
    end
  end
end

puts ans


As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length li.The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle .Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing. Help sculptor!

The first line contains an integer n (3 ≤ n ≤ 105) — a number of rod-blanks. The second line contains n integers li (1 ≤ li ≤ 109) — lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.

Print the only integer z — the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the rods.

NoteIn the first example triangle with sides {1 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}. In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}.

n = readline.to_i
arr = readline.split(' ').collect(&:to_i).sort.reverse
puts 1 + arr[0] - arr[1..-1].inject(0, :+)

def solve(a)
  2*a.max - a.inject(:+) + 1
end

gets

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

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

l.sort!
max = l.pop
sum = l.reduce(:+)

puts [max - sum + 1, 0].max

lodNum = gets.chomp.to_i
input = gets.chomp.split(' ').map {|i| i.to_i}
input.sort!

sum = 0
flag = false
max = input[input.length - 1]
for i in (0...(input.length - 1))
	sum += input[i]
end

if !flag && sum > max
	puts '0'
else
	puts (max - sum + 1)
end

n = gets

parse_int = lambda { gets.split.map{|x| x.to_i} }

m = parse_int.call

m.sort!

last = m.pop
sum = 0
m.each { |a| sum+=a }
puts last-sum+1


You are given a string $$$s$$$ consisting of the characters 0, 1, and ?.Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...).Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can replace the characters ? to 0 or 1 (for each character, the choice is independent), so that the string becomes unstable.For example, the strings 0??10, 0, and ??? are beautiful, and the strings 00 and ?1??1 are not.Calculate the number of beautiful contiguous substrings of the string $$$s$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of test cases. The first and only line of each test case contains the string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$) consisting of characters 0, 1, and ?. It is guaranteed that the sum of the string lengths over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of beautiful substrings of the string $$$s$$$.


You are given a set of $$$2n+1$$$ integer points on a Cartesian plane. Points are numbered from $$$0$$$ to $$$2n$$$ inclusive. Let $$$P_i$$$ be the $$$i$$$-th point. The $$$x$$$-coordinate of the point $$$P_i$$$ equals $$$i$$$. The $$$y$$$-coordinate of the point $$$P_i$$$ equals zero (initially). Thus, initially $$$P_i=(i,0)$$$.The given points are vertices of a plot of a piecewise function. The $$$j$$$-th piece of the function is the segment $$$P_{j}P_{j + 1}$$$.In one move you can increase the $$$y$$$-coordinate of any point with odd $$$x$$$-coordinate (i.e. such points are $$$P_1, P_3, \dots, P_{2n-1}$$$) by $$$1$$$. Note that the corresponding segments also change.For example, the following plot shows a function for $$$n=3$$$ (i.e. number of points is $$$2\cdot3+1=7$$$) in which we increased the $$$y$$$-coordinate of the point $$$P_1$$$ three times and $$$y$$$-coordinate of the point $$$P_5$$$ one time:  Let the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it).Let the height of the plot be the maximum $$$y$$$-coordinate among all initial points in the plot (i.e. points $$$P_0, P_1, \dots, P_{2n}$$$). The height of the plot on the picture above is 3.Your problem is to say which minimum possible height can have the plot consisting of $$$2n+1$$$ vertices and having an area equal to $$$k$$$. Note that it is unnecessary to minimize the number of moves.It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^{18}$$$) — the number of vertices in a plot of a piecewise function and the area we need to obtain.

Print one integer — the minimum possible height of a plot consisting of $$$2n+1$$$ vertices and with an area equals $$$k$$$. It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.

NoteOne of the possible answers to the first example:  The area of this plot is 3, the height of this plot is 1.There is only one possible answer to the second example:  The area of this plot is 12, the height of this plot is 3.

def solution
  n, k = read_ints
  s = k/n
  s += 1 if s*n < k
  puts s
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']

N, K = gets.split.map(&:to_i)
puts (K-1)/N+1

n,k=gets.strip.split.map(&:to_i)
ans=0
ans += (k/n)
ans += 1 if k%n != 0
puts ans

# T = gets.chomp.to_i
# (0..T-1).map do |i|
#     N = gets.chomp.to_i
#     pN = (N/2).ceil
#     b = gets.chomp
#     max_bs = []
#     (0..(b.length - pN + 1)).map do |j|
#         sub_b = b[j..(j + pN - 1)]
#         sum_b = sub_b.split('').inject 0 do |s, e|
#             s += e.to_i
#         end
#         max_bs << sum_b
#     end
#     p "Case ##{i + 1}: #{max_bs.max}"
# end

n, k = gets.chomp.split " "
n = n.to_i
k = k.to_i
p (k.to_r / n).ceil

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

ans = k / n
if k % n != 0
    ans += 1
end

puts ans

n,k = gets.split.map(&:to_i)
puts (k+n-1)/n

n, k = gets.split.map &:to_i
print (k+n-1)/n

n, k = gets.chomp.split.map(&:to_i)
puts (n.to_f/k).ceil

def solution
  n, k = read_ints
  s = k/n
  s += 1 if s*k < n
  puts s
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']

n, k = gets.chomp.split.map(&:to_i)
puts (k.to_f/n).ceil

# T = gets.chomp.to_i
# (0..T-1).map do |i|
#     N = gets.chomp.to_i
#     pN = (N/2).ceil
#     b = gets.chomp
#     max_bs = []
#     (0..(b.length - pN + 1)).map do |j|
#         sub_b = b[j..(j + pN - 1)]
#         sum_b = sub_b.split('').inject 0 do |s, e|
#             s += e.to_i
#         end
#         max_bs << sum_b
#     end
#     p "Case ##{i + 1}: #{max_bs.max}"
# end

n, k = gets.chomp.split " "
n = n.to_i
k = k.to_i
p (k.to_f / n).ceil