Recently Vova found $$$n$$$ candy wrappers. He remembers that he bought $$$x$$$ candies during the first day, $$$2x$$$ candies during the second day, $$$4x$$$ candies during the third day, $$$\dots$$$, $$$2^{k-1} x$$$ candies during the $$$k$$$-th day. But there is an issue: Vova remembers neither $$$x$$$ nor $$$k$$$ but he is sure that $$$x$$$ and $$$k$$$ are positive integers and $$$k > 1$$$.Vova will be satisfied if you tell him any positive integer $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$. It is guaranteed that at least one solution exists. Note that $$$k > 1$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 10^9$$$) — the number of candy wrappers Vova found. It is guaranteed that there is some positive integer $$$x$$$ and integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.

Print one integer — any positive integer value of $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.

NoteIn the first test case of the example, one of the possible answers is $$$x=1, k=2$$$. Then $$$1 \cdot 1 + 2 \cdot 1$$$ equals $$$n=3$$$.In the second test case of the example, one of the possible answers is $$$x=2, k=2$$$. Then $$$1 \cdot 2 + 2 \cdot 2$$$ equals $$$n=6$$$.In the third test case of the example, one of the possible answers is $$$x=1, k=3$$$. Then $$$1 \cdot 1 + 2 \cdot 1 + 4 \cdot 1$$$ equals $$$n=7$$$.In the fourth test case of the example, one of the possible answers is $$$x=7, k=2$$$. Then $$$1 \cdot 7 + 2 \cdot 7$$$ equals $$$n=21$$$.In the fifth test case of the example, one of the possible answers is $$$x=4, k=3$$$. Then $$$1 \cdot 4 + 2 \cdot 4 + 4 \cdot 4$$$ equals $$$n=28$$$.

# Author : Fuad Ashraful Mehmet
#Date: 22th April

t=gets.to_i

def Solve()
    n=gets.to_i
    k=4
    a=3
    while n.modulo(a)!=0
        a+=k
        k<<=1
    end

    return n/a
end
(1).upto(t) do

    puts Solve()
end

gets.to_i.times do
	n = gets.to_i
	i = (2..64).find { |i| n % (2**i - 1) == 0 }
	puts n / (2**i - 1)
end

class Result
  def print_result
    n = gets.to_i
    2.upto(29) do |i|
      if n % (2**i - 1) == 0
        puts n / (2**i - 1)
        break
      end
    end
  end
end

gets.to_i.times do
  Result.new.print_result
end

1.upto(gets.chomp.to_i) do
  n = gets.chomp.to_i
  k = 2
  m = 4
  while n % (m-1) != 0
    m *= 2;
    k += 1;
  end
  puts n / (m-1)
end

number_of_testcases = gets.to_s.to_i

number_of_testcases.times do |i|

  n = gets.to_s.to_i
  s = 2
  loop do

    s *= 2
    t = s - 1
    if n % t == 0
      puts n / t
      break
    end
  end
end

gets.to_i.times do
  n = gets.to_i
  k = 2
  loop do
    s = 2**k - 1
    if n%s == 0
      puts n/s
      break
    end
    k += 1
  end
end

t = gets.to_i

1.upto(t) do
  n = gets.to_i

  2.upto(32) do |k|
    next unless n.modulo((2 ** k) - 1).zero?

    puts n.div((2 ** k) - 1)
    break
  end
end

t=gets.to_i
(1).upto(t) do
  n=gets.to_i
  k=4
  a=3
  while n.modulo(a)!=0
    a+=k
    k<<=1
  end
  puts n/a
end


DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b denotes taking a remainder after division a by b.However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the i-th insertion, you should output i. If no conflict happens, just output -1.

The first line contains two integers, p and n (2 ≤ p, n ≤ 300). Then n lines follow. The i-th of them contains an integer xi (0 ≤ xi ≤ 109).

Output a single integer — the answer to the problem.

p,n = gets.split.map{|i| i.to_i}
h=[]
n.times{|i| h<<gets.to_i % p;if h.count(h[-1])==2
	puts i+1
	exit
end}
puts -1

#!/usr/bin/ruby
p,n=gets.split.map(&:to_i)
h={}
n.times{|i|
	x=gets.to_i%p
	if h[x]
		p i+1
		exit
	end
	h[x]=1
}
puts -1

inp = gets
arr = inp.split(" ")
p = arr[0].to_i
n = arr[1].to_i

hash = {}
res = -1
for i in 1..n
    inp = gets
    num = inp.to_i
    if hash[num%p] == 1
        res = i
        break
    end
    hash[num%p] = 1
end

puts res

a=gets.chomp.split(" ")
hash={"0"=>0}
k=0
1.upto(a[0].to_i-1) do |i|
hash["#{i}"]=0
end

1.upto(a[1].to_i) do |i|
temp=(gets.chomp.to_i)%a[0].to_i
hash["#{temp}"]+=1
if hash["#{temp}"]>1 && k==0
k=i
end
end

if k==0
puts "-1"
else
puts "#{k}"
end

numbers = gets.split(' ')
p = numbers[0].to_i
n = numbers[1].to_i

conflicts = false
hashtable = Array.new()
n.times do |i|
  x = gets.to_i
  next if conflicts
  if hashtable[x % p].nil?
    hashtable[x % p] = x
  else
    conflicts = true
    puts i + 1
  end
end

puts -1 unless conflicts

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

hash = Array.new p
collision = -1

n.times { |i|
  x = gets.to_i
  next if collision != -1

  mod = x % p
  if hash[mod].nil?
    hash[mod] = x
  else
    collision = i+1
  end
}

puts collision

p, n = gets.split.map { |x| x.to_i }
vis = Array.new(p, false)

ans = -1
n.times do |i|
	x = gets.to_i % p
	if !vis[x] ;
		vis[x] = true
	elsif ans == -1 ;
		ans = i+1;
	end
end
puts ans

pn=gets.chomp.to_s.split(" ").map {|x| x.to_i}
def solve(pn)
  hash=Hash.new
  for i in 0...pn[1]
    h=gets.chomp.to_i
    if hash[h%pn[0]].nil?
      hash[h%pn[0]]=1
    else
      puts i+1
      return
    end
  end
  puts "-1"
end
solve(pn)

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

y = Array.new(n)

i = 0

while i < n

    z = gets.to_i % p

    if y[z] == nil

        y[z] = z

    else

        puts i + 1

        break

    end

    i += 1

end

puts -1 if i == n

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

myHash=Hash.new()

for i in 0...n do
    myHash[i]=nil
end

found=-1
for i in 1..n do
    x=gets.split[0].to_i
    h=x%p
    if(myHash[h]==nil)
        myHash[h]=x
    else
        found=i
        break
    end
end

p found

p, n = gets.split(" ").collect { |e|  e.to_i}

arr = Array.new(p) { |i|  0}
i = 1
while i <= n
    num = gets.to_i
    mod = num % p
    if arr[mod] == 1
        break
    end
    arr[mod] += 1
    i += 1
end
puts i == n + 1 ? "-1" : i

line = gets
p, n  = line.split(' ').map(&:to_i)
hash = []
ins = -1
(1..n).each do |order|
  number = gets.to_i
  if ins == -1
    index = number % p
    if hash[index] != nil
      ins = order
    else
      hash[index] = 1
    end
  end
end
puts ins

p, n = gets.chomp.split.map(&:to_i)
h = Array.new(p, false)
(1..n).each { |i|
  if h[r = gets.to_i % p]
    puts i
    exit
  else
    h[r] = true
  end
}
puts -1

h={}
p,n=gets.split.map &:to_i
n.times do |i|
	x=gets.to_i%p
	if h.has_key? x
		p i+1
		exit
	end
	h[x]=1
end
p (-1)

p, n = gets.split.map {|i| i.to_i}
a = Array.new(p)
for i in 0...n
  x = gets.to_i
  if a[x % p] != nil
    puts i + 1
    exit
  end
  a[x % p] = true
end
puts -1

pn = gets
params = pn.split(" ")
p = params[0].to_i
n = params[1].to_i
array = []
found = false
(1..n).each do |item|
  temp = gets.to_i % p
  if(array[temp] == nil) then
    array[temp] = true
  elsif(array[temp] == true && found == false) then
    found = item
  end
end
if(found == false) then
  puts "-1"
else
  puts found
end

pn = gets
params = pn.split(" ")
p = params[0].to_i
n = params[1].to_i
array = []
found = false
(1..n).each do |item|
  temp = gets.to_i % p
  if(array[temp] == nil) then
    array[temp] = true
  elsif(array[temp] == true && found == false) then
    found = item
  end
end
puts found

#!/usr/bin/ruby
p,n=gets.split.map(&:to_i)
h={}
n.times{|i|
	x=gets.to_i%p
	if h[x]
		p i+1
		exit
	end
	h[x]=1
}
p -1

numbers = gets.split(' ')
p = numbers[0].to_i
n = numbers[1].to_i

conflicts = false
hashtable = Array.new()
n.times do |i|
  x = gets.to_i
  if hashtable[x % p].nil?
    hashtable[x % p] = x
  else
    if hashtable[x % p] != x
      puts i + 1
      conflicts = true
    end
  end
end

puts -1 unless conflicts


Two integer sequences existed initially — one of them was strictly increasing, and the other one — strictly decreasing.Strictly increasing sequence is a sequence of integers $$$[x_1 < x_2 < \dots < x_k]$$$. And strictly decreasing sequence is a sequence of integers $$$[y_1 > y_2 > \dots > y_l]$$$. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.They were merged into one sequence $$$a$$$. After that sequence $$$a$$$ got shuffled. For example, some of the possible resulting sequences $$$a$$$ for an increasing sequence $$$[1, 3, 4]$$$ and a decreasing sequence $$$[10, 4, 2]$$$ are sequences $$$[1, 2, 3, 4, 4, 10]$$$ or $$$[4, 2, 1, 10, 4, 3]$$$.This shuffled sequence $$$a$$$ is given in the input.Your task is to find any two suitable initial sequences. One of them should be strictly increasing and the other one — strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ to increasing and decreasing sequences, print "NO".

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ to increasing and decreasing sequences, print "NO" in the first line. Otherwise print "YES" in the first line and any two suitable sequences. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing. In the second line print $$$n_i$$$ — the number of elements in the strictly increasing sequence. $$$n_i$$$ can be zero, in this case the increasing sequence is empty. In the third line print $$$n_i$$$ integers $$$inc_1, inc_2, \dots, inc_{n_i}$$$ in the increasing order of its values ($$$inc_1 < inc_2 < \dots < inc_{n_i}$$$) — the strictly increasing sequence itself. You can keep this line empty if $$$n_i = 0$$$ (or just print the empty line). In the fourth line print $$$n_d$$$ — the number of elements in the strictly decreasing sequence. $$$n_d$$$ can be zero, in this case the decreasing sequence is empty. In the fifth line print $$$n_d$$$ integers $$$dec_1, dec_2, \dots, dec_{n_d}$$$ in the decreasing order of its values ($$$dec_1 > dec_2 > \dots > dec_{n_d}$$$) — the strictly decreasing sequence itself. You can keep this line empty if $$$n_d = 0$$$ (or just print the empty line). $$$n_i + n_d$$$ should be equal to $$$n$$$ and the union of printed sequences should be a permutation of the given sequence (in case of "YES" answer).

n = gets.to_i
a = gets.split.map(&:to_i).sort
x = []
y = []
n.times do |i|
    if i == 0 || a[i] != a[i-1]
        x << a[i]
    else
        y << a[i]
    end
end
if x.uniq.size == x.size && y.uniq.size == y.size
    puts "YES",x.size,x.join(" "),y.size,y.reverse.join(" ")
else
    puts "NO"
end

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

inc = [a.shift]
dec = []
a = a.reduce([]) do |acc, x|
      x > inc.last ? inc.push(x) : acc.push(x)
      acc
    end

a.reverse!

dec.push(a.shift) if a.size > 0
a = a.reduce([]) do |acc, x|
      x < dec.last ? dec.push(x) : acc.push(x)
      acc
    end

if a.size == 0
  puts "YES"
  puts inc.size
  inc.each_with_index { |x, i| print " " if i > 0; print x }
  print "\n"
  puts dec.size
  dec.each_with_index { |x, i| print " " if i > 0; print x }
  print "\n"
else
  puts "NO"
end

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

h = Hash.new(0)

res = ""
a.each do |e|
  h[e] += 1
  res = "No" if h[e] > 2
end

if res == "No"
  puts res
else
  a.sort!
  b = a.select.with_index { |e, idx| idx.even? }
  c = a.select.with_index { |e, idx| idx.odd? }
  puts "Yes"
  puts b.count
  puts b.join(" ")
  puts c.count
  puts c.reverse.join(" ")
end

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

h = Hash.new(0)

res = ""
a.each do |e|
  h[e] += 1
  res = "No" if h[e] > 2
end

if res == "No"
  puts res
else
  a.sort!
  b = a.select.with_index { |e, idx| idx.even? }
  c = a.select.with_index { |e, idx| idx.odd? }
  puts "Yes"
  puts b.reduce(&:+)
  puts b.join(" ")
  puts c.reduce(&:+)
  puts c.reverse.join(" ")
end


Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a1, a2, ..., ak.Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another n - k cities, and, of course, flour delivery should be paid — for every kilometer of path between storage and bakery Masha should pay 1 ruble.Formally, Masha will pay x roubles, if she will open the bakery in some city b (ai ≠ b for every 1 ≤ i ≤ k) and choose a storage in some city s (s = aj for some 1 ≤ j ≤ k) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used).Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.

The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 105, 0 ≤ k ≤ n) — the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively. Then m lines follow. Each of them contains three integers u, v and l (1 ≤ u, v ≤ n, 1 ≤ l ≤ 109, u ≠ v) meaning that there is a road between cities u and v of length of l kilometers . If k > 0, then the last line of the input contains k distinct integers a1, a2, ..., ak (1 ≤ ai ≤ n) — the number of cities having flour storage located in. If k = 0 then this line is not presented in the input.

Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line. If the bakery can not be opened (while satisfying conditions) in any of the n cities, print  - 1 in the only line.

NoteImage illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened.

# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.chomp end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

N, M, K = gis
UVL = ngis M
ST = K > 0 ? gis : []

h = [-1] * (N + 1)
f = [true] * (N + 1)

ST.each do |a|
    f[a] = false
end

mn = nil

UVL.each do |u, v, l|
    next if !(f[u] ^ f[v])
    mn = l if mn.nil? || l < mn
end

puts mn.nil? ? -1 : mn

class Array
  def r
    self.map { |q| q.to_i }
  end
end

def read_line
  STDIN.gets.split(" ")
end

def read_to_array
  read_line.to_a
end

def read_numbers_to_array
  read_to_array.r
end

first = Array.new(100009)
second = Array.new(100009)
len = Array.new(100009)

cities, roads, k = read_numbers_to_array
for i in 0..roads - 1 do
  first[i], second[i], len[i] = read_numbers_to_array
end

shortest = -1
if k > 0
b = read_numbers_to_array
bakers = Array.new(cities + 9, false)

b.each do |i|
  bakers[i] = true
end

for i in 0..roads - 1 do
  if bakers[first[i]] != bakers[second[i]] && (shortest == - 1 || len[i] < shortest)
    shortest = len[i]
  end
end
end

puts shortest

n, m, k = gets.split.map(&:to_i)
v = m.times.map{gets.split.map(&:to_i)}
s = Array.new(n+1, false)
gets.split.map(&:to_i).each {|x| s[x] = true } if k>0
ans = nil
v.each { |a, b, l| ans = l if (s[a]^s[b])&&(ans.nil? || l<ans) }
puts ans.nil? ? -1 : ans

n, m, k = gets.split.map(&:to_i)
data = m.times.map{gets.split.map(&:to_i)}
storage = Array.new(n + 1, false)
arr = k > 0 ? gets.split.map(&:to_i) : []
arr.each{|x| storage[x] = true}
ans = nil
data.each do |a, b, l|
  ans = l if (storage[a] ^ storage[b]) && (ans.nil? || l < ans)
end
puts ans.nil? ? -1 : ans

 class Node
	attr_accessor :dest, :val

	def initialize dest, val
		@dest = dest
		@val = val
	end

	def to_s
		print "Dest : #{dest}, Val : #{val}"
	end
end

n, m, k = gets.chomp.split(' ').map(&:to_i)
found = false
nearest = Array.new(n + 1) { |i| i = {} }

m.times do
	u, v, l = gets.chomp.split(' ').map(&:to_i)

	if u != v
		if nearest[u].has_key? v
			if nearest[u][v] > l
				nearest[u][v] = l
			end
		else
			nearest[u][v] = l
		end

		if nearest[v].has_key? u
			if nearest[v][u] > l
				nearest[v][u] = l
			end
		else
			nearest[v][u] = l
		end
	end
end

storage = Array.new(n + 1) { |i| i = false }

if k > 0
	inputStorage = gets.chomp.split(' ').map(&:to_i)

	inputStorage.each do |i|
		storage[i] = true
	end
end

ans = 1000000000000

1.upto(n) do |city|
	next if !storage[city]

	nearest[city].each do |dest, val|
		if !storage[dest]
			ans = val if ans > val
			found = true
		end
	end
end

if !found
	puts -1
else
	puts ans
end

n, m, k = gets.split.map(&:to_i)
nn = 1000000000
h = Hash.new(nn)
m.times do
  a, b, l = gets.split.map(&:to_i)
  h[a] = [h[a], l].min
  h[b] = [h[b], l].min
end
arr = k > 0 ? gets.split.map(&:to_i) : []
mi = h[arr.min_by{|x| h[x]}]
puts mi.nil? || mi == nn ? -1 : mi

class Node
	attr_accessor :dest, :val

	def initialize dest, val
		@dest = dest
		@val = val
	end
end

n, m, k = gets.chomp.split(' ').map(&:to_i)
found = false
nearest = Array.new(n + 1) { |i| i = Node.new(-1, 100000000) }

m.times do
	u, v, l = gets.chomp.split(' ').map(&:to_i)

	if u != v
	if nearest[u].val > l
		nearest[u].dest = v
		nearest[u].val = l
	end

	if nearest[v].val > l
		nearest[v].dest = u
		nearest[v].val = l
	end
	end
end

storage = Array.new(k + 1) { |i| i = false }

if k > 0
	inputStorage = gets.chomp.split(' ').map(&:to_i)

	inputStorage.each do |i|
		storage[i] = true
	end
end

ans = 100000000

1.upto(n) do |city|
	#puts "city = #{city}"

	next if !storage[city]
	next if nearest[city].dest < 0

	if !storage[nearest[city].dest]
		ans = nearest[city].val if ans > nearest[city].val
		found = true
	end

	#puts "ans = #{ans}"
end

if !found
	puts -1
else
	puts ans
end

class Node
	attr_accessor :dest, :val

	def initialize dest, val
		@dest = dest
		@val = val
	end
end

n, m, k = gets.chomp.split(' ').map(&:to_i)
found = false
nearest = Array.new(n + 1) { |i| i = Node.new(-1, 100000000) }

m.times do
	u, v, l = gets.chomp.split(' ').map(&:to_i)

	if nearest[u].val > l
		nearest[u].dest = v
		nearest[u].val = l
	end

	if nearest[v].val > l
		nearest[v].dest = u
		nearest[v].val = l
	end
end

storage = Array.new(k + 1) { |i| i = false }

if k > 0
	inputStorage = gets.chomp.split(' ').map(&:to_i)

	inputStorage.each do |i|
		storage[i] = true
	end
end

ans = 100000000

1.upto(n) do |city|
	#puts "city = #{city}"

	next if !storage[city]
	next if nearest[city].dest < 0

	if !storage[nearest[city].dest]
		ans = nearest[city].val if ans > nearest[city].val
		found = true
	end

	#puts "ans = #{ans}"
end

if !found
	puts -1
else
	puts ans
end

class Node
	attr_accessor :dest, :val

	def initialize dest, val
		@dest = dest
		@val = val
	end
end

n, m, k = gets.chomp.split(' ').map(&:to_i)
found = false
nearest = Array.new(n + 1) { |i| i = Node.new(-1, 100000000) }

m.times do
	u, v, l = gets.chomp.split(' ').map(&:to_i)

	if nearest[u].val > l
		nearest[u].dest = v
		nearest[u].val = l
	end

	if nearest[v].val > l
		nearest[v].dest = u
		nearest[v].val = l
	end
end

storage = Array.new(k + 1) { |i| i = false }

if k > 0
	inputStorage = gets.chomp.split(' ').map(&:to_i)

	inputStorage.each do |i|
		storage[i] = true
	end
end

ans = 0

1.upto(n) do |city|
	next if !storage[city]

	if !storage[nearest[city].dest]
		ans = nearest[city].val
		found = true
	end
end

if !found
	puts -1
else
	puts ans
end

 class Node
	attr_accessor :dest, :val

	def initialize dest, val
		@dest = dest
		@val = val
	end

	def to_s
		print "Dest : #{dest}, Val : #{val}"
	end
end

n, m, k = gets.chomp.split(' ').map(&:to_i)
found = false
nearest = Array.new(n + 1) { |i| i = {} }

m.times do
	u, v, l = gets.chomp.split(' ').map(&:to_i)

	if u != v
		if nearest[u].has_key? v
			if nearest[u][v] > l
				nearest[u][v] = l
			end
		else
			nearest[u][v] = l
		end

		if nearest[v].has_key? u
			if nearest[v][u] > l
				nearest[v][u] = l
			end
		else
			nearest[v][u] = l
		end
	end
end

storage = Array.new(n + 1) { |i| i = false }

if k > 0
	inputStorage = gets.chomp.split(' ').map(&:to_i)

	inputStorage.each do |i|
		storage[i] = true
	end
end

ans = 100000000

1.upto(n) do |city|
	next if !storage[city]

	nearest[city].each do |dest, val|
		if !storage[dest]
			ans = val if ans > val
			found = true
		end
	end
end

if !found
	puts -1
else
	puts ans
end


Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has n clock stations, station number i is at point (xi, yi) of the plane. As the player visits station number i, he increases the current time on his timer by ai. The stations are for one-time use only, so if the player visits some station another time, the time on his timer won't grow.A player spends d·dist time units to move between stations, where dist is the distance the player has covered and d is some constant. The distance between stations i and j is determined as |xi - xj| + |yi - yj|.Initially, the player is at station number 1, and the player has strictly more than zero and strictly less than one units of time. At station number 1 one unit of money can increase the time on the timer by one time unit (you can buy only integer number of time units).Now Yaroslav is wondering, how much money he needs to get to station n. Help Yaroslav. Consider the time to buy and to increase the timer value negligibly small.

The first line contains integers n and d (3 ≤ n ≤ 100, 103 ≤ d ≤ 105) — the number of stations and the constant from the statement. The second line contains n - 2 integers: a2, a3, ..., an - 1 (1 ≤ ai ≤ 103). The next n lines contain the coordinates of the stations. The i-th of them contains two integers xi, yi (-100 ≤ xi, yi ≤ 100). It is guaranteed that no two stations are located at the same point.

In a single line print an integer — the answer to the problem.

#@n, @d = 100, 1000
#@as = (0..100).to_a.map do rand(1000) end
#@ps = (0..100).to_a.map do [rand(200)-100, rand(200)-100, nil] end

@n, @d = gets.strip.split(' ').map {|x| x.to_i}
@as = gets.strip.split(' ').map {|x| x.to_i}
@ps = (0...@n).to_a.map do
  (gets.strip.split(' ').map {|x| x.to_i}) << nil
end

def dist(n1, n2)
  ((@ps[n1][0] - @ps[n2][0]).abs + (@ps[n1][1] - @ps[n2][1]).abs)*@d
end

@sum = @as.inject(0, :+)
@base = -dist(0, @n - 1)

@c = {}
@b = nil

def it(stn, currt, mint, mask, sum, d = 0)
  d += 1
  return if mint < @base
  if @b.nil? || @b < @base
    @b = @base
  end

  if stn == @n - 1
    @b = mint if @b.nil? || mint > @b
    return
  end
  return if @b && mint <= @b

  mask = mask.clone
  mask[stn] = '1'
  k = mask + stn.to_s
  v = @c[k]
  return if v && v >= mint
  @ps[stn][2] = mint
  currt += @as[stn - 1] if stn > 0

  e = currt - dist(stn, @n-1)
  x = [mint, e].min
  @base = x if @base < x

  @ps.each_with_index do |ps, i|
    at = currt - dist(i, stn)
    nmint = [mint, at].min
    next if ps[2] && ps[2] >= nmint
    it(i, at, nmint, mask, sum + @as[stn - 1], d)
    return if @b && mint <= @b
    return if mint < @base
  end

  v = @c[k]
  @c[k] = mint if v.nil? || v < mint

  #@ps[stn][2] = false
  #p [@base, @b]
end

it(0, 0, 0, '0'*@n, 0)
puts -@b

@n, @d = gets.strip.split(' ').map {|x| x.to_i}
@as = gets.strip.split(' ').map {|x| x.to_i}
@ps = (0...@n).to_a.map do
  (gets.strip.split(' ').map {|x| x.to_i}) << false
end

@b = nil
def it(stn, currt, mint)
  #p [stn, currt, mint]
  return if @b && currt < @b
  if stn == @n - 1
    @b = mint if @b.nil? || mint > @b
    return
  end

  @ps[stn][2] = true
  currt += @as[stn - 1] if stn > 0

  @ps.each_with_index do |ps, i|
    next if ps[2]
    at = currt - dist(i, stn)
    it(i, at, [mint, at].min )
    return if @b && currt < @b
  end

  @ps[stn][2] = false

end

def dist(n1, n2)
  (@ps[n1][0] - @ps[n2][0]).abs + (@ps[n1][1] - @ps[n2][1]).abs*@d
end

it(0, 0, 0)
puts -@b

@n, @d = 100, 1000
@as = (0..100).to_a.map do rand(1000) end
@ps = (0..100).to_a.map do [rand(200)-100, rand(200)-100] end

#@n, @d = gets.strip.split(' ').map {|x| x.to_i}
#@as = gets.strip.split(' ').map {|x| x.to_i}
#@ps = (0...@n).to_a.map do
#  (gets.strip.split(' ').map {|x| x.to_i}) << false
#end

def dist(n1, n2)
  ((@ps[n1][0] - @ps[n2][0]).abs + (@ps[n1][1] - @ps[n2][1]).abs)*@d
end

@sum = @as.inject(0, :+)
@base = -dist(0, @n - 1)

@c = {}
@b = nil

def it(stn, currt, mint, mask, sum)
  return if currt < @base
  x = currt - dist(stn, @n-1)
  @base = x if @base < x

  if stn == @n - 1
    @b = mint if @b.nil? || mint > @b
    return
  end
  if @b
    return if currt <= @b
    return if( (currt - dist(stn, @n - 1) + @sum - sum) <= @b )
  end

  mask = mask.clone
  mask[stn] = '1'
  k = mask + stn.to_s
  v = @c[k]
  return if v && v >= currt
  @ps[stn][2] = true
  currt += @as[stn - 1] if stn > 0

  @ps.each_with_index do |ps, i|
    next if ps[2]
    at = currt - dist(i, stn)
    it(i, at, [mint, at].min, mask, sum + @as[stn - 1])
    return if @b && currt <= @b
  end

  v = @c[k]
  @c[k] = currt if v.nil? || v < currt

  @ps[stn][2] = false
  #p [@base, @b]
end

it(0, 0, 0, '0'*@n, 0)
puts -@b


Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least $$$a$$$ minutes to feel refreshed.Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in $$$b$$$ minutes.Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than $$$a$$$ minutes in total, then he sets his alarm to go off in $$$c$$$ minutes after it is reset and spends $$$d$$$ minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another $$$c$$$ minutes and tries to fall asleep for $$$d$$$ minutes again.You just want to find out when will Polycarp get out of his bed or report that it will never happen.Please check out the notes for some explanations of the example.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The only line of each testcase contains four integers $$$a, b, c, d$$$ ($$$1 \le a, b, c, d \le 10^9$$$) — the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep.

For each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed.

NoteIn the first testcase Polycarp wakes up after $$$3$$$ minutes. He only rested for $$$3$$$ minutes out of $$$10$$$ minutes he needed. So after that he sets his alarm to go off in $$$6$$$ minutes and spends $$$4$$$ minutes falling asleep. Thus, he rests for $$$2$$$ more minutes, totaling in $$$3+2=5$$$ minutes of sleep. Then he repeats the procedure three more times and ends up with $$$11$$$ minutes of sleep. Finally, he gets out of his bed. He spent $$$3$$$ minutes before the first alarm and then reset his alarm four times. The answer is $$$3+4 \cdot 6 = 27$$$.The second example is almost like the first one but Polycarp needs $$$11$$$ minutes of sleep instead of $$$10$$$. However, that changes nothing because he gets $$$11$$$ minutes with these alarm parameters anyway.In the third testcase Polycarp wakes up rested enough after the first alarm. Thus, the answer is $$$b=9$$$.In the fourth testcase Polycarp wakes up after $$$5$$$ minutes. Unfortunately, he keeps resetting his alarm infinitely being unable to rest for even a single minute :(

t=gets.to_i
for i in 1..t
    a,b,c,d = gets.split(" ").map(&:to_i)
    sum=0
    if(a<=b)
        print(b,"\n")
    elsif(d>=c)
        print(-1,"\n")
    else
        sum += b
        a -= b
        tt = (a.to_f/(c-d)).ceil()
        sum += tt*c
        print(sum,"\n")
    end
end

t=gets.to_i
for i in 1..t
    a,b,c,d = gets.split(" ").map(&:to_i)
    sum=0
    if(a<=b)
        print(b,"\n")
    elsif(d>=c)
        print(-1,"\n")
    else
        sum += b
        a -= b
        sum += ((a+c-d-1)/(c-d)*c).floor()
        print(sum,"\n")
    end
end


A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.

The first input line contains two integers n and k (1 ≤ n ≤ 5·105; 2 ≤ k ≤ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.

Print a single integer — the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.

n, m = gets.chomp.split(' ').map{|x| x.to_i}
str = gets.chomp
if m == 2## time complexity = n
  a = "AB" * (n/2.to_i)
  b = "BA" * (n/2.to_i)
  if n%2 == 1
    a += 'A'
    b += 'B'
  end
  p1 = 0
  p2 = 0
  (0..str.length-1).each do |i|
    if a[i] != str[i]
      p1 += 1
    end
    if b[i] != str[i]
      p2 += 1
    end
  end
  if p1 <= p2
    puts p1, a
  else
    puts p2, b
  end
else #time complexity = 26*n
  pa = 0
  res = str.split('')

  for i in (1 .. res.length-1)
    if res[i] == res[i-1]
      s1 = res[i-1]
      s2 = res[i+1]

      if s1 != 'A' and s2 != 'A'
        res[i] = 'A'
      elsif s1 != 'B' and s2 != 'B'
        res[i] = 'B'
      else
        res[i] = 'C'
      end
      pa += 1
    end
  end
  puts pa, res.join('')
end

n, m = gets.chomp.split(' ').map{|x| x.to_i}
str = gets.chomp
res = str.chars
if m == 2## time complexity = n
  a = "AB" * (n/2.to_i)
  b = "BA" * (n/2.to_i)
  if n%2 == 1
    a += 'A'
    b += 'B'
  end
  p1 = 0
  p2 = 0
  (0..res.length-1).each do |i|
    if a[i] != res[i]
      p1 += 1
    end
    if b[i] != res[i]
      p2 += 1
    end
  end
  if p1 <= p2
    puts p1, a
  else
    puts p2, b
  end
else #time complexity = 26*n
  pa = 0

  for i in (1 .. res.length-1)
    if res[i] == res[i-1]
      s1 = res[i-1]
      s2 = res[i+1]

      if s1 != 'A' and s2 != 'A'
        res[i] = 'A'
      elsif s1 != 'B' and s2 != 'B'
        res[i] = 'B'
      else
        res[i] = 'C'
      end
      pa += 1
    end
  end
  puts pa, res.join('')
end


A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them.The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs pj rubles.In total, the boys' shared budget is a rubles. Besides, each of them has his own personal money, the i-th boy has bi personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike.Each boy can rent at most one bike, one cannot give his bike to somebody else.What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?

The first line of the input contains three integers n, m and a (1 ≤ n, m ≤ 105; 0 ≤ a ≤ 109). The second line contains the sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104), where bi is the amount of the i-th boy's personal money. The third line contains the sequence of integers p1, p2, ..., pm (1 ≤ pj ≤ 109), where pj is the price for renting the j-th bike.

Print two integers r and s, where r is the maximum number of schoolboys that can rent a bike and s is the minimum total personal money needed to rent r bikes. If the schoolchildren cannot rent any bikes, then r = s = 0.

NoteIn the first sample both schoolchildren can rent a bike. For instance, they can split the shared budget in half (5 rubles each). In this case one of them will have to pay 1 ruble from the personal money and the other one will have to pay 2 rubles from the personal money. In total, they spend 3 rubles of their personal money. This way of distribution of money minimizes the amount of spent personal money.

def can_buy(shared, bikes, boys)
    #puts "Shared: #{shared} - #{bikes.to_s} - #{boys.to_s}"

    s = 0

    richest_boy = boys.size - 1

    bikes.reverse_each do |price|
        can_pay = boys[richest_boy]
        richest_boy -= 1

        if can_pay >= price
            s += price
        else
            need = price - can_pay
            if shared >= need
                shared -= need
                s += can_pay
            else
                return -1
            end
        end
    end

    return [s - shared, 0].max
end

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

nboy = s[0]
nbike = s[1]
shared_money = s[2]

n = [nboy, nbike].min
rich_boys = gets.split.map(&:to_i).sort { |x, y| y <=> x }.first(n).sort
cheap_bikes = gets.split.map(&:to_i).sort.first(n)

#puts can_buy(shared_money, cheap_bikes.first(3), rich_boys)

low = 1
high = n

r = 0
s = 0

while low <= high
    mid = (low + high) / 2
    bikes = cheap_bikes.first(mid)
    x = can_buy(shared_money, bikes, rich_boys)

    if x == -1
        high = mid - 1
    else
        r = mid
        s = x
        low = mid + 1
    end
end

puts "#{r} #{s}"


Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present — the clock that shows not only the time, but also the date.The clock's face can display any number from 1 to d. It is guaranteed that ai ≤ d for all i from 1 to n. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number d + 1, so after day number d it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day d is also followed by day 1.Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the n-th month inclusive, considering that on the first day of the first month the clock display showed day 1.

The first line contains the single number d — the maximum number of the day that Vasya's clock can show (1 ≤ d ≤ 106). The second line contains a single integer n — the number of months in the year (1 ≤ n ≤ 2000). The third line contains n space-separated integers: ai (1 ≤ ai ≤ d) — the number of days in each month in the order in which they follow, starting from the first one.

Print a single number — the number of times Vasya manually increased the day number by one throughout the last year.

NoteIn the first sample the situation is like this:   Day 1. Month 1. The clock shows 1. Vasya changes nothing.  Day 2. Month 1. The clock shows 2. Vasya changes nothing.  Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1.  Day 2. Month 2. The clock shows 2. Vasya changes nothing.  In total, Vasya manually changed the day number by 1 exactly 2 times.

n = gets.chomp.to_i
m = gets.chomp.to_i
a = gets.chomp.split(/ /).map!{|x| x.to_i}
ret = 0
for i in 0..m-2
    ret += (n - a[i])
end
puts ret

d = gets.to_i
gets
p gets.split.map{|_| d - _.to_i}[0..-2].inject(&:+) || 0

d = gets.chomp.to_i
n = gets.chomp.to_i
days = gets.chomp.split(" ").map{|e| e.to_i}

ans = 0

for i in (0..(n - 2)) do
  ans += d - days[i]
end

puts ans

d = gets.to_i
n = gets.to_i
puts gets.split.map(&:to_i)[0..-2].inject(0) {|acc, x|  acc + d - x }

d = gets.to_i
gets
a = gets.split.map(&:to_i)
c = 0
a.pop

a.each do |i|
  c += d - i
end
p c

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

(n-1).times do |i|
  ans += d - a[i]
end
puts ans

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

s = 0
0.upto(a.size-2) do |i|
  s += (d-a[i])
end
puts s

d = gets.to_i
n = gets.to_i
arr = gets.split(" ").map(&:to_i)
ans = arr[0..-2].map{|a| d - a}
puts ans.inject(0,:+)
#

def main
    d = STDIN.gets.to_i
    n = STDIN.gets.to_i
    a = STDIN.gets.split
    s = 0
    (n - 1).times do |i|
        s += d - a[i].to_i
    end
    puts s
end

main

# ProblemB

d = gets.to_i
n = gets.to_i
ary = gets.split().map {|s| s.to_i}

ret = 0

i = 0
while i < (ary.size - 1)
  ret += (d - ary[i])
  i += 1
end

puts ret

n = gets.chomp.to_i
mes = gets.chomp.to_i
dni = gets.chomp.split(" ")

length = dni.length

for i in(0..length-1)
    dni[i] = dni[i].to_i
end

k = 0
p = 0

for i in(0..length-2)

    k = n - dni[i]
    p+=k
end

puts p

d = gets.to_i
n = gets.to_i
puts gets.split.map(&:to_i)[1..-1].inject(0) {|acc, x|  acc + d - x }

d = gets.to_i
n = gets.to_i
puts gets.split.map(&:to_i)[0..-1].inject(0) {|acc, x|  acc + d - x }


Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.

The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000). The following line contains a binary string of length n representing Kevin's results on the USAICO.

Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.

NoteIn the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.In the second sample, Kevin can flip the entire string and still have the same score.

n = gets.chomp.to_i
str = gets.chomp

cnt2 = 0
cnt3 = 0
ls = [1]
for i in 1...n
  if str[i - 1] == str[i]
    ls[-1] += 1
    cnt2 += 1 if ls[-1] == 2
    cnt3 += 1 if ls[-1] == 3
  else
    ls << 1
  end
end

ans = ls.size
if 2 <= cnt2 || 1 <= cnt3
  ans += 2
elsif 1 <= cnt2
  ans += 1
end

puts ans

n = gets.chomp.to_i
tab = gets.chomp
s = 1
t = tab[0]
e = 0
for i in 1...tab.length
	if t != tab[i]
		s += 1
		t = tab[i]
	end
	if (tab[i] == tab[i-1] and tab[i]== '0') or (tab[i] == tab[i-1] and tab[i] == '1')
		e += 1
		e = [e, 2].min
	end
end
puts s+e

#!/usr/bin/ruby

len = gets.to_i
score = gets.strip()
char = '-'
alter = 0
for ch in 0..len - 1
    if char == '-' or char != score[ch]
        char = score[ch]
        alter += 1
    end
end
puts [alter + 2, len].min

=begin
min(len, maxi + 2)
=end

len = gets.to_i
s = gets
cnt = 1
1.upto(len - 1){|i|
  cnt += 1 if s[i] != s[i - 1]
}
puts [len.to_i, cnt + 2].min

n = $stdin.readline.to_i
ans = $stdin.readline.strip

subseqs = []
from = 0
ans.each_char.each_cons(2).with_index{|(fst,snd),ind|
  if fst == snd
    subseqs << [from, ind]
    from = ind + 1
  end
}
subseqs << [from, ans.size - 1]

# if subseqs.size >= 3
#   puts subseqs.each_cons(3).map{|a,b,c|
#     c.last - a.first + 1
#   }.max
# else
#   puts ans.size
# end

puts subseqs.map{|subseq| subseq[1] - subseq[0] + 1 - 1 }.inject(&:+) + 1 + (subseqs.length > 2 ? 2 : (subseqs.length > 1 ? 1 : 0))

gets
s = gets.chomp
n = s.chars.inject([0, nil]) do |(things, last), ch|
  if ch == last
    [things, ch]
  else
    [things + 1, ch]
  end
end.first

if s.scan(/(.)\1/).size > 1 || /(.)\1\1/ =~ s
  puts n + 2
elsif /(.)\1/ =~ s
  puts n + 1
else
  puts n
end

n = gets.to_i
s = gets
c = 0
for i in 0...n-1 do
   c += 1 if s[i] == s[i+1]
end
c-=2
ans = c > 0 ? c : 0
puts n-ans

#!/usr/bin/ruby

len = gets.to_i
score = gets.strip()
new = ""
alter = ""
for ch in 0..len - 1
    if new == "" or score[ch] != new[-1] or (new.length >= 2 and new[-2] != new[-1])
        new += score[ch]
    end
    if alter == "" or alter[-1] != score[ch]
        alter += score[ch]
    end
end
puts [alter.length + 2, new.length].min

=begin
min(len, maxi + 2)
=end

len = gets.to_i
s = gets
cnt = 0
1.upto(len - 1){|i|
  cnt += 1 if s[i] != s[i - 1]
}
puts [len.to_i, cnt + 2].min

gets
s = gets.chomp
n = s.chars.inject([0, nil]) do |(things, last), ch|
  if ch == last
    [things, ch]
  else
    [things + 1, ch]
  end
end.first

if s.scan(/(.)\1/).size > 1
  puts n + 2
elsif s[/^(.)\1/] || s[/(.)\1$/]
  puts n + 1
else
  puts n
end

gets
s = gets.chomp
n = s.chars.inject([0, nil]) do |(things, last), ch|
  if ch == last
    [things, ch]
  else
    [things + 1, ch]
  end
end.first

if s.scan(/(.)\1/).size > 1
  puts n + 2
elsif /(.)\1/ =~ s
  puts n + 1
else
  puts n
end

gets
s = gets.chomp
n = s.chars.inject([0, nil]) do |(things, last), ch|
  if ch == last
    [things, ch]
  else
    [things + 1, ch]
  end
end.first

if s.scan(/(.)\1/).size > 1
  puts n + 2
else
  puts n
end

n = gets.to_i
s = gets
c = 0
for i in 0...n-1 do
   c += 1 if s[i] == s[i+1]
end
c-=2
ans = c > 0 ? c : 0
puts ans


Основой любой социальной сети является отношение дружбы между двумя пользователями в том или ином смысле. В одной известной социальной сети дружба симметрична, то есть если a является другом b, то b также является другом a. В этой же сети есть функция, которая демонстрирует множество людей, имеющих высокую вероятность быть знакомыми для пользователя. Эта функция работает следующим образом. Зафиксируем пользователя x. Пусть некоторый другой человек y, не являющийся другом x на текущий момент, является другом не менее, чем для k% друзей x. Тогда он является предполагаемым другом для x.У каждого человека в социальной сети есть свой уникальный идентификатор — это целое число от 1 до 109. Вам дан список пар пользователей, являющихся друзьями. Определите для каждого упомянутого пользователя множество его предполагаемых друзей.

В первой строке следуют два целых числа m и k (1 ≤ m ≤ 100, 0 ≤ k ≤ 100) — количество пар друзей и необходимый процент общих друзей для того, чтобы считаться предполагаемым другом. В последующих m строках записано по два числа ai, bi (1 ≤ ai, bi ≤ 109, ai ≠ bi), обозначающих идентификаторы пользователей, являющихся друзьями.  Гарантируется, что каждая пара людей фигурирует в списке не более одного раза.

Для всех упомянутых людей в порядке возрастания id выведите информацию о предполагаемых друзьях. Информация должна иметь вид "id:  k id1 id2 ... idk", где id — это id самого человека, k — количество его предполагаемых друзей, а id1, id2, ..., idk — идентификаторы его предполагаемых друзей в возрастающем порядке.

pairs, percent = gets.strip.split(" ").map(&:to_i)
percent = percent.to_f / 100.0

users = Hash.new

pairs.times do |i|
    u1, u2 = gets.strip.split(" ").map(&:to_i)
    users[u1] = Array.new unless users[u1].kind_of?(Array)
    users[u2] = Array.new unless users[u2].kind_of?(Array)

    users[u1] << u2
    users[u2] << u1
end

users = Hash[users.sort]

users.map do |i, arr1|
    print "#{i}: "
    cmn_tr = []
    users.map do |j, arr2|
        next if i == j
        cmn = arr1 & arr2
        if cmn.length.to_f / users[i].length.to_f >= percent
            cmn_tr << j unless arr1.include? j
        end
    end
    print "#{cmn_tr.length} "
    cmn_tr.map{|k| print "#{k} "}
    print "\n"
end

pairs, percent = gets.strip.split(" ").map(&:to_i)
percent = percent.to_f / 100.0

users = Hash.new

pairs.times do |i|
    u1, u2 = gets.strip.split(" ").map(&:to_i)
    users[u1] = Array.new unless users[u1].kind_of?(Array)
    users[u2] = Array.new unless users[u2].kind_of?(Array)

    users[u1] << u2
    users[u2] << u1
end

users.each do |i, arr1|
    print "#{i}: "
    cmn_tr = []
    users.each do |j, arr2|
        next if i == j
        cmn = arr1 & arr2
        if cmn.length.to_f / users[i].length.to_f >= percent
            cmn_tr << j
        end
    end
    print "#{cmn_tr.length} "
    cmn_tr.map{|k| print "#{k} "}
    print "\n"
end

pairs, percent = gets.strip.split(" ").map(&:to_i)
percent = percent.to_f / 100.0

users = Hash.new

pairs.times do |i|
    u1, u2 = gets.strip.split(" ").map(&:to_i)
    users[u1] = Array.new unless users[u1].kind_of?(Array)
    users[u2] = Array.new unless users[u2].kind_of?(Array)

    users[u1] << u2
    users[u2] << u1
end

users = Hash[users.sort]

users.map do |i, arr1|
    print "#{i}: "
    cmn_tr = []
    users.map do |j, arr2|
        next if i == j
        cmn = arr1 & arr2
        if cmn.length.to_f / users[i].length.to_f >= percent
            cmn_tr << j
        end
    end
    print "#{cmn_tr.length} "
    cmn_tr.map{|k| print "#{k} "}
    print "\n"
end


Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.Now Petya wants to know for each friend i the number of a friend who has given him a gift.

The first line contains one integer n (1 ≤ n ≤ 100) — the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi — the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.

Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.

n = gets.to_i
a = gets.split(' ').map(&:to_i)
res = Array.new
n.times do |i|
  res[a[i]-1] = i+1
end
res.each { |v| print "#{v} " }

n = gets.to_i
a = gets.split(' ').map(&:to_i)
res = Array.new
n.times do |i|
  res[a[i]-1] = i+1
end
puts res.to_s.gsub(/\[/, '').gsub(/\]/, '').gsub(/,/, '')

n = gets.to_i
ar = gets.chomp.split(' ',n).map{|_|_.to_i}
puts ar.map.with_index(1).sort_by(&:first).map(&:last).map(&:to_s).join(' ')

class Main
  #def get_problem_link
  #  problem_link = "https://codeforces.com/contest/136/problem/A"
  #  return problem_link
  #end

  #def get_submission_link
  #  submission_link = ''
  #  return submisson_link
  #end

  #begin
  #of codeforces interface
  def run_interface
    n = gets.to_i
    k = gets.split(' ').map(&:to_i)
    puts solution(n, k)
  end
  #end
  #of codeforces interface

  def solution(n, presents_array)
      res_array = []
      for i in 1..n do
        res_array.push(presents_array.index(i) + 1)
      end
      return res_array.join(' ')
  end

end

#then upload to codeforces uncomment this line:
Main.new.run_interface

n = STDIN.gets.chomp.to_i
p = STDIN.gets.chomp.split(' ').map{|i| i.to_i}

res = p.inject(Hash.new(-1)) {|h, i| h[i - 1] = p.index(i); h}
n.times do |i|
    if res[i] == -1
        print i + 1, " "
        next
    end
    print res[i] + 1, " "
end

n = gets.to_i

h = {}
st = gets.split.map{|i| i.to_i}

n.times do |i|
    h[i+1] = st[i]
end

h = h.invert

st = ""
i = 1
while i <= n do
    st += h[i].to_s + " "
    i += 1
end

puts st

gets;a=gets.split.map &:to_i
puts (1..a.size).map{|i|a.index(i)+1}*" "

n=gets.to_i
a=Array.new(n,0)
i=gets.split.map(&:to_i)
n.times{|j|
        a[i[j]-1]=j
}
a.each{|j|
        print "#{j+1} "
}
puts

n = gets.to_i
p = gets.split.map(&:to_i)
a = Array(p.size)
p.each_index {|i| a[p[i] - 1] = i + 1 }
puts a

n = gets.to_i
a = []
a = gets.split.map &:to_i
b = Array.new(n)

(0...n).each do |i|
    b[a[i] - 1] = i + 1;
end

print  b.join(' ')

l = STDIN.read.split("\n")
a = []
l[1].split(' ').each_with_index{|x,i| a << [x.to_i, i+1] }
b = a.sort_by{|x| x[0] }.map{|x| x[1] }
puts b.join(' ')

def r
  myArray = gets.chomp.split().map { |e| e.to_i  }
end
n = r
array = r
array_2 = Array.new(n)
array.each_with_index{|val, index|
  array_2[val-1] = index + 1
}
array_2.each {|e| print "#{e} " }

n = gets.chomp;
n = n.to_i;

p = gets.chomp;
p = p.split(' ');

for i in 0..p.length-1
	p[i] = p[i].to_i;
#puts p[i];
end

#puts("done");

from = Array.new(n + 1);

for i in 0..p.length-1
	from[p[i]] = i + 1
end

for i in 1..from.length-1
	if i > 1
		printf(" ");
	end
	printf("%d", from[i]);
end
printf("\n");

n=gets.chomp.strip.to_i
a=gets.chomp.split(' ').map(&:to_i)
p=[]
a.each_index do |i|
	p[a[i]-1]=i
end
for x in p do
	print (x+1).to_s+' '
end
puts

#!/usr/bin/ruby

friends = gets.to_i
gifts = gets.chomp.split(" ").map(&:to_i)
(1..friends+1).each do |num|
   (0..friends).each do |i|
    if(gifts[i] == num)
      puts i + 1
    end
  end
end

a = Array.new(gets.to_i)
gets.strip.split.map(&:to_i).to_a.each_with_index { |e, i| a[e-1] = i+1 }
puts a*' '

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

b = []

a.each_with_index do |t,i|
 b[t-1] = i+1
end

puts b.join(' ')

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

for i in 0..n-1
 c[a[i]] = i+1
end
puts c.compact

n = $stdin.readline.to_i
f = $stdin.readline.split.map(&:to_i)

f_inv = Array.new(n)
f.each_with_index {|e,i| f_inv[e-1]=i+1 }

puts f_inv.join(" ")

#!/usr/bin/ruby
def readNextValues
  return gets.chomp.split.collect {|x| x.to_i }
end

n = readNextValues
arr = readNextValues
result = []
for i in 1..arr.size
  result << arr.find_index(i) + 1
end
puts result.join(' ')

gets
arr = gets.split.map &:to_i
sol = Array.new
arr.each_with_index { |x, index| sol[arr[index]] = index + 1 }
sol.shift
puts sol

n = gets.to_i
ps = gets.split.map(&:to_i)
ans = Array.new(n)
ps.each_with_index do |p, i|
  ans[p-1] = i + 1
end
puts ans.join(" ")

friends = gets.chomp.to_i
gifts = gets.chomp.split(/ /).map(&:to_i)
received_gifts = {}
(1..friends).each do |friend|
    received_gifts.store gifts[friend - 1], friend
end
ans = []
(1..friends).each do |friend|
    ans << received_gifts[friend]
end
puts ans.join(" ")

a=gets.chomp.to_i
b=gets.chomp.split(" ")
ans=""
1.upto(a) do |i|
    c=b.index("#{i}")+1
    ans=ans+"#{c} "
end
puts "#{ans}"

n=gets.to_i
b=(1..n).map{0}
x=gets.split.map{|e| e.to_i}
n.times{|i|
	j=i+1
	b[x[i]-1]=j
}
puts b*" "

n = gets.to_i
arr_n = gets.split.map(&:to_i)
res = []
arr_n.each.with_index(1) { |e,i| res[e]=i }
puts res[1..-1].join(' ')

n = gets.to_i
a = gets.split.map(&:to_i)
b = []
n.times do |i|
  b << a.index(i+1)+1
end
puts b * " "

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

c = {}
arr.each_with_index do |a,i|
  c[i+1] = a
end

cc = {}
c.each do |k,v|
  cc[v] = k
end

aa = []
n.times do |i|
  aa << cc[i+1]
end

puts aa.join(' ')

#=================================
require 'prime'
require 'set'
require 'matrix'
require 'tsort'
include Math

if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

n=gets.to_i
data=gets.split.map(&:to_i)
ans=Array.new(n, 0)

n.times{|i|
	ans[data[i]-1]=i+1
}

ans.each{|v| print "#{v} "}

number = gets.to_i
answer = Array.new(number + 1)

arr = gets.chomp.split(' ').map(&:to_i)
i = 1
arr.each do |x|
  answer[x] = i
  i += 1
end

answer.each { |x| print "#{x} " }

len=gets.to_i
b=[]
a=gets.split.map{|i|i.to_i}
len.times{|i| b[a[i]]=i+1}
b.shift
print b[0]
1.upto(len) {|i| print ' ',b[i]}
puts

len=gets.to_i
b=[]
a=gets.split.map{|i|i.to_i}
len.times{|i| b[a[i]]=i+1}
b.shift
len.times {|i| print b[i],' '}

n = gets.to_i
q = gets.chomp.split.map { |x| x.to_i }
h = Hash.new

for i in 0..n-1
  h[i] = q[i]
end

h = h.invert

for i in 1..n
  print h[i]+1, ' '
end

i = gets.to_i
array = gets.chomp.split.map(&:to_i)
a = Array.new

array.map.with_index { |x, i| a[x-1] = i+1 }
puts a.join(" ")

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

b = Array.new(a.size)

a.each_index { |i| b[a[i]] = i + 1}

puts b

t=[];$<.take(2)[1].split.each_with_index{|k,i| t[k.to_i]=i+1};puts t[1..-1].join " "

number_of_friends = gets.strip.to_i
friends = gets.strip.split(' ')

results = []
1.upto(number_of_friends) do |current_friend|
  results << friends.index { |given_friend| current_friend.to_s == given_friend } + 1
end

puts results.join(' ')

n = $stdin.readline.to_i
a = $stdin.readline.split(' ').map { |x| x.to_i }

b = Array.new(n)
for i in 1..n
  b[i-1] = i
end

for i in 1..n
  b[a[i-1]-1] = i unless a[i-1].nil?
end

puts b.join(' ')

n=gets.to_i
a=gets.split.map(&:to_i)
(1..n).each{|i|puts a.index(i)+1}

friends = gets.chomp.to_i
gifts = gets.chomp
gifts = gifts.split

arr_gifts = []
for i in (0..gifts.size-1)
	arr_gifts[gifts[i].to_i-1] = i+1
end

for i in (0..gifts.size-1)
	print arr_gifts[i].to_i
	print " "
end

n=gets.to_i
s=gets.split(' ').map{|x|x.to_i-1}
n.times{|i|print s.index(i)+1,' '}

r={}
i=1
n=gets.to_i
gets.split(' ').each{|x|r[x.to_i]=i.to_s;i=i+1}
n.times{|i|print r[i+1]+' '}

n=gets.to_i
r=[0]*n
i=1
gets.split(' ').each{|x|r[x.to_i-1]=i;i=i+1}
print r.join(' ')

n=gets.to_i
s=gets
n.times{|i|p s.split(' ').index((i+1).to_s)+1}

n = gets
p = gets
=begin
arr1 = p.chomp.split(' ')
arr1 = arr1.sort
max = arr1[-2]
if max == 1
  puts  arr1.sort[0..-2].join(' ')+" 2"
else
  puts "1 " + arr1.sort[0..-2].join(' ')
end
=end

from = Array.new(n.to_i)
to = p.split(' ')
i = 1
for el in to
  from[el.to_i-1] = i
  i+=1
end
puts from.join(' ').chomp

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
h = {}
arr.each_with_index { |a,i|
  h[a] = i + 1
}
for i in (1..n)
  puts h[i]
end

n = gets.to_i
a = gets.split.map &:to_i
c = {}
for i in (1..n)
  c[i] = a[i-1]
end
puts c.sort_by {|k, v| v}.map{|x| x[0]}.join(" ")

n = gets.to_i
ar = Array.new
ar = gets.split.map &:to_i
a = ar.size
a.times{
  |i| puts ar.index(i+1)+1 # array.index(value) returns the index of value in the array
 }

l = []
gets
gets.split.map(&:to_i).each_with_index { |x, i| l[x - 1] = i + 1 }
puts l.join(" ")

member_num = gets.chomp.to_i
present_arr = gets.chomp.split
present_arr.map!{|i| i.to_i}
output_arr = Array.new(member_num)
i = 0
while i < output_arr.length
  output_arr[present_arr[i]-1] = i+1
  i = i+1
end
print output_arr.join(" ")

n=gets.to_i
a=[]
(n-1).times{
a.push gets(' ').to_i
}
a.push gets.to_i

b=[]

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

for i in b
print i
print ' '
end
print "\n"

n = gets.to_i
input = gets.split(' ').map(&:to_i).unshift(0)
result = Array.new(n+1, 0)

0.upto(n) do |i|
  result[input[i]] = i
end

result.shift

puts result.join(' ')

n = gets.to_i
m = gets.chomp.split(" ")

p = Array.new(n)

for i in(0..n-1)
    p[m[i].to_i - 1] = i + 1
end

p.each{ |x|
    print(x, " ")
}

n = gets.to_i
b = gets.split(' ').map{|s| s.to_i}
a = Array.new(n)
i = 0
while (i < n)
    a[b[i]-1] = i
    i+=1
end
s = ''
a.each{|q| s += (q+1).to_s + ' '}
puts s

n = gets.to_i
a = []
gets.split.each_with_index{ |x,i|
 a[x.to_i] = i+1
}
puts a.join(" ")

gets
t = 1
rec = Array.new(t)
gets.scan(/\d+/).each do |i|
	rec[i.to_i] = t
	t = t+1
end
rec.each do |out|
	printf(out.to_s + " ")
end

#!/usr/bin/env ruby

gets
m = {}
gets.split.map(&:to_i).each_with_index { |p,i|
   m[p] = i
}
m.map.sort_by{ |i,p|i }.map { |i,p|
   print "#{p+1} "
}
puts

n = gets.to_i
res = Array.new(n, 0)
n = 1
arr = gets.split.map(&:to_i).each do |item|
  res[item - 1] = n
  n += 1
end
puts res.join(" ")

gets
gets.split(" ").each_with_index.map { |s, i| [s.to_i, i] }.sort_by! {|s, i| s}.each { |s, i| print "#{i+1} "}

n = gets.to_i
h = {}
readline.split(" ").each_with_index.map { |item, pos| h[item.to_i] = pos+1 }
(1..n).each { |i| print "#{h[i]} " }

gets
puts gets.split.map(&:to_i).each_with_index.map.sort_by{|p,i|p}.map{|p,i|i+1}*" "

gets;
arr = gets.split.map(&:to_i)
arr2 = Array(arr.size + 1)
for i in 1..arr.size do
 arr2[ arr[i-1] ] = i;
end
for i in 1...arr2.size do
 puts arr2[i]
end

friendNum = gets.chomp.to_i
input = gets.chomp.split(' ').map {|item| item.to_i}
output = []
(0...friendNum).each do |loops|
	output[(input[loops] - 1) % friendNum] = loops + 1
end
output.each do |ans|
	print "#{ans} "
end

n = gets.chomp.to_i
gets.chomp.split(' ').map(&:to_i).zip((1..n).to_a).sort { |x, y| x[0] <=> y[0]}.each {|x| puts x[1] }

n = gets.to_i
ar = gets.chomp.split(' ',n)
puts ar.map.with_index(1).sort_by(&:first).map(&:last).map(&:to_s).join(' ')

a = Array.new(gets.to_i)
puts gets.strip.split.map(&:to_i).to_a.each_with_index { |e, i| a[e-1] = i+1 } * ' '

gets
arr = gets.split.map &:to_i
sol = Array.new
arr.each_with_index { |x, index| sol[arr[index]] = index + 1 }
sol.shift
p sol

number = gets.to_i
answer = Array.new(number + 1)
i = 1

number.times {
  n = gets.to_i
  answer[n] = i
  i += 1
}

answer.each { |x| print "#{x} " }

n = gets.to_i
q = gets.chomp.split.map { |x| x.to_i }
h = Hash.new

for i in 0..n-1
  h[i] = q[i]
end

h = h.invert

p h

for i in 1..n
  print h[i]+1, ' '
end

i = gets.to_i
array = gets.chomp.split.map(&:to_i)
a = Array.new

puts array.map.with_index { |x, i| a[x-1] = i+1 }.join(" ")

t=[];gets.split.each_with_index{|k,i| t[k.to_i]=i+1};puts t[1..-1].join " "

r={}
i=1
gets
gets.split(' ').each{|x|r[x.to_i]=i;i=i+1}
print r.values.join(' ')

#!/usr/bin/env ruby

gets
m = {}
gets.split.map(&:to_i).each_with_index { |p,i|
   m[p] = i
}
m.map { |i,p|
   print "#{p+1} "
}
puts


Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day.In return, the fleas made a bigger ukulele for her: it has $$$n$$$ strings, and each string has $$$(10^{18} + 1)$$$ frets numerated from $$$0$$$ to $$$10^{18}$$$. The fleas use the array $$$s_1, s_2, \ldots, s_n$$$ to describe the ukulele's tuning, that is, the pitch of the $$$j$$$-th fret on the $$$i$$$-th string is the integer $$$s_i + j$$$.Miyako is about to leave the kingdom, but the fleas hope that Miyako will answer some last questions for them.Each question is in the form of: "How many different pitches are there, if we consider frets between $$$l$$$ and $$$r$$$ (inclusive) on all strings?"Miyako is about to visit the cricket kingdom and has no time to answer all the questions. Please help her with this task!Formally, you are given a matrix with $$$n$$$ rows and $$$(10^{18}+1)$$$ columns, where the cell in the $$$i$$$-th row and $$$j$$$-th column ($$$0 \le j \le 10^{18}$$$) contains the integer $$$s_i + j$$$. You are to answer $$$q$$$ queries, in the $$$k$$$-th query you have to answer the number of distinct integers in the matrix from the $$$l_k$$$-th to the $$$r_k$$$-th columns, inclusive.

The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — the number of strings. The second line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \leq s_i \leq 10^{18}$$$) — the tuning of the ukulele. The third line contains an integer $$$q$$$ ($$$1 \leq q \leq 100\,000$$$) — the number of questions. The $$$k$$$-th among the following $$$q$$$ lines contains two integers $$$l_k$$$，$$$r_k$$$ ($$$0 \leq l_k \leq r_k \leq 10^{18}$$$) — a question from the fleas.

Output one number for each question, separated by spaces — the number of different pitches.

def bsearch(arr,t)
  ok,ng = 0,arr.length
  while (ng - ok).abs > 1
    mid = (ok+ng)/2
    if arr[mid] <= t
      ok = mid
    else
      ng = mid
    end
  end
  return ok
end

n = gets.to_i
s = gets.split.map(&:to_i)
q = gets.to_i
qs = []
q.times do
  l,r = gets.split.map(&:to_i)
  qs << r-l+1
end

s.sort!
diff = [0]
(n-1).times do |i|
  diff << s[i+1] - s[i]
end
diff << 10**18+1
diff.sort!
cumsum = [0]
n.times do |i|
  cumsum << cumsum[-1] + diff[i+1]
end

qs.each do |t|
  fill = bsearch(diff,t)
  ans = cumsum[fill] + t*(n-fill)
#  p [t,fill,cumsum[fill]]
  print "#{ans} "
end

def binary_search(ok, ng)
  while (ok - ng).abs > 1
    mid = (ok + ng) / 2

    if yield(mid)
      ok = mid
    else
      ng = mid
    end
  end

  ok
end

N = gets.to_i
S = gets.split.map(&:to_i)
SU = S.sort.uniq
Q = gets.to_i
query = Q.times.map { gets.split.map(&:to_i) }

DL = SU.each_cons(2).map { |a, b| b - a - 1 }.sort
DL.unshift(-Float::INFINITY)
DL.push(Float::INFINITY)
DL.reverse!

RUI = []

sum = 0

DL.reverse[1..-2].each do |v|
  sum += v
  RUI << sum
end

RUI.unshift(-Float::INFINITY)
RUI << Float::INFINITY
RUI.reverse!

ans = []
query.each do |l, r|
  a = SU.size
  d = r - l
  ei = binary_search(0, DL.size - 1) { |x| DL[x] >= d }
  b = d * ei
  c = d
  d = [RUI[ei + 1], 0].max

  ans << a + b + c + d
end

puts ans.join(' ')

n = gets.to_i
s = gets.split.map(&:to_i).uniq.sort
n = s.size
t = Array.new(n-1)
for i in 0..n-2
    t[i] = s[i+1]-s[i]
end
t.sort!
q = gets.to_i
lr = Array.new(q)
q.times do |i|
    lr[i] = gets.split.map(&:to_i)
end
a = Array.new(q){|i|i}.sort_by{|i|lr[i][1]-lr[i][0]}
ans = Array.new(q,0)
lr.sort_by!{|i,j|j-i}
c = 0
sum = 0
q.times do |i|
    d = lr[i][1]-lr[i][0]+1
    while c < n-1 && t[c] < d
        sum += t[c]
        c += 1
    end
    ans[a[i]] = sum+d+(n-c-1)*d
end
puts ans.join(" ")

def binary_search(ok, ng)
  while (ok - ng).abs > 1
    mid = (ok + ng) / 2

    if yield(mid)
      ok = mid
    else
      ng = mid
    end
  end

  ok
end

N = gets.to_i
S = gets.split.map(&:to_i)
SU = S.sort.uniq
Q = gets.to_i
query = Q.times.map { gets.split.map(&:to_i) }

DL = SU.each_cons(2).map { |a, b| b - a - 1 }.sort
RUI = []

sum = 0

DL.each do |v|
  sum += v
  RUI << sum
end

RUI.unshift(-Float::INFINITY)
RUI << Float::INFINITY
RUI.reverse!

ans = []
query.each do |l, r|
  a = SU.size
  d = r - l
  ei = binary_search(0, RUI.size - 1) { |x| RUI[x] >= d }
  b = d * ei
  c = d
  d = [RUI[ei + 1], 0].max

  ans << a + b + c + d
end

puts ans.join(' ')


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You can perform the following operations with it:   Choose some positions $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n, i \ne j$$$), write the value of $$$a_i \cdot a_j$$$ into the $$$j$$$-th cell and remove the number from the $$$i$$$-th cell;  Choose some position $$$i$$$ and remove the number from the $$$i$$$-th cell (this operation can be performed no more than once and at any point of time, not necessarily in the beginning). The number of elements decreases by one after each operation. However, the indexing of positions stays the same. Deleted numbers can't be used in the later operations.Your task is to perform exactly $$$n - 1$$$ operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it you need to print any sequence of operations which leads to this maximum number. Read the output format to understand what exactly you need to print.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the elements of the array.

Print $$$n - 1$$$ lines. The $$$k$$$-th line should contain one of the two possible operations. The operation of the first type should look like this: $$$1~ i_k~ j_k$$$, where $$$1$$$ is the type of operation, $$$i_k$$$ and $$$j_k$$$ are the positions of the chosen elements. The operation of the second type should look like this: $$$2~ i_k$$$, where $$$2$$$ is the type of operation, $$$i_k$$$ is the position of the chosen element. Note that there should be no more than one such operation. If there are multiple possible sequences of operations leading to the maximum number — print any of them.

NoteLet X be the removed number in the array. Let's take a look at all the examples:The first example has, for example, the following sequence of transformations of the array: $$$[5, -2, 0, 1, -3] \to [5, -2, X, 1, -3] \to [X, -10, X, 1, -3] \to$$$ $$$[X, X, X, -10, -3] \to [X, X, X, X, 30]$$$. Thus, the maximum answer is $$$30$$$. Note, that other sequences that lead to the answer $$$30$$$ are also correct.The second example has, for example, the following sequence of transformations of the array: $$$[5, 2, 0, 4, 0] \to [5, 2, X, 4, 0] \to [5, 2, X, 4, X] \to [X, 10, X, 4, X] \to$$$ $$$[X, X, X, 40, X]$$$. The following answer is also allowed: 1 5 31 4 21 2 12 3Then the sequence of transformations of the array will look like this: $$$[5, 2, 0, 4, 0] \to [5, 2, 0, 4, X] \to [5, 8, 0, X, X] \to [40, X, 0, X, X] \to$$$ $$$[40, X, X, X, X]$$$.The third example can have the following sequence of transformations of the array: $$$[2, -1] \to [2, X]$$$.The fourth example can have the following sequence of transformations of the array: $$$[0, -10, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0]$$$.The fifth example can have the following sequence of transformations of the array: $$$[0, 0, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0]$$$.

n = gets.to_i
a = gets.split.map(&:to_i)
used = Array.new(n+1,false)
z = []
p = 0
pre = 0
mx = [-1000000010,0]
for i in 0..n-1
  if a[i] == 0
    z.push(i+1)
    next
  end
  if a[i] < 0
    p = 1-p
    if mx[0] < a[i]
      mx = [a[i],i+1]
    end
  end
end
z.push(mx[1]) if p == 1
for i in 0..z.size-2
  puts "1 #{z[i]} #{z[i+1]}"
  used[z[i]-1] = true
end
if (z.size != 0 && z.size != n)
  puts "2 #{z[-1]}"
  used[z[-1]-1] = true
end
for i in 0..n-1
  next if used[i]
  if pre != 0
    puts "1 #{pre} #{i+1}"
  end
  pre = i+1
end


You are given two segments $$$[l_1; r_1]$$$ and $$$[l_2; r_2]$$$ on the $$$x$$$-axis. It is guaranteed that $$$l_1 < r_1$$$ and $$$l_2 < r_2$$$. Segments may intersect, overlap or even coincide with each other.    The example of two segments on the $$$x$$$-axis. Your problem is to find two integers $$$a$$$ and $$$b$$$ such that $$$l_1 \le a \le r_1$$$, $$$l_2 \le b \le r_2$$$ and $$$a \ne b$$$. In other words, you have to choose two distinct integer points in such a way that the first point belongs to the segment $$$[l_1; r_1]$$$ and the second one belongs to the segment $$$[l_2; r_2]$$$.It is guaranteed that the answer exists. If there are multiple answers, you can print any of them.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Each of the next $$$q$$$ lines contains four integers $$$l_{1_i}, r_{1_i}, l_{2_i}$$$ and $$$r_{2_i}$$$ ($$$1 \le l_{1_i}, r_{1_i}, l_{2_i}, r_{2_i} \le 10^9, l_{1_i} < r_{1_i}, l_{2_i} < r_{2_i}$$$) — the ends of the segments in the $$$i$$$-th query.

Print $$$2q$$$ integers. For the $$$i$$$-th query print two integers $$$a_i$$$ and $$$b_i$$$ — such numbers that $$$l_{1_i} \le a_i \le r_{1_i}$$$, $$$l_{2_i} \le b_i \le r_{2_i}$$$ and $$$a_i \ne b_i$$$. Queries are numbered in order of the input. It is guaranteed that the answer exists. If there are multiple answers, you can print any.

gets;puts$<.map{|e|a,b,c,d=e.split.map &:to_i;[a,(c!=a ? c : d)]*' '}

q = gets.to_i
q.times do
  l1, r1, l2, r2 = gets.split.map(&:to_i)
  a = l1
  b = l2
  if b == a
    b = r2
  end
  puts "#{a} #{b}"
end

input = gets.to_i
i = 0
input_range = []
input.times do
  input_range[i] = gets.split.map(&:to_i)
  input_range[i]
  i += 1
end

i = 0

input.times do
  if input_range[i][0] != input_range[i][3]
    print "#{input_range[i][0]} "
    puts "#{input_range[i][3]}"
  else
    print "#{input_range[i][1]} "
    puts "#{input_range[i][2]}"
  end
  i += 1
end

n = gets.to_i
n.times do
  l1, r1, l2, r2 = gets.split(' ').map(&:to_i)
  if (l1 != l2)
    puts [l1, l2].join(' ')
    next
  end
  if (r1 != r2)
    puts [r1, r2].join(' ')
    next
  end
  if (r1 - l1 == 2)
    puts [l1, r1].join(' ')
    next
  end
  puts [l1 + 1, r1 - 1].join(' ')
end

a = gets

def sol(a)
	(1..a.to_i).map {|num|
		a,b,c,d = gets.chomp.split
		[a,a==c ? d : c ]
	}
end

puts sol(a)

f = gets.to_i
f.times do
  l1, r1, l2, r2 = gets.to_s.chomp.split(" ").map{|x| x.to_i}
  if r1 != r2
    puts "#{r1} #{r2}"
  else
    puts "#{r1} #{r2 - 1}"
  end
end

N = gets.to_i
N.times do
    l1, r1, l2, r2 = gets.chomp.split.map(&:to_i)
    if r1 < l2 or r2 < l1
        puts "#{l1} #{l2}"
    else
        if l1 <= l2
            puts "#{l1} #{r2}"
        else
            puts "#{r1} #{l2}"
        end
    end
end

if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

q = gets.to_i
q.times do
	lrlr = gets.chomp.split(" ").map(&:to_i)
	l1 = lrlr[0]
	r1 = lrlr[1]
	l2 = lrlr[2]
	r2 = lrlr[3]

	if (l1 == l2) and (l1==r2)
		puts "#{r1} #{l1}"
	else
		print "#{l1} "
		if(l1==l2)
			print r2
		else
			print l2
		end
		puts
	end
end

input = gets.to_i
i = 0
input_range = []
input.times do
  input_range[i] = gets.split.map(&:to_i)
  input_range[i]
  i += 1
end

i = 0

input.times do
  print "#{input_range[i][0]} "
  puts "#{input_range[i][3]}"
  i += 1
end

n = gets.to_i
n.times do
  l1, r1, l2, r2 = gets.split(' ').map(&:to_i)
  if (l1 != l2)
    puts [l1, l2].join(' ')
    next
  end
  if (r1 != r2)
    puts [r1, r2].join(' ')
    next
  end
  puts [l1 + 1, r1 - 1].join(' ')
end

a = gets

def sol(a)
	(1..a.to_i).map {|num|
		a,b,c,d = gets.chomp.split('\s')
		[a,a==c ? d : c ]
	}
end

puts sol(a)


A permutation — is a sequence of length $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all the numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ — permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ — no.Polycarp was recently gifted a permutation $$$a[1 \dots n]$$$ of length $$$n$$$. Polycarp likes trees more than permutations, so he wants to transform permutation $$$a$$$ into a rooted binary tree. He transforms an array of different integers into a tree as follows:   the maximum element of the array becomes the root of the tree;  all elements to the left of the maximum — form a left subtree (which is built according to the same rules but applied to the left part of the array), but if there are no elements to the left of the maximum, then the root has no left child;  all elements to the right of the maximum — form a right subtree (which is built according to the same rules but applied to the right side of the array), but if there are no elements to the right of the maximum, then the root has no right child. For example, if he builds a tree by permutation $$$a=[3, 5, 2, 1, 4]$$$, then the root will be the element $$$a_2=5$$$, and the left subtree will be the tree that will be built for the subarray $$$a[1 \dots 1] = [3]$$$, and the right one — for the subarray $$$a[3 \dots 5] = [2, 1, 4]$$$. As a result, the following tree will be built:     The tree corresponding to the permutation $$$a=[3, 5, 2, 1, 4]$$$. Another example: let the permutation be $$$a=[1, 3, 2, 7, 5, 6, 4]$$$. In this case, the tree looks like this:     The tree corresponding to the permutation $$$a=[1, 3, 2, 7, 5, 6, 4]$$$. Let us denote by $$$d_v$$$ the depth of the vertex $$$a_v$$$, that is, the number of edges on the path from the root to the vertex numbered $$$a_v$$$. Note that the root depth is zero. Given the permutation $$$a$$$, for each vertex, find the value of $$$d_v$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the permutation. This is followed by $$$n$$$ numbers $$$a_1, a_2, \ldots, a_n$$$ — permutation $$$a$$$.

For each test case, output $$$n$$$ values — $$$d_1, d_2, \ldots, d_n$$$.

# Entrada: testcases, longitud del arreglo, arreglo permutación
# Salida: profundidad de cada nodo en orden de la entrada del arreglo
# Formación del arbol y resultado:
# 1 Paso: encontrar el número mayor del arreglo
# 2 Paso: separar los elementos del arreglo con base del número mayor, de los elementos de
# izquierda de este, y los elementos de la derecha
# 3 Paso: en cada conjunto separado, realizar el paso 1 y 2 hasta que no se pueda dividir
# Nota: si no hay elementos, se descarta(No se toma en cuenta).
# 4 Paso: buscar el nivel de profundidad de cada nodo y relacionarlo con el arreglo inicial
# 5 Paso: Mostrar en pantalla los niveles de profundidad de cada arreglo dado

# Más ejemplos de casos
# 1 Caso (Caso cargado a la derecha): 7,5,6,3,4,2,1
# Nivel 0
# 1 Paso: 7
# 2 Paso: Izquierda--> .Derecha-->5,6,3,4,2,1
# 3 Paso: Para Izquierda: ¿Es solo un elemento? No hay elemento ---> Se descarta
# Para Derecha: ¿Es solo un elemento? No ---> volvemos a 1 Paso con entrada derecha
# Nivel 1, Derecha
# 1 Paso: 6
# 2 Paso: Izquierda--> 5 .Derecha-->3,4,2,1
# 3 Paso: Para Izquierda ¿Es solo un elemento? Si --->Termina.
# Para Derecha: ¿Es solo un elemento? No ---> volvemos a 1 Paso con entrada derecha
# Nivel 2, Derecha
# 1 Paso: 4
# 2 Paso: Izquierda-->3 .Derecha-->2,1
# 3 Paso: Para Izquierda: ¿Es solo un elemento? Si --->Termina.
# Para Derecha: ¿Es solo un elemento? No ---> volvemos a 1 Paso con entrada derecha
# Nivel 3, Derecha
# 1 Paso: 2
# 2 Paso: Izquierda--> .Derecha-->1
# 3 Paso: Para Izquierda: ¿Es solo un elemento? No hay elemento ---> Se descarta
# Para Derecha: ¿Es solo un elemento? Si --->Termina.
# 4 Paso: Nivel 0: 7, Nivel 1: 6, Nivel 2: 4, Nivel 3: 2
# 5 Paso: 0, , 1, , 2, 3,  Sin conocer 5, 3, 1
# Salida correcta: No
# Observación: Para los niveles sin conocer, cada que se detecte que solo es un elemento,
# relacionar con el siguiente nivel ese elemento, entonces para nivel 2: 5 nivel 3: 3,
# nivel 4: 1 y la salída sería: 0, 2, 1, 3, 2, 3, 4
# Salida correcta con observación: Si
# 2 Caso (Zig-zag): 4,2,5,1,3
# Nivel 0
# 1 Paso: 5
# 2 Paso: Izquierda-->4,2 .Derecha-->1,3
# 3 Paso: Para Izquierda: ¿Es solo un elemento? No ---> volvemos a 1 Paso con entrada izquierda
# Para Derecha: ¿Es solo un elemento? No ---> volvemos a 1 Paso con entrada derecha
# Nivel 1, Izquierda
# 1 Paso: 4
# 2 Paso: Izquierda--> .Derecha-->2
# 3 Paso: Para Izquierda ¿Es solo un elemento? No hay elemento ---> Se descarta
# Para Derecha: ¿Es solo un elemento? Si ---> Termina y se relaciona con el siguiente nivel
# Nivel 1, Derecha
# 1 Paso: 3
# 2 Paso: Izquierda-->1 .Derecha-->
# 3 Paso: Para Izquierda: ¿Es solo un elemento? Si --->Termina y se relaciona con el siguiente nivel
# Para Derecha: ¿Es solo un elemento? No hay elemento ---> Se descarta
# 4 Paso: Nivel 0: 5, Nivel 1: 4,3, Nivel 2: 2,1
# 5 Paso: 1, 2, 0, 2, 1
# Salida correcta: Si

def permutationTransformation(a,n,nivel)
    # Observación
    if n == 1
        return nivel
    end
    #Pre paso: crear el arreglo del arbol "d" y los arreglos derecha, izquierda
    d = []
    izquierda, derecha = []
    # 1 Paso
    mayor = buscarMayorNumero(a,n)
    # 2 Paso
    izquierda, derecha = separarElementosArreglo(a,n,mayor)
    # 3 Paso
    if izquierda.length>0
        izquierda = permutationTransformation(izquierda,izquierda.length,nivel+1)
    end
    if derecha.length>0
        derecha = permutationTransformation(derecha,derecha.length,nivel+1)
    end
    # 4 Paso
    d = buscarNiveles(izquierda,nivel,derecha)
    return d
end

def buscarNiveles(izquierda,mayor,derecha)
    d = []
    if izquierda.class == Integer
        d.push(izquierda)
    else
        for i in(0..izquierda.length-1)
            d.push(izquierda[i])
        end
    end
    d.push(mayor)
    if derecha.class == Integer
        d.push(derecha)
    else
        for i in(0..derecha.length-1)
            d.push(derecha[i])
        end
    end
    return d
end

def separarElementosArreglo(a,n,mayor)
    izquierda = []
    derecha = []
    #Para izquierda
    for i in(0..mayor-1)
        izquierda.push(a[i])
    end
    #Para derecha
    for i in(mayor+1..n-1)
        derecha.push(a[i])
    end
    return izquierda, derecha
end

def buscarMayorNumero(a,n)
    mayor = a[0]
    posicion = 0
    for i in(0..n-1)
        if a[i]>mayor
            mayor = a[i]
            posicion = i
        end
    end
    return posicion
end

def convertirAInteger(a,n)
    for i in(0..n-1)
        a[i] = Integer(a[i])
    end
    return a
end

def darFormatoDeSalida(d)
    resultado = ""
    if d.class == Integer
        resultado = d.to_s
    else
        for i in(0..d.length-1)
            resultado = resultado + d[i].to_s
            if i != d.length-1
                resultado = resultado + " "
            end
        end
    end
    return resultado
end

# Variables
testcases = 0
n = 0
a = []
d = []
resultado = []

# Pre paso: Pedir los testcases, la longitud del arreglo y el arreglo
# testcases
testcases = Integer(gets.chomp)

for i in(0..testcases-1)
    #Longitud del arreglo
    n = Integer(gets.chomp)
    #Arreglo
    array = gets.chomp
    a = array.split(" ")
    a = convertirAInteger(a,n)
    d = permutationTransformation(a,n,0)
    resultado.push(darFormatoDeSalida(d))
end

resultado.each do |elements|
    puts elements
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	puts a.each_with_index.map { |x, i|
			res = 0
			now = a[i]
			(i + 1...n).each do |j|
				if now < a[j]
					now = a[j]
					res += 1
				end
			end
			now = a[i]
			(0...i).reverse_each do |j|
				if now < a[j]
					now = a[j]
					res += 1
				end
			end
			res
	     }.join(' ')
end


Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally.

The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even.

If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes).

NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy.

n = gets.to_i
digits = gets.chop.split('')

front = digits[0...(n/2)]
rear = digits[(n/2)...n]

fSum = front.map(&:to_i).reduce(:+)
rSum = rear.map(&:to_i).reduce(:+)
sumDelta = fSum - rSum

fEmpty = front.count('?')
rEmpty = rear.count('?')
emptyDelta = fEmpty - rEmpty
totalEmpty = fEmpty + rEmpty

canEqual = false
canEqual = true if sumDelta == 0

if emptyDelta.abs > 0
    d = emptyDelta / 2
    canEqual = (sumDelta % 9 == 0 && sumDelta / 9 == -d)
end

if canEqual
    puts "Bicarp"
else
    puts "Monocarp"
end

n = gets.to_i
digits = gets.chop.split('')

front = digits[0...(n/2)]
rear = digits[(n/2)...n]

fSum = front.map(&:to_i).reduce(:+)
rSum = rear.map(&:to_i).reduce(:+)
sumDelta = fSum - rSum

fEmpty = front.count('?')
rEmpty = rear.count('?')
emptyDelta = fEmpty - rEmpty
totalEmpty = fEmpty + rEmpty

canEqual = false
canEqual = true if sumDelta == 0

if emptyDelta.abs > 0
    d = emptyDelta / 2
    canEqual = true if sumDelta % 9 == 0 && sumDelta / 9 == -d
end

if canEqual
    puts "Bicarp"
else
    puts "Monocarp"
end


The little girl loves the problems on array queries very much.One day she came across a rather well-known problem: you've got an array of $$$n$$$ elements (the elements of the array are indexed starting from 1); also, there are $$$q$$$ queries, each one is defined by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \le l_i \le r_i \le n)$$$. You need to find for each query the sum of elements of the array with indexes from $$$l_i$$$ to $$$r_i$$$, inclusive.The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.

The first line contains two space-separated integers $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) and $$$q$$$ ($$$1 \le q \le 2\cdot10^5$$$) — the number of elements in the array and the number of queries, correspondingly. The next line contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \le a_i \le 2\cdot10^5$$$) — the array elements. Each of the following $$$q$$$ lines contains two space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the $$$i$$$-th query.

In a single line print, a single integer — the maximum sum of query replies after the array elements are reordered. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

n, q = gets.split(' ').collect!{|i| i.to_i}

arr = gets.split(' ').collect!{|i| i.to_i}

d = Array.new(n, 0)
q.times do
	l, r = gets.split(' ').collect!{|i| i.to_i - 1}
	# (l..r).each do |j|
	# 	el[j] += 1
	# end
	d[l] += 1
	d[r+1] -= 1 if r < n-1
end

el = Array.new(n, 0)
sum = 0
n.times do |i|
	sum += d[i]
	el[i] = sum
end

el.sort!.reverse!

arr.sort!.reverse!

maxsum = 0

n.times do |i|
	# j = n - i - 1
	maxsum += arr[i]*el[i]
	break if el[i] == 0
end

p maxsum

n, q = gets.split.collect{|i| i.to_i}
a = gets.split.collect{|i| i.to_i}.sort.reverse
s = Array.new(n+1,0)
q.times do
    l, r = gets.split.collect{|i| i.to_i-1}
    s[l] += 1
    s[r+1] -= 1
end
n.times do |i|
    s[i+1] += s[i]
end
s = s.sort.reverse
puts (0...n).inject(0){|sum, i| sum += s[i]*a[i]}

n, q = gets.split.collect{|i| i.to_i}
a = gets.split.collect{|i| i.to_i}.sort.reverse
s = Array.new(n+1,0)
(0...q).each do
    l, r = gets.split.collect{|i| i.to_i-1}
    s[l] += 1
    s[r+1] -= 1
end
(1...n).each do |i|
    s[i] += s[i-1]
end
s = s.sort.reverse
puts (0...n).inject(0){|sum, i| sum += s[i]*a[i]}

n, q = gets.split.collect{|i| i.to_i}
a = gets.split.collect{|i| i.to_i}
s = Array.new(n+1,0)
e = Array.new(n+1,0)
(0...q).each do
    tmp = gets.split.collect{|i| i.to_i}
    s[tmp[0]] += 1
    e[tmp[1]] += 1
end
(1..n).each do |i|
    s[i] += s[i-1]
    e[i] += e[i-1]
end
(1..n).each do |i|
    s[i] = s[i]-e[i-1]
end
s = s.sort.reverse
a = a.sort.reverse
puts (0...n).inject(0){|sum, i| sum += s[i]*a[i]}

n, q = gets.split.collect{|i| i.to_i}
a = gets.split.collect{|i| i.to_i}.sort.reverse
s = Array.new(n+1,0)
q.times do
    l, r = gets.split.collect{|i| i.to_i-1}
    s[l] += 1
    s[r+1] -= 1
end
n.times do |i|
    s[i+1] += s[i]
end
s.sort!.reverse!
puts (0...n).inject(0){|sum, i| sum += s[i]*a[i]}

n,m,=gets.split.map{|x|x.to_i}
a=gets.split.map{|x|x.to_i}.sort.reverse
b=Array.new(300000,0)
m.times{|i|
  l,r,=gets.split.map{|x|x.to_i}
  b[l-1]+=1
  b[r]-=1
}
z=0
b=b.map{|e|e+z;z+=e}
b.sort!.reverse!
z=0
for i in 0..n-1 do
  z+=(b[i]*a[i])
end
puts "#{z}"


In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.

The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).

Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.

NoteIn the first example the ranks will be raised in the following manner:1 2 2 3  →  2 2 3 4  →  2 3 4 4  →  3 4 4 4  →  4 4 4 4Thus totals to 4 training sessions that require 4 golden coins.

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

ranks=Array.new(104,0)
a.each{|i| ranks[i]+=1}
ans=0
n=a.length
loop do
        if ranks[k]==n then
                puts ans
                exit
        end
        next_rank=Array.new(104,0)
        1.upto(k-1){|a|
                next_rank[a]+=[ranks[a]-1,0].max
                next_rank[a+1]+=[ranks[a],1].min
        }
        next_rank[k]+=ranks[k]
        ranks=next_rank
        ans+=1
end

include Math
require "prime"
require "bigdecimal"
require "bigdecimal/math"
require "matrix"
require "pp"
require "benchmark"

Infinity = 1/0.0
class Matrix;def inspect;empty? ? "Matrix.empty(#{row_size}, #{column_size})":"Matrix[\n#{@rows.map(&:inspect).join("\n")}\n]";end;end
def pbin(obj);case obj;when Integer;puts obj.to_s(2);end;end
class String;def to_a;split("");end;end
class String;def to_ia;split.map(&:to_i);end;end
def getia;gets.to_ia;end
def geti;gets.to_i;end
class Object;def dcopy;Marshal.load(Marshal.dump(self));end;end

n,k=getia
ar=getia
dp=Array.new(k+1).fill(0)
ar.each{|a|dp[a]+=1}
t=0
while dp[k] != n
    nextdp=Array.new(k+1).fill(0)
    for j in 0...k
        next if dp[k-j-1].zero?
        dp[k-j]+=1
        dp[k-j-1]-=1
    end
    t+=1
end
puts t

n,k,*a=gets(p).split.map(&:to_i)
a<<k
a=a.group_by{|_|_}.map{|k,v|[k]*~-v.size+[k+1]}.flatten while a[0]<k
p a[-1]-k

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

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

d=Array.new(k+1, 0)
data.each{|v| d[v]+=1}

if d[-1]==n
	puts 0
	exit
end

ans=0
loop do
	(k-1).downto(1) do |i|
		if d[i]!=0
			d[i+1]+=1
			d[i]-=1
		end
	end

	ans+=1
	break if d[-1]==n
end

puts ans

n,k = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
count = Array.new(k,0)
arr.each do |a|
	count[a-1] += 1
end
move = 0
count1 = count.dup
while count[k-1] != n
	# puts "#{count}"
	move += 1
	count.each_with_index do |a,key|
		if count[key] != 0 && key != k - 1
			count1[key] -= 1
			count1[key+1] += 1
		end
	end
	count = count1.dup
end

puts move

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

tbl = Hash.new(0)
gets.split.each{|x| tbl[x.to_i] += 1 }

cnt = 0
until tbl[k] == n
  tbl2 = Hash.new(0)
  tbl.each do |key, value|
    if key < k
      tbl2[key] += value - 1 if value > 1
      tbl2[key + 1] += 1
    else
      tbl2[key] += value
    end
  end
  tbl = tbl2
  cnt += 1
end
p cnt

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

ranks=Array.new(104,0)
a.each{|i| ranks[i]+=1}
ans=0
n=a.length
loop do
        if ranks[k]==n then
                puts ans
                exit
        end
        next_rank=Array.new(104,0)
        1.upto(k-1){|a|
                next_rank[a]+=ranks[a]/2
                next_rank[a+1]+=(ranks[a]+1)/2
        }
        next_rank[k]+=ranks[k]
        ranks=next_rank
        ans+=1
end

n,k = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
count = Hash.new(0)
arr.each do |a|
	count[a] += 1
end
move = 0
while count[k] != n
	move += 1
	count.keys.each do |key|
		if count[key] != 0 && key != k
			count[key] -= 1
			count[key+1] += 1
		end
	end
end

puts move


Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases.

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

For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$.

NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$.

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	puts a.chunk { _1 < 0 }.sum { _1[1].max }
end

# frozen_string_literal: true

class Result
  def print_result
    gets
    arr = gets.split(' ').map(&:to_i)

    positive_arrs = [[], []]
    positive_arrs.each_with_index do |positive_arr, j|
      positive = j.zero?
      min = 0
      first = true
      arr.each do |i|
        if first
          if positive && i < 0
            next
          elsif !positive && i > 0
            next
          end

          first = false
        end

        if positive && min < i
          min = i
          next
        end

        if positive && i < 0
          positive = false
          positive_arr.push(min)
          min = i
          next
        end

        if !positive && (min == 0 || min < i) && i < 0
          min = i
          next
        end

        next unless !positive && i > 0

        positive = true
        positive_arr.push(min)
        min = i
      end

      positive_arr.push(min) if min != 0
    end

    puts(if positive_arrs[0].size == positive_arrs[1].size
           positive_arrs.map(&:sum).max
         elsif positive_arrs[0].size > positive_arrs[1].size
           positive_arrs[0].sum
         else
           positive_arrs[1].sum
    end)
  end

  private

  attr_reader :n
end

gets.to_i.times do
  Result.new.print_result
end

number_of_testcases = gets.to_s.to_i

number_of_testcases.times do |i|

  n = gets.to_s.to_i
  a = gets.to_s.split.map{|e|e.to_i}.push 0

  ans = 0
  s = []
  a.each do |k|
    if s.size > 0 && s[-1] * k <= 0
      ans += s.max
      s = []
    end
    s << k
  end
  # ans += s.max
  puts ans
end

1.upto(gets.to_i) do
  gets
  a = gets.split(' ').map(&:to_i)

  blocks = []
  while !a.empty?
    sign = a.first / a.first.abs
    blocks << a.take_while { |x| x / x.abs == sign }

    a = a.drop(blocks.last.size)
  end

  puts blocks.inject(0) { |s, e| s + e.max }
end

t=gets.to_i
(1).upto(t) do
  n=gets.to_i
  a=gets.split(' ').map(&:to_i)
  vec = []
  ans = 0
  pos=false
  a.each do |i|
    if vec.empty?
      vec.push(i)
      pos=i>0
      next
    end
    if(i>0 != pos)
      ans+=vec.max
      vec=[i]
      pos = i>0
    else
      vec.push(i)
    end
  end
  ans+=vec.max
  puts ans
end

t=gets.to_i
(1).upto(t) do
  n=gets.to_i
  n>>=1
  if(n&1)==1
    puts "NO"
    next
  end
  puts "YES"
  sum =0
  (1).upto(n) do |i|
    print "#{i*2} "
    sum+=i*2
  end

  (1).upto(n-1) do |i|
    sum-=i*2-1
    print "#{i*2-1} "
  end
  puts sum
end