One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?

The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.

In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
amax = a.max
ans = 0
a.each{|aa| ans += amax-aa}
if amax <= ans
    puts amax
else
    amax -= ans
    ans += amax/(n-1)*n
    amax %= n-1
    ans += amax+1 if amax > 0
    puts ans
end

#! /usr/bin/env ruby

n = STDIN.gets.to_i
rounds = STDIN.gets.to_s.split(' ').map(&:to_i).take(n)

if rounds.length != n
  raise ArgumentError.new
end

def how_many(rounds, n)
  max = rounds.max
  diff_total = rounds.inject(0) {|diff, round| diff += max - round}

  if diff_total >= max
    max
  else
    n -= 1
    rest = max - diff_total
    max + (rest / n) + (rest % n == 0 ? 0 : 1)
  end
end

puts how_many(rounds, n)

n = gets.to_i
arr = gets.split(" ").map{|i| i.to_i}
sum = arr.inject(:+)
max = arr.max
ans = (sum + n - 2) / (n - 1)
puts max > ans ? max : ans

n=gets.to_i; d=gets.split.map(&:to_i); p [d.max,(d.reduce(&:+)+n-2)/(n-1)].max

n = gets.to_i
a = gets.split.map(&:to_i)
mx, s = [0, 0]
a.each {|i|
  mx = [mx, i].max
  s += i
}
puts [mx, (s+n-2).div(n.pred)].max

#! /usr/bin/env ruby

n = STDIN.gets.to_i
rounds = STDIN.gets.to_s.split(' ').map(&:to_i).sample(n)

if rounds.length != n
  raise ArgumentError.new
end

def how_many(rounds)
  max = rounds.max
  diff_total = rounds.inject(0) {|diff, round| diff += max - round}

  if diff_total == 0
    return max + (max / rounds.length) + ( max % rounds.length == 0 ? 0 : 1)
  end

  if diff_total >= max
    return max
  end

  max + (max - diff_total)
end

puts how_many(rounds)

#! /usr/bin/env ruby

n = STDIN.gets.to_i
rounds = STDIN.gets.to_s.split(' ').map(&:to_i).sample(n)

if rounds.length != n
  raise ArgumentError.new
end

def how_many(rounds)
  max = rounds.max
  diff_total = rounds.inject(0) {|diff, round| diff += max - round}

  if diff_total == 0
    return max + (max / rounds.length) + 1
  end

  if diff_total >= max
    return max
  end

  return max + (max - diff_total)
end

puts how_many(rounds)

#! /usr/bin/env ruby

n = STDIN.gets.to_i
rounds = STDIN.gets.to_s.split(' ').map(&:to_i).take(n)

if rounds.length != n
  raise ArgumentError.new
end

def how_many(rounds, n)
  max = rounds.max
  diff_total = rounds.inject(0) {|diff, round| diff += max - round}

  if diff_total == 0
    return max + (max / n) + ( max % n == 0 ? 0 : 1)
  end

  if diff_total >= max
    return max
  end

  max + (max - diff_total)
end

puts how_many(rounds, n)

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
amax = a.max
cnt = 0
a.each{|aa| cnt += amax-aa}
if amax <= cnt
    puts amax
else
    amax -= cnt
    puts cnt+amax/(n-1)*n+amax%(n-1)+1
end

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
amax = a.max
cnt = 0
a.each{|aa| cnt += amax-aa}
amax -= cnt
if amax <= 0
    puts cnt
else
    puts cnt+amax/(n-1)*n+amax%(n-1)+1
end

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
amax = a.max
cnt = 0
a.each{|aa| cnt += amax-aa}
amax -= cnt
if amax.zero?
    puts cnt
else
    puts cnt+amax/(n-1)*n+amax%(n-1)+1
end

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
amin, amax = a.minmax
ans = 0
if amin/(n-1) > 0
    amax -= amin
    ans += amin/(n-1)*n
    amin %= n-1
end
if amax != amin
    ans += amax
else
    ans += amax+1
end
puts ans

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
amax = a.max
cnt = 0
a.each{|aa| cnt += amax-aa}
amax -= cnt
puts cnt+amax/(n-1)*n+amax%(n-1)+1

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
puts a.max+1

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
amin, amax = a.minmax
ans = 0
if amin/(n-1) > 0
    amax -= amin
    ans += amin/(n-1)*n
    amin %= n-1
end
if amin.zero?
    ans += amax
else
    ans += amax+1
end
puts ans

people = gets.to_i
take_rounds = gets.split.map(&:to_i)
max = take_rounds.max
sum = take_rounds.reduce(&:+)
if sum <= max * people.pred
  puts max
else
  puts max.next
end


The Human-Cow Confederation (HC2), led by Heidi, has built a base where people and cows can hide, guarded from zombie attacks. The entrance to the base is protected by an automated gate which performs a kind of a Turing test: it shows the entering creature a photograph and asks them whether the top and bottom halves of this photograph have been swapped or not. A person (or even a cow) will have no problem answering such questions; on the other hand, a zombie would just randomly smash one of the two buttons.The creature is asked a series of such questions. If at least 75% of them are answered correctly, the gate is unlocked; otherwise, a side door opens, beneath which a huge fan is spinning...Heidi is now building a robot army to fight the zombies, and she wants the robots to also be able to enter the base. You are tasked with programming them to distinguish the images. The first two images from the test set. The first picture has been rearranged, but not the second.

The first line of the input contains the number q of questions (1 ≤ q ≤ 220). After that, q questions follow, each of which in the format described below. The first line of every question contains two space-separated integers h and w (1 ≤ h, w ≤ 600) – the height (number of rows) and width (number of columns) of the photograph. (Most photographs are roughly 200 × 300.) After this, h lines follow, each describing a single row of the picture. The picture is monochrome (in shades of grey). Its i-th row is described by w space-separated integers aij (j = 1, ..., w), where aij is the brightness of the corresponding pixel (0 ≤ aij < 256, where 0 is black and 255 is white). Each picture will be either a real-life photograph, or a real-life photograph which has been broken up into two pieces and rearranged. More precisely, in the latter case, the topmost  rows have been moved to the bottom of the picture. It is guaranteed that h is even. There is only a single input file to be processed, called all.in, and it is downloadable from the online judge. You are also a given another input file, called sample.in, which contains the first 20 pictures from all.in; you are provided the correct answers for sample.in in sample.out. You are also given a directory easy_bmp, which contains the first 50 input photographs in the form of .bmp image files, as well as a directory easy_sample_original_bmp, which contains the first 20 images before rearrangement. Check the notes for the download links.

Your program should print q lines. The i-th line should contain your answer for the i-th question: YES if the photograph has been rearranged and NO otherwise. Your answers will be accepted if they all conform to this format and if at least 75% of them are correct. Because the input is rather huge, feel free to process it locally and submit just your precomputed answers (i.e., a program which just prints your output for the input file all.in).

NoteThe link to download all necessary files is http://assets.codeforces.com/files/690/easy_contestant_package.zip

print "YES
NO
NO
YES
NO
NO
NO
NO
NO
YES
YES
YES
YES
NO
YES
YES
NO
YES
YES
YES
NO
NO
YES
NO
NO
YES
NO
NO
YES
YES
NO
YES
NO
NO
NO
YES
YES
YES
NO
YES
YES
NO
YES
YES
NO
YES
YES
YES
NO
YES
NO
NO
YES
YES
YES
YES
YES
YES
YES
NO
YES
NO
NO
NO
NO
YES
NO
NO
YES
NO
YES
NO
YES
NO
NO
NO
YES
YES
NO
YES
YES
NO
NO
NO
NO
NO
NO
YES
NO
NO
YES
NO
YES
NO
NO
NO
NO
YES
YES
YES
YES
YES
NO
NO
NO
YES
NO
YES
NO
YES
NO
YES
NO
NO
YES
YES
YES
YES
NO
NO
NO
YES
NO
YES
YES
YES
NO
YES
NO
NO
NO
YES
NO
NO
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
NO
YES
NO
NO
NO
NO
NO
YES
NO
NO
YES
NO
YES
NO
YES
NO
YES
NO
NO
YES
NO
NO
NO
YES
NO
NO
NO
NO
YES
NO
NO
NO
NO
YES
NO
YES
NO
YES
NO
NO
NO
YES
YES
NO
YES
NO
YES
YES
YES
NO
YES
YES
NO
YES
NO
YES
YES
NO
YES
YES
NO
NO
YES
NO
NO
NO
YES
YES
NO
NO
"


You are given an integer $$$n$$$ ($$$n > 1$$$).Your task is to find a sequence of integers $$$a_1, a_2, \ldots, a_k$$$ such that:  each $$$a_i$$$ is strictly greater than $$$1$$$;  $$$a_1 \cdot a_2 \cdot \ldots \cdot a_k = n$$$ (i. e. the product of this sequence is $$$n$$$);  $$$a_{i + 1}$$$ is divisible by $$$a_i$$$ for each $$$i$$$ from $$$1$$$ to $$$k-1$$$;  $$$k$$$ is the maximum possible (i. e. the length of this sequence is the maximum possible). If there are several such sequences, any of them is acceptable. It can be proven that at least one valid sequence always exists for any integer $$$n > 1$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 10^{10}$$$). It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^{10}$$$ ($$$\sum n \le 10^{10}$$$).

For each test case, print the answer: in the first line, print one positive integer $$$k$$$ — the maximum possible length of $$$a$$$. In the second line, print $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ — the sequence of length $$$k$$$ satisfying the conditions from the problem statement. If there are several answers, you can print any. It can be proven that at least one valid sequence always exists for any integer $$$n > 1$$$.

require'prime'
gets;$<.map{|l|i=l.to_i;x,y=i.prime_division.map{|k,v|[v-1,k]}.max;p x+1;puts ([y]*x+[i/y**x])*' '}

require 'prime'
t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = n.prime_division
  res = []
  while arr.any?
    res << arr.map{|el| el[0]}.inject(:*)
    arr = arr.map{|el| [el[0], el[1] - 1]}
    arr.filter! {|el| el[1] > 0}
  end
  puts res.size
  puts res.reverse.join(' ')
end


You are given an array $$$a$$$ of $$$n$$$ integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_j - a_i = j - i$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_j - a_i = j - i$$$.

t = gets.chomp.to_i
t.times do
  hash = {}
  n = gets.chomp.to_i
  a = gets.split.map{|_|_.to_i}
  a.each_with_index do |num, i|
    hash[num-i] = (hash[num-i] || 0) + 1
  end
  puts hash.values.map{|v| v*(v-1)/2}.sum
end

t = gets.chomp.to_i

t.times do
  hash = {}
  n = gets.chomp.to_i
  a = gets.split.map{|_|_.to_i}
  a.each_with_index do |num, i|
    hash[num-i] = (hash[num-i] || 0) + 1
  end
  rs = 0
  hash.values.each{|v| rs+=v*(v-1)/2}
  puts rs
end

def read_test_case
  # @type [String]
  line = gets.chomp
  # &: notation is sometimes called 'pretzel colon'
  # Kind of like a method references? It's syntax sugar for some Proc magic:
  # &:to_i == { |foo| foo.to_i }
  # :to_i here is a symbol, and:
  line.split(' ').map(&:to_i)
end

# @param nums [Array]
def get_diff_array(nums)
  nums.map.each_with_index do |num, idx|
    # Problem uses 1 indexing, so I'll be consistent
    num - (idx + 1)
  end
end

# @param diffs [Array]
def count_diff_array(diffs)
  counts = {}
  diffs.each do |diff|
    if !counts.include? diff
      counts[diff] = 1
    else
      counts[diff] += 1
    end
  end
  counts
end

# @param counts [Hash]
def count_total_pairs(counts)
  pairs = 0
  counts.each_value do |count|
    pairs += compute_triangular_number(count - 1)
  end
  pairs
end

def compute_triangular_number(n)
  (n * (n + 1)) / 2
end

# @type[Integer]
t = gets.chomp.to_i

(1..t).each do
  _test_size = gets

  test = read_test_case
  diff_array = get_diff_array test
  counts = count_diff_array diff_array
  puts count_total_pairs counts
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.strip.split.map {|x| x.to_i }
  0.upto(n - 1) {|i| a[i] -= i }
  cnt = {}
  a.each {|x| cnt[x] = (cnt[x] || 0) + 1 }
  result = 0
  cnt.each {|k, v| result += v * (v - 1) / 2 }
  printf("%d\n", result)
end


Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how many times he had a breakfast, a dinner and a supper (thus, the card contains three integers). Vasiliy could sometimes have missed some meal, for example, he could have had a breakfast and a supper, but a dinner, or, probably, at some days he haven't been at the dining room at all.Vasiliy doesn't remember what was the time of the day when he arrived to sanatorium (before breakfast, before dinner, before supper or after supper), and the time when he left it (before breakfast, before dinner, before supper or after supper). So he considers any of these options. After Vasiliy arrived to the sanatorium, he was there all the time until he left. Please note, that it's possible that Vasiliy left the sanatorium on the same day he arrived.According to the notes in the card, help Vasiliy determine the minimum number of meals in the dining room that he could have missed. We shouldn't count as missed meals on the arrival day before Vasiliy's arrival and meals on the departure day after he left.

The only line contains three integers b, d and s (0 ≤ b, d, s ≤ 1018,  b + d + s ≥ 1) — the number of breakfasts, dinners and suppers which Vasiliy had during his vacation in the sanatorium.

Print single integer — the minimum possible number of meals which Vasiliy could have missed during his vacation.

NoteIn the first sample, Vasiliy could have missed one supper, for example, in case he have arrived before breakfast, have been in the sanatorium for two days (including the day of arrival) and then have left after breakfast on the third day. In the second sample, Vasiliy could have arrived before breakfast, have had it, and immediately have left the sanatorium, not missing any meal.In the third sample, Vasiliy could have been in the sanatorium for one day, not missing any meal.

a, b, c = gets.split.map(&:to_i)
x = 0
if a>=b && a>=c
    x+=1 if a!=b
    x+=1 if a!=c
   p a-b+a-c-x
elsif c>=b && c>=a
    x+=1 if c!=b
    x+=1 if c!=a
    p c-b+c-a-x
else
    x+=1 if c!=b
    x+=1 if b!=a
    p b-c+b-a-x
end

a=gets.split.map(&:to_i)
m=a.max-1
p a.select{|e|e<m}.reduce(0){|s,e|s+m-e}

a = gets.split.map &:to_i
m = a.max - r = 1
a.map{|e| e < m && r += m - e}
p ~- r

a=gets.split.map &:to_i
m=a.max-r=1
a.map{|e|e<m&&r+=m-e}
p~-r

class Sanatorium
  def self.get_advice(meat_cnt)
    meat_at_last_day = false
    meat_at_first_day = false
    result=0
    return 0 if meat_cnt.all? {|x| x==meat_cnt[2]}
    return 0 if meat_cnt.all? {|x| x<=1}

    if meat_cnt.max == meat_cnt[2] #&& meat_cnt[2]> meat_cnt[0]
      meat_cnt[1]-=1 if meat_cnt[2]==meat_cnt[1]
      meat_cnt[2]-=1
      return 0 if meat_cnt.all? {|x| x==meat_cnt[2]}
      meat_at_first_day=true
    end

    if meat_cnt.max == meat_cnt[0] && meat_cnt[0]>meat_cnt[2]
      meat_cnt[1]-=1 if meat_cnt[0]== meat_cnt[1]
      meat_cnt[0]-=1
      return 0 if meat_cnt.all? {|x| x==meat_cnt[0]}
      meat_at_last_day=true
    end

    if meat_cnt.max == meat_cnt[1]
      if !meat_at_last_day && meat_cnt[1]>meat_cnt[2]
        meat_cnt[1]-=1
        if meat_cnt[0]>0
          meat_cnt[0]-=1
        else
          result+=1
        end
      end
      if !meat_at_first_day && meat_cnt[1]>meat_cnt[0]
        meat_cnt[1]-=1
        if meat_cnt[2]>0
          meat_cnt[2]-=1
        else
          result+=1
        end
      end
      return result if meat_cnt.all? {|x| x==meat_cnt[1]}
    end
    meat_cnt=(meat_cnt.map { |x| x-meat_cnt.min })
    return 0 if meat_cnt.all? {|x| x.zero?}
    result+=case meat_cnt.count(0)
              when 2
                meat_cnt.reduce(:+)*2
              when 1
                meat_cnt.select {|x| x.nonzero?}.minmax.reduce(0) {|sum,x| (sum.zero?) ? (sum-x):(sum+x*2)}
            end
  end

  def self.run
    puts get_advice($stdin.readline.chomp.split.map(&:to_i))
  end
end

if __FILE__ == $0
  Sanatorium.run
end

def ev(arr)
  arr.sort!
  arr[2] - arr[0] + arr[2] - arr[1]
end

b, d, s = gets.strip.split(' ').map(&:to_i)
mn = [b, d, s].min
b -= mn
d -= mn
s -= mn
if b == d && d == s
  printf("%d\n", 0)
else
  v = []
  arr = [b, d, s]
  0.upto(2) do |i|
    0.upto(2) do |j|
      arr_c1 = arr.clone
      arr_c1[i] += 1
      arr_c2 = arr.clone
      arr_c2[j] += 1
      arr_c3 = arr.clone
      arr_c3[i] += 1
      arr_c3[j] += 1 if i != j
      v << ev(arr_c1)
      v << ev(arr_c2)
      v << ev(arr_c3)
    end
  end

  printf("%d\n", v.min)
end

a, b, c = gets.split.map(&:to_i)
p [[a, b, c].max-[a, b, c].min-1, 0].max

a = gets.split.map &:to_i
m = a.max - r = 1
a.map{|e| e < m && r += m - e; puts r}
p r - 1

a=gets.split.map &:to_i
def solution(b,d,s)
	max = [b,d,s].max
	sum = 0
	case max
	when b
		sum += max - d - 1  if max > d + 1
		sum += max - s - 1  if max > s + 1
	when d
		sum += max - b if max > b
		sum += max - s - 1 if max > s + 1
	when s
		sum += max - b if max > b
		sum += max - d if max > d
	end
	sum
end
p solution(a[0],a[1],a[2])

a=gets.split.map &:to_i
def solution(b,d,s)
	max = [b,d,s].max
	sum = 0
	case max
	when b
		sum += max - d - 1  if max > d + 1
		sum += max - s - 1  if max > s + 1
	when d
		sum += max - b  if max > b && b != 0
		sum += max - s - 1 if max > s + 1
	when s
		sum += max - b if max > b && b != 0
		sum += max - d if max > d && d != 0
	end
	sum
end
p solution(a[0],a[1],a[2])

def ev(arr)
  b, d, s = arr
  (b - d).abs + (d - s).abs
end

b, d, s = gets.strip.split(' ').map(&:to_i)
mn = [b, d, s].min
b -= mn
d -= mn
s -= mn
if b == d && d == s
  printf("%d\n", 0)
else
  v = []
  arr = [b, d, s]
  0.upto(2) do |i|
    0.upto(2) do |j|
      arr_c1 = arr.clone
      arr_c1[i] -= 1
      arr_c2 = arr.clone
      arr_c2[j] -= 1
      arr_c3 = arr.clone
      arr_c3[i] -= 1
      arr_c3[j] -= 1
      v << ev(arr_c1)
      v << ev(arr_c2)
      v << ev(arr_c3)
    end
  end
  printf("%d\n", v.min)
end

b, d, s = gets.strip.split(' ').map(&:to_i)
mn = [b, d, s].min
b -= mn
d -= mn
s -= mn
if b == d && d == s
  printf("%d\n", 0)
else
  arr = [b, d, s]
  mx = -1
  cnt = 0
  arr.each do |l|
    if l > mx
      mx = l
      cnt = 1
    elsif l == mx
      cnt += 1
    end
  end
  if cnt == 2
    0.upto(2) do |i|
      arr[i] -= 1 if mx == arr[i]
    end
    printf("%d\n", arr.max - arr.min)
  else
    0.upto(2) do |i|
      arr[i] -= 1 if mx == arr[i]
    end
    printf("%d\n", arr.max - arr.min)
  end
end

b, d, s = gets.strip.split(' ').map(&:to_i)
mn = [b, d, s].min
b -= mn
d -= mn
s -= mn
if b == d && d == s
  printf("%d\n", 0)
else
  arr = [b, d, s]
  mx = -1
  cnt = 0
  arr.each do |l|
    if l > mx
      mx = l
      cnt = 1
    elsif l == mx
      cnt += 1
    end
  end
  if cnt == 2
    0.upto(2) do |i|
      arr[i] -= 1 if mx == arr[i]
    end
    printf("%d\n", arr.max - arr.min)
  else
    0.upto(2) do |i|
      arr[i] -= 1 if mx == arr[i]
    end
    if arr.uniq == 3
      printf("%d\n", (arr[0] - arr[1]).abs + (arr[1] - arr[2]).abs - 1)
    else
      printf("%d\n", arr.max - arr.min)
    end
  end
end

def ev(arr)
  b, d, s = arr
  ((b - d).abs + (d - s).abs + (s - b).abs) / 2
end

b, d, s = gets.strip.split(' ').map(&:to_i)
mn = [b, d, s].min
b -= mn
d -= mn
s -= mn
if b == d && d == s
  printf("%d\n", 0)
else
  v = []
  arr = [b, d, s]
  0.upto(2) do |i|
    0.upto(2) do |j|
      arr_c1 = arr.clone
      arr_c1[i] -= 1
      arr_c2 = arr.clone
      arr_c2[j] -= 1
      arr_c3 = arr.clone
      arr_c3[i] -= 1
      arr_c3[j] -= 1
      v << ev(arr_c1)
      v << ev(arr_c2)
      v << ev(arr_c3)
    end
  end
  printf("%d\n", v.min)
end


Timur likes his name. As a spelling of his name, he allows any permutation of the letters of the name. For example, the following strings are valid spellings of his name: Timur, miurT, Trumi, mriTu. Note that the correct spelling must have uppercased T and lowercased other letters.Today he wrote string $$$s$$$ of length $$$n$$$ consisting only of uppercase or lowercase Latin letters. He asks you to check if $$$s$$$ is the correct spelling of his name.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ $$$(1 \leq n \leq 10)$$$ — the length of string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting of only uppercase or lowercase Latin characters.

For each test case, output "YES" (without quotes) if $$$s$$$ satisfies the condition, and "NO" (without quotes) otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

10

5

Timur

5

miurT

5

Trumi

5

mriTu

5

timur

4

Timr

6

Timuur

10

codeforces

10

TimurTimur

5

TIMUR

t = gets.chomp.to_i

for i in 0..t-1

  n = gets.chomp.to_i
  name = gets.chomp
  if name = name.chars.sort.join == "Timru"
    puts "YES"
  else
    puts "NO"
  end

end

gets.to_i.times do
  gets
  puts gets.chomp.chars.sort == 'Timur'.chars.sort ? :YES : :NO
end

t = gets.chomp.to_i

for i in 0..t-1

  n = gets.chomp.to_i
  name = gets.chomp
  if name = name.chars.sort.join == "Timru"
    print "Yes"
  else
    print "No"
  end

end


You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps:   Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements.  Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements.  Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive).

gets.to_i.times do
  gets
  as = gets.split.map(&:to_i)
  ((as.size % 2)..as.size - 2).step(2).each do |i|
    if as[i] > as[i + 1]
      as[i], as[i + 1] = as[i + 1], as[i]
    end
  end
  ok = as.each_cons(2).all? { |a, b| a <= b }
  puts ok ? "YES" : "NO"
end

T = gets.to_i
T.times do
    n = gets.to_i
    a = gets.split.map(&:to_i)
    a.unshift(0) if n.odd?
    n = a.size
    puts (0 ... n / 2 - 1).all? { |i| a[i * 2, 2].max <= a[i * 2 + 2, 2].min } ? "YES" : "NO"
end

gets.to_i.times do
  gets
  as = gets.split.map(&:to_i)
  (0..as.size - 2).step(2).each do |i|
    if as[i] > as[i + 1]
      as[i], as[i + 1] = as[i + 1], as[i]
    end
  end
  ok = as.each_cons(2).all? { |a, b| a <= b }
  puts ok ? "YES" : "NO"
end

T = gets.to_i
T.times do
    n = gets.to_i
    a = gets.split.map(&:to_i)
    a << 10**18 if n.odd?
    n = a.size
    puts (0 ... n / 2 - 1).all? { |i| a[i * 2, 2].max <= a[i * 2 + 2, 2].min } ? "YES" : "NO"
end


A palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you déjà vu.There is a string $$$s$$$. You must insert exactly one character 'a' somewhere in $$$s$$$. If it is possible to create a string that is not a palindrome, you should find one example. Otherwise, you should report that it is impossible.For example, suppose $$$s=$$$ "cbabc". By inserting an 'a', you can create "acbabc", "cababc", "cbaabc", "cbabac", or "cbabca". However "cbaabc" is a palindrome, so you must output one of the other options.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The only line of each test case contains a string $$$s$$$ consisting of lowercase English letters. The total length of all strings does not exceed $$$3\cdot 10^5$$$.

For each test case, if there is no solution, output "NO". Otherwise, output "YES" followed by your constructed string of length $$$|s|+1$$$ on the next line. If there are multiple solutions, you may print any. You can print each letter of "YES" and "NO" in any case (upper or lower).

YES
cbabac
YES
aab
YES
zaza
YES
baa
NO
YES
nutforajarofatuna

NoteThe first test case is described in the statement.In the second test case, we can make either "aab" or "aba". But "aba" is a palindrome, so "aab" is the only correct answer.In the third test case, "zaza" and "zzaa" are correct answers, but not "azza".In the fourth test case, "baa" is the only correct answer.In the fifth test case, we can only make "aa", which is a palindrome. So the answer is "NO".In the sixth test case, "anutforajaroftuna" is a palindrome, but inserting 'a' elsewhere is valid.

def palindrome?(string)
  string == string.reverse
end

# returns correct string if found else returns nil
def no_palindrome(string)
  # appending 'a' before or after a string is enough to break a palindrome
  return "a#{string}" unless palindrome?("a#{string}")
  return "#{string}a" unless palindrome?("#{string}a")

  nil
end

# prints output for test cases
def print_answer(string)
  answer = no_palindrome(string)

  return puts 'NO' if answer.nil?

  puts 'YES'
  puts answer
end

#### code for tests:

number_of_cases = gets.chomp.to_i

number_of_cases.times do
  string = gets.chomp
  print_answer(string)
end

n=gets.rstrip.to_i
n.times do
    s=gets.rstrip
    valid=false
    s.each_char do |c|
        if c!='a'
            valid=true
            break
        end
    end
    if valid
        puts "YES"
        s2=s+'a'
        if s2==s2.reverse
            puts 'a'+s
        else
            puts s2
        end
    else
        puts "NO"
    end
 end

def is_pal?(s)
  half = s.size / 2
  s[0...half] === s[-half..-1].reverse
end

gets.to_i.times {
  s = gets.chomp
  if s.count('a') === s.size
    puts 'NO'
  else
    puts 'YES'
    s2 = "a#{s}"
    if !is_pal?(s2)
      puts s2
    else
      puts "#{s}a"
    end
  end
}

gets.to_i.times do
  s=gets.chomp
  z=s.size
  i=0
  j=z-1
  f=false
  while i<=j
    if s[i]=="a"&&s[j]=="a"
      i+=1
      j-=1
    elsif s[j]=="a"
      puts "YES"
      if j==z-1
        puts s+"a"
      else
        puts s[0..j]+"a"+s[j+1..]
      end
      f=true
      break
    else
      puts "YES"
      if i==0
        puts "a"+s
      else
        puts s[0...i]+"a"+s[i..]
      end
      f=true
      break
    end
  end
  if !f
    puts "NO"
  end
end


A championship is held in Berland, in which $$$n$$$ players participate. The player with the number $$$i$$$ has $$$a_i$$$ ($$$a_i \ge 1$$$) tokens.The championship consists of $$$n-1$$$ games, which are played according to the following rules:  in each game, two random players with non-zero tokens are selected;  the player with more tokens is considered the winner of the game (in case of a tie, the winner is chosen randomly);  the winning player takes all of the loser's tokens; The last player with non-zero tokens is the winner of the championship.All random decisions that are made during the championship are made equally probable and independently.For example, if $$$n=4$$$, $$$a = [1, 2, 4, 3]$$$, then one of the options for the game (there could be other options) is:   during the first game, the first and fourth players were selected. The fourth player has more tokens, so he takes the first player's tokens. Now $$$a = [0, 2, 4, 4]$$$;  during the second game, the fourth and third players were selected. They have the same number of tokens, but in a random way, the third player is the winner. Now $$$a = [0, 2, 8, 0]$$$;  during the third game, the second and third players were selected. The third player has more tokens, so he takes the second player's tokens. Now $$$a = [0, 0, 10, 0]$$$;  the third player is declared the winner of the championship. Championship winners will receive personalized prizes. Therefore, the judges want to know in advance which players have a chance of winning, i.e have a non-zero probability of winning the championship. You have been asked to find all such players.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case consists of one positive integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of players in the championship. The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the number of tokens the players have. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the number of players who have a nonzero probability of winning the championship. On the next line print the numbers of these players in increasing order. Players are numbered starting from one in the order in which they appear in the input.

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).each_with_index.to_a.sort
	sum = 0

	f = -1
	(0...n).each do |i|
		sum += a[i][0]
		f = i unless i == n - 1 || sum >= a[i + 1][0]
	end
	ans = a[f + 1..].map { _1[1] + 1 }.sort
	puts ans.size, ans.join(' ')
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).each_with_index.to_a.sort
	sum = 0

	ans = []
	(0...n).each do |i|
		sum += a[i][0]
		ans << a[i][1] + 1 if i == n - 1 || sum >= a[i + 1][0]
	end
	puts ans.size, ans.sort.join(' ')
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).sort
	sum = 0
	ans =
		(0...n).select do |i|
			sum += a[i]
			i == n - 1 || sum >= a[i + 1]
		end.map { _1 + 1 }
	puts ans.size, ans.join(' ')
end


Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.

The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.

NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.

gets
a = gets.split(" ").map(&:to_i)
n=a.size
base = a.min
ans = 0

sans = base*n
(a+a).each do |x|
  if x == base
    sans = base*n
  else
    sans += 1
  end
  ans = sans if sans > ans
end

p ans

n = gets.strip.to_i
ar = gets.strip.split.map(&:to_i)
m = ar.min
a = ar.each_with_index.select{|e, i| e == m}
c = a.reduce([]){|res, e| res <<e[1]}
b = c.each_cons(2).map{|a,b| b-a-1}
b << (c[0] +n-c[-1]-1 )
puts n*m+b.max

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

amin = 10**9
hs = Hash.new{ |hs, k| hs[k] = [] }

for i in 0...n
  a = as[i]
  amin = [amin, a].min
  hs[a] << i
end

cols = n - 1 - hs[amin][-1] + hs[amin][0]
for i in 1...hs[amin].size
  cols = [cols, hs[amin][i] - hs[amin][i - 1] - 1].max
end

puts n * amin + cols

n = gets.chomp.to_i
jars = gets.chomp.split(" ").map(&:to_i)
jarmin = jars.min
if jars.uniq.length == 1 then
  puts jars.length * jarmin
else
  jars = jars * 2
  rem = 0
  i = 0
  while true
    break if jars.empty?
    j = jars.shift
    if j == jarmin then
      rem = [rem, i].max
      i = 0
    else
      i += 1
    end
  end
  puts n * jarmin + [rem, i].max
end

n = Integer(gets)
s = gets
mas = s.split(" ")
a = Array.new(n, Array.new(2))
for i in 0...n
    a[i] = [i, mas[i].to_i]
end

a.sort! do |x, y|
    if x[1] < y[1]
        -1
    elsif x[1] > y[1]
        1
    else
        x[0] <=> y[0]
    end
end

def max(x, y)
    if x > y
        return x
    else
        return y
    end
end

ans = a[0][1] * n

x = 0
i = 0
pL = a[0][0]
pR = a[0][0]
while i + 1 < n && a[i][1] == a[i + 1][1]
    pR = a[i + 1][0]
    x = max(x, pR - a[i][0])
    i += 1
end

x = max(x, n - pR + pL) - 1
ans += x
puts ans

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

amin = 10**9
fst = Hash.new(n - 1)
lst = Hash.new(0)

for i in 0...n
  a = as[i]
  amin = [amin, a].min
  fst[a] = [fst[a], i].min
  lst[a] = [lst[a], i].max
end

puts n * (amin + 1) - (lst[amin] - fst[amin] + 1)

n = Integer(gets)
s = gets
a = Array.new(n, Array.new(2))
t = 0
sz = 0
for i in 0...s.length
    c = s[i]
    if c == " "
        a[sz] = [sz, t]
        t = 0
        sz += 1
    else
        t = t * 10 + c.to_i
    end
end
a[sz] = [sz,t]
sz += 1
t = 0

a.sort! do |x, y|
    if x[1] < y[1]
        -1
    elsif x[1] > y[1]
        1
    else
        x[0] <=> y[0]
    end
end

def max(x, y)
    if x > y
        return x
    else
        return y
    end
end

ans = a[0][1] * n

x = 0
i = 0
pL = a[0][0]
pR = a[0][0]
while i + 1 < n && a[i][1] == a[i + 1][1]
    pR = a[i + 1][0]
    x = max(x, pR - a[i][0])
    i += 1
end

x = max(x, n - pR + pL) - 1
ans += x
puts ans


Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?

The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.

Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.

NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.

require 'set'

str = gets.chomp

# nunmber = -1
# string = input
# index  = input
def fun(number, str, index, length)

	if index >=length
		return 0
	end

	if number == -1
		number = str[index].to_i
	else
		number *= 10 + str[index].to_i
	end

	if number % 3 == 0
		return 1 + fun(-1, str, index + 1, length)
	else
		return [fun(number, str, index + 1, length), fun(-1, str, index + 1, length)].max
	end
end

def dp_fun(str, length)
	a = str.split('').map(&:to_i)
	dp_a = Array.new(length, 0)
	index_i = 0
	index_j = -1
	while index_i < length
		i = index_i
		number = 0
		(dp_a[index_i] += dp_a[index_i - 1]) if (index_i -1 >= 0)
		while i > index_j
			number *= 10
			number += a[i]
			if number % 3 == 0
				dp_a[index_i] += 1
				index_j = index_i
				break
			end
			i -= 1
		end
		index_i += 1
	end
	return dp_a[length-1]
end

print dp_fun(str, str.size)

def max_div_3(digit_string)
  digits = digit_string.chomp.chars.map(&:to_i)

  prefix_sums = [0]
  crt = 0
  digits.each do |d|
    crt += d
    prefix_sums << crt
  end

  count = 0
  i = 0
  j = 0

  while j < digits.size
    start_index = (i..j).find do |k|
      range_sum = prefix_sums[j + 1] - prefix_sums[k]
      range_sum % 3 < 1
    end

    if start_index
      count += 1
      j = j + 1
      i = j
    else
      j = j + 1
    end
  end

  count
end

def solution
  input = gets
  puts(max_div_3(input))
end

solution

S = gets.chomp.split('').map{|c| c.to_i % 3}
A = [true, false, false]
arr = A.dup
sum = 0
ans = 0
S.each do |a|
    sum = (sum + a) % 3
    if arr[sum]
        ans += 1
        sum = 0
        arr = A.dup
    else
        arr[sum] = true
    end
end
puts ans

ary = gets.strip.split('').map(&:to_i)
n = ary.size
dp = Array.new(n+5, 0)

dp[0] = (ary[0]%3==0 ? 1 : 0)

1.upto(n-1).each do |i|
  sum = 0
  dp[i] = dp[i-1]
  i.downto(0).each do |j|
    sum += ary[j]
    if sum%3 ==0
      dp[i] = [dp[i], ((j>0 ? dp[j-1] : 0) + 1)].max
      break
    end
    break if dp[j]<dp[i]
  end
end

puts dp[n-1]

def max_div_3(digit_string)
  digits = digit_string.chomp.chars.map(&:to_i)

  prefix_sums = [0]
  crt = 0
  digits.each do |d|
    crt += d
    prefix_sums << crt
  end

  p prefix_sums

  count = 0
  i = 0
  j = 0

  while j < digits.size
    start_index = (i..j).find do |k|
      range_sum = prefix_sums[j + 1] - prefix_sums[k]
      range_sum % 3 < 1
    end

    if start_index
      count += 1
      j = j + 1
      i = j
    else
      j = j + 1
    end
  end

  count
end

puts(max_div_3(gets))


You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$n$$$ is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold:  At least $$$\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \dots, n - 1$$$ are greater than or equal to $$$0$$$.  At least $$$\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \dots, n - 1$$$ are less than or equal to $$$0$$$. Find any valid way to flip the signs. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 500$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \le n \le 99$$$, $$$n$$$ is odd)  — the number of integers given to you. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)  — the numbers themselves. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10000$$$.

For each test case, print $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$, corresponding to the integers after flipping signs. $$$b_i$$$ has to be equal to either $$$a_i$$$ or $$$-a_i$$$, and of the adjacent differences $$$b_{i + 1} - b_i$$$ for $$$i = 1, \dots, n - 1$$$, at least $$$\frac{n - 1}{2}$$$ should be non-negative and at least $$$\frac{n - 1}{2}$$$ should be non-positive. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.

NoteIn the first test case, the difference $$$(-4) - (-2) = -2$$$ is non-positive, while the difference $$$3 - (-4) = 7$$$ is non-negative.In the second test case, we don't have to flip any signs. All $$$4$$$ differences are equal to $$$0$$$, which is both non-positive and non-negative.In the third test case, $$$7 - (-4)$$$ and $$$4 - (-6)$$$ are non-negative, while $$$(-4) - (-2)$$$ and $$$(-6) - 7$$$ are non-positive.

tests = gets.strip.to_i

tests.times{|i|
    inputs = gets.strip.to_i
    puts gets.strip.split(' ').each_with_index.map{|v, i|
        if i.even?
            v.to_i.abs * -1
        else
            v.to_i.abs
        end
    }.join(' ')
}

def solve (inputs, values)
    diff = []
    results = [values[0]]
    (inputs - 1).times.map{|i|
        d = values[i + 1] - values[i]
        if diff.any?
            if (d >= 0 && diff[i - 1] >= 0) or (d <= 0 && diff[i - 1] <= 0)
                results.push(-values[i + 1])
                diff.push -d
            else
                results.push(values[i + 1])
                diff.push d
            end
        else
            results.push(values[i + 1])
            diff.push d
        end
    }
    results.join(' ')
end

tests = gets.strip.to_i

tests.times{|i|
    inputs = gets.strip.to_i
    values = gets.strip.split(' ').map(&:to_i)
    puts solve(inputs, values)
}


Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it.After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies.Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies).You have to answer $$$q$$$ independent queries.Let's see the following example: $$$[1, 3, 4]$$$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob — then Alice has $$$4$$$ candies, and Bob has $$$4$$$ candies.Another example is $$$[1, 10, 100]$$$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $$$54$$$ candies, and Alice takes $$$46$$$ candies. Now Bob has $$$55$$$ candies, and Alice has $$$56$$$ candies, so she has to discard one candy — and after that, she has $$$55$$$ candies too.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains three integers $$$a, b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^{16}$$$) — the number of candies in the first, second and third piles correspondingly.

Print $$$q$$$ lines. The $$$i$$$-th line should contain the answer for the $$$i$$$-th query — the maximum number of candies Alice can have after the division, if both Alice and Bob act optimally (of course, Bob will have the same number of candies).

q = gets.to_i
q.times do
  a = gets.split.map(&:to_i)
  p a.inject(:+)/2
end

#!/usr/bin/env ruby

q = STDIN.gets.to_i

def calc(x)
  x.split(' ').map(&:to_i).inject(:+) / 2
end
q.times { puts calc(STDIN.gets.chomp) }

#!/usr/bin/env ruby

q = STDIN.gets.to_i
xs = q.times.map{STDIN.gets.chomp}
def calc(x)
  x.split(' ').map(&:to_i).inject(:+) / 2
end

res = xs.map do |x|
  calc(x)
end

puts res

q = gets.to_i
q.times do
  a, b, c = gets.split.map(&:to_i)
  puts (a+b+c)/2
end

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

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
n.times {
    q = gets.split.map(&:to_i)
    s = q.reduce(:+)

    puts s >> 1
}

gets.to_i.times do
  a, b, c = gets.split.map(&:to_i)
  puts (a + b + c) / 2
end

times = gets.chomp
ary = []
answ = []

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

ary.each do |ele|
    a = ele.delete_at(ele.index(ele.min))
    b = ele.delete_at(ele.index(ele.min))
    max = ele.last

    if a == b && b == max
        answ << (a+b+max)/2
        next
    end

    tmp = b-a

    if tmp > 0
        t_shr = max - tmp
        if t_shr%2 == 0
            shr = t_shr/2
        else
            shr = (t_shr-1)/2
        end
        answ << shr+tmp+[a,b].min
    elsif tmp == 0
        if max%2 == 0
            a = a + (max/2)
        else
            a = a + ((max-1)/2)
        end
        answ << a
    end
end

answ.each do |ele|
    puts "#{ele}\n"
end

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

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

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
q = gi
ans = []
q.times do
  a, b, c = gsmi
  ans << (a+b+c)/2
end
puts ans

1.upto(gets.to_i) do
  puts gets.split(' ').map(&:to_i).inject(&:+).div(2)
end


Shubham has a binary string $$$s$$$. A binary string is a string containing only characters "0" and "1".He can perform the following operation on the string any amount of times:   Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. A string is called good if it does not contain "010" or "101" as a subsequence  — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.

The first line of the input contains a single integer $$$t$$$ $$$(1\le t \le 100)$$$ — the number of test cases. Each of the next $$$t$$$ lines contains a binary string $$$s$$$ $$$(1 \le |s| \le 1000)$$$.

For every string, output the minimum number of operations required to make it good.

NoteIn test cases $$$1$$$, $$$2$$$, $$$5$$$, $$$6$$$ no operations are required since they are already good strings.For the $$$3$$$rd test case: "001" can be achieved by flipping the first character  — and is one of the possible ways to get a good string.For the $$$4$$$th test case: "000" can be achieved by flipping the second character  — and is one of the possible ways to get a good string.For the $$$7$$$th test case: "000000" can be achieved by flipping the third and fourth characters  — and is one of the possible ways to get a good string.

def solve(num)
  one_count = 0
  zero_count = 0
  ones_first = []
  zeroes_first = []

  num.each_char.with_index do |char, i|
    one_count += 1 if char == "1"
    zero_count += 1 if char == "0"
    ones_first[i] = zero_count
    zeroes_first[i] = one_count
  end

  i = num.length - 1
  ones_last = []
  ones_last[i] = 0
  zeroes_last = []
  zeroes_last[i] = 0
  min = Float::INFINITY

  while i > 0
    zeroes_last[i - 1] = zeroes_last[i] + zeroes_first[i] - zeroes_first[i-1]
    ones_last[i - 1] = ones_last[i] + ones_first[i] - ones_first[i-1]
    min = [min, zeroes_first[i] + ones_last[i], ones_first[i] + zeroes_last[i]].min
    i -= 1
  end

  [min, zeroes_first[0] + ones_last[0], ones_first[0] + zeroes_last[0]].min
end

amount = gets.chomp.to_i
amount.times do
  input = gets.chomp
  puts solve(input)
end

def solve(num)
  count = 0
  zeroes_first =  num.each_char.map do |char|
    count += 1 if char == "1"
    count
  end
  count = 0
  i = num.length - 1
  ones_last = []
  ones_last[i] = 0

  while i > 0
    count += 1 if num[i] == "0"
    ones_last[i - 1] = count
    i -= 1
  end
  count = 0
  ones_first =  num.each_char.map do |char|
    count += 1 if char == "0"
    count
  end
  count = 0
  i = num.length - 1
  zeroes_last = []
  zeroes_last[i] = 0
  while i > 0
    count += 1 if num[i] == "1"
    zeroes_last[i - 1] = count
    i -= 1
  end

  i = 0
  min = Float::INFINITY
  while i < num.length
    min = [min, zeroes_first[i] + ones_last[i], ones_first[i] + zeroes_last[i]].min
    i += 1
  end
  min
end

amount = gets.chomp.to_i
amount.times do
  input = gets.chomp
  puts solve(input)
end

# coding: utf-8

n = gets.to_i
n.times {
    s = gets.chomp.split(//).map(&:to_i)
    total = s.length
    ones = s.count(1)
    zeroes = s.count(0)
    # 0->1과, 1->0으로 모두 뒤집는 경우에 대한 기본해(이게 최소일 수도 있음)
    min = [ones, zeroes].min
    flip_ones, flip_zeroes = 0, 0

    for i in s
        if i == 0
            flip_zeroes += 1
            zeroes -= 1
        else
            flip_ones += 1
            ones -= 1
        end
        # 자기 자리를 계속 바꿔가며 나아간다
        # 0으로 나아갈 경우-> 뒷부분을 전부 1로 만들기 위해 바꿔야할 0의 수
        # 1로 나아갈 경우 -> 뒷부분을 전부 0으로 만들기 위해 바꿔야할 1의 수
        # 항상 미니멈을 유지하자
        # dp 응용 같음
        min = [min, flip_zeroes + ones, flip_ones + zeroes].min
    end
    puts min
}

gets.to_i.times do
    s = gets.chomp
    ones = s.each_char.inject([]) do |arr, c|
        arr.push arr[-1] || 0
        arr[-1] += 1 if c == '1'
        arr
    end
    all = [ones[-1], s.length - ones[-1]].min
    min = s.length.times.inject(all) do |min, i|
        right_zero = s.length - (i + 1) - (ones[-1] - ones[i])
        left_zero = i + 1 - ones[i]
        right_one = ones[-1] - ones[i]
        min = [min, ones[i] + right_zero, left_zero + right_one].min
    end
    puts min
end

# coding: utf-8

n = gets.to_i
n.times {
    s = gets.chomp.split(//).map(&:to_i)
    i = 0
    len = s.length
    flipped = 0
    # 010 -> remove 1's
    # 101 -> removes 0's
    while i < len-1
        base = 0
        flip = 1
        if s[i] == 0
            base = 0
            flip = 1
        else
            base = 1
            flip = 0
        end

        p1 = s[i..-1].index(flip)
        if p1 != nil
            p1 += i #compensation
            p2 = s[p1..-1].index(base)
            if p2 != nil
                p2 += p1 # compensation
                j = p1
                while s[j] == flip
                    s[j] = base
                    j += 1
                    flipped += 1
                end
                i = p2
                next
            end
        end

        i += 1
    end
    puts flipped
}

# coding: utf-8

n = gets.to_i
n.times {
    s = gets.split(//).map(&:to_i)
    i = 0
    len = s.length
    flipped = 0
    # 010 -> remove 1's
    # 101 -> removes 0's
    while i < len-1
        base = 0
        flip = 1
        if s[i] == 0
            base = 0
            flip = 1
        else
            base = 1
            flip = 0
        end

        p1 = s[i..-1].index(flip)
        if p1 != nil
            p1 += i #compensation
            p2 = s[p1..-1].index(base)
            if p2 != nil
                p2 += p1 # compensation
                j = p1
                while s[j] == flip
                    s[j] = base
                    j += 1
                    flipped += 1
                end
                i = p2
                next
            end
        end

        i += 1
    end
    puts flipped
}


When little Petya grew up and entered the university, he started to take part in АСМ contests. Later he realized that he doesn't like how the АСМ contests are organised: the team could only have three members (and he couldn't take all his friends to the competitions and distribute the tasks between the team members efficiently), so he decided to organize his own contests PFAST Inc. — Petr and Friends Are Solving Tasks Corporation. PFAST Inc. rules allow a team to have unlimited number of members.To make this format of contests popular he organised his own tournament. To create the team he will prepare for the contest organised by the PFAST Inc. rules, he chose several volunteers (up to 16 people) and decided to compile a team from them. Petya understands perfectly that if a team has two people that don't get on well, then the team will perform poorly. Put together a team with as many players as possible given that all players should get on well with each other.

The first line contains two integer numbers n (1 ≤ n ≤ 16) — the number of volunteers, and m () — the number of pairs that do not get on. Next n lines contain the volunteers' names (each name is a non-empty string consisting of no more than 10 uppercase and/or lowercase Latin letters). Next m lines contain two names — the names of the volunteers who do not get on. The names in pair are separated with a single space. Each pair of volunteers who do not get on occurs exactly once. The strings are case-sensitive. All n names are distinct.

The first output line should contain the single number k — the number of people in the sought team. Next k lines should contain the names of the sought team's participants in the lexicographical order. If there are several variants to solve the problem, print any of them. Petya might not be a member of the sought team.

n, m = gets.split.map &:to_i
p = []
$e = Array.new(n,0)

n.times {
  name = gets.chomp
  p << name
}
m.times {
  p0, p1 = gets.chomp.split
  i = p.index p0
  j = p.index p1
  $e[i] = $e[i] + (1<< j)
  $e[j] = $e[j] + (1<< i)
}

$max = []
def f(mems, mask, i, n)
  $max = mems.dup if mems.length > $max.length
  i.upto(n-1) {|j|
    if ($e[j] & mask) == 0
      mems << j
      f(mems, mask + (1<< j), j+1, n)
      mems.pop
    end
  }
end
f([], 0, 0, n)
puts $max.length
$max.map {|i| p[i] }.sort.each { |p| puts p}

def ones(a)
	c = 0
	while a > 0
		c += a % 2
		a /= 2
	end
	c
end

n,m  = gets.split(" ").map(&:to_i)
arr = []
n.times do
	arr << gets.chomp
end
enemy = []

m.times do
	a,b = gets.chomp.split(" ")
	val = 0
	val |= 1 << arr.index(a)
	val |= 1 << arr.index(b)
	enemy << val
end

# puts "here #{arr}"
best = 0

(0..(2**n)).each do |i|
	ans = true
	enemy.each do |en|
		if (en & i) == en
			ans = false
			# puts "ere"
		end
		# puts "fdf"
	end
	# puts "ere"
	if ans && (ones(i) > ones(best))
		best = i
	end
	# puts "dsafds"
end
# puts "dasf"
puts ones(best)
list  = []
# puts "#{arr}"
# puts "#{best.to_s(2).rjust(n,'0')}"
best.to_s(2).rjust(n,'0').each_char.with_index do |c,i|
	if c == '1'
		list << arr[n-i - 1]
	end
end
puts list.sort.join("\n")

#!/usr/bin/env ruby

def main
  n, m = STDIN.gets.split.map!{|x| x.to_i}
  names = []
  n.times {
    name = STDIN.gets.rstrip
    names.push(name)
  }

  ng = (0...n).map {Array.new(n)}
  m.times {
    a, b = STDIN.gets.split
    a = names.find_index(a)
    b = names.find_index(b)
    ng[a][b] = ng[b][a] = true
  }

  ans = 0
   (1 << n).times {|set|
    if  ans.to_s(2).count('1') >= set.to_s(2).count('1')
      next
    end

    ok = true
    n.times do |i| if (set >> i & 1) != 0
        i.times do |j| if (set >> j & 1) != 0
            if ng[i][j]
              ok = false
            end
          end
        end
      end
    end
    if ok
      ans = set
    end
  }

  puts ans.to_s(2).count('1')
  ans_names = []
  n.times {|i|
    if (ans >> i & 1) == 1
      ans_names.push(names[i])
    end
  }
  ans_names.sort!.each do |x|
    puts x
  end

end

if __FILE__ == $0
  main
end

n, m = gets.split.map &:to_i
p = []
$e = []
n.times { $e << Array.new(n, false) }

n.times {
  name = gets.chomp
  p << name
}
m.times {
  p0, p1 = gets.split
  i = p.index p0
  j = p.index p1
  $e[i][j] = $e[j][i] = true
}

$max = []
def f(mems, i, n)
  if i == n
    $max = mems.dup if mems.length > $max.length
  else
    i.upto(n-1) {|j|
      if not mems.any? { |k| $e[j][k] }
        mems << j
        f(mems, j+1, n)
        mems.pop
      end
    }
  end
end
f([], 0, n)
puts $max.length
puts $max.map { |i| p[i]}.sort

n, m = gets.split.map &:to_i
p = []
$e = Array.new(n,0)

n.times {
  name = gets.chomp
  p << name
}
m.times {
  p0, p1 = gets.chomp.split
  i = p.index p0
  j = p.index p1
  $e[i] = $e[i] + (1<< j)
  $e[j] = $e[j] + (1<< i)
}

$max = []
def f(mems, mask, i, n)
  if i == n
    $max = mems.dup if mems.length > $max.length
  else
    i.upto(n-1) {|j|
      if ($e[j] & mask) == 0
        mems << j
        f(mems, mask + (1<< j), j+1, n)
        mems.pop
      end
    }
  end
end
f([], 0, 0, n)
puts $max.length
$max.map { |i| p[i]}.sort.each { |p| puts p}

n, m = gets.split.map &:to_i
p = []
$e = Array.new(n,0)

n.times {
  name = gets.chomp
  p << name
}
m.times {
  p0, p1 = gets.chomp.split
  i = p.index p0
  j = p.index p1
  $e[i] = $e[i] + (1<< j)
  $e[j] = $e[j] + (1<< i)
}

$max = []
def f(mems, mask, i, n)
  if i == n
    $max = mems.dup if mems.length > $max.length
  else
    i.upto(n-1) {|j|
      if ($e[j] & mask) == 0
        mems << j
        f(mems, mask + (1<< j), j+1, n)
        mems.pop
      end
    }
  end
end
f([], 0, 0, n)
puts $max.length
puts $max.map { |i| p[i]}.sort

n, m = gets.split.map &:to_i
p = []
$e = Array.new(n,0)

n.times {
  name = gets.chomp
  p << name
}
m.times {
  p0, p1 = gets.chomp.split
  i = p.index p0
  j = p.index p1
  $e[i] = $e[i] + (1<< j)
  $e[j] = $e[j] + (1<< i)
}

$max = []
def f(mems, mask, i, n)
  if i == n
    $max = mems.dup if mems.length > $max.length
  else
    i.upto(n-1) {|j|
      if ($e[j] & mask) == 0
        mems << j
        f(mems, mask + (1<< j), j+1, n)
        mems.pop
      end
    }
  end
end
f([], 0, 0, n)
puts $max.length
$max.map {|i| p[i] }.sort_by(&:downcase).each { |p| puts p}

n,m  = gets.split(" ").map(&:to_i)
arr = []
n.times do
	arr << gets.chomp
end
enemy = {}

m.times do
	a,b = gets.chomp.split(" ")
	enemy[a] ||= []
	enemy[b] ||= []
	enemy[a] << b
	enemy[b] << a
end
# ans = arr.dup
# puts "#{enemy}"
# puts "here #{enemy.key(:Pasha)}"
enemy_vals = enemy.sort_by{|x,v| -v.length}
# puts "#{}"
enemy_vals.each do |v|
	k = v[0]
	val = enemy[k]
	# puts "arr #{arr}"
	if val.length > 0
		# puts "#{enemy}"
		arr -= [k]
		val.each{|x| enemy[x] -= [k] }
	end
end
puts arr.length
puts "#{arr.sort.join("\n")}"

n,m  = gets.split(" ").map(&:to_i)
arr = []
n.times do
	arr << gets.chomp
end
enemy = {}

m.times do
	a,b = gets.chomp.split(" ")
	enemy[a] ||= []
	enemy[b] ||= []
	enemy[a] << b
	enemy[b] << a
end
# ans = arr.dup
enemy.each do |k,v|
	if v.length > 0
		arr -= [k]
		v.each{|x| enemy[x] -= [k] }
	end
end
puts arr.length
puts "#{arr.sort.join("\n")}"

def ones(a)
	c = 0
	while a > 0
		c += a % 2
		a /= 2
	end
	c
end

n,m  = gets.split(" ").map(&:to_i)
arr = []
n.times do
	arr << gets.chomp
end
enemy = []

m.times do
	a,b = gets.chomp.split(" ")
	val = 0
	val |= 1 << arr.index(a)
	val |= 1 << arr.index(b)
	enemy << val
end

# puts "here #{arr}"
best = 0

(0..(2**n)).each do |i|
	ans = true
	enemy.each do |en|
		if (en & i) == en
			ans = false
			# puts "ere"
		end
		# puts "fdf"
	end
	# puts "ere"
	if ans && (ones(i) > ones(best))
		best = i
	end
	# puts "dsafds"
end
# puts "dasf"
puts ones(best)
list  = []
# puts "#{best}"
best.to_s(2).each_char.with_index do |c,i|
	if c == '1'
		list << arr[i]
	end
end
puts list.sort.join("\n")

def ones(a)
	c = 0
	while a > 0
		c += a % 2
		a /= 2
	end
	c
end

n,m  = gets.split(" ").map(&:to_i)
arr = []
n.times do
	arr << gets.chomp
end
enemy = []

m.times do
	a,b = gets.chomp.split(" ")
	val = 0
	val |= 1 << arr.index(a)
	val |= 1 << arr.index(b)
	enemy << val
end

# puts "here #{arr}"
best = 0

(0..(2**n)).each do |i|
	ans = true
	enemy.each do |en|
		if (en & i) == en
			ans = false
			# puts "ere"
		end
		# puts "fdf"
	end
	# puts "ere"
	if ans && (ones(i) > ones(best))
		best = i
	end
	# puts "dsafds"
end
# puts "dasf"
puts ones(best)
list  = []
# puts "#{best}"
best.to_s(2).each_char.with_index do |c,i|
	if c == '1'
		list << arr[n-i - 1]
	end
end
puts list.sort.join("\n")

#!/usr/bin/env ruby

def main
  n, m = STDIN.gets.split.map!{|x| x.to_i}
  names = []
  n.times {
    name = STDIN.gets.rstrip
    names.push(name)
  }

  ng = (0...n).map {Array.new(n)}
  m.times {
    a, b = STDIN.gets.split
    a = names.find_index(a)
    b = names.find_index(b)
    ng[a][b] = ng[b][a] = true
  }

  ans = 0
  (1 << n).times {|set|
    if  ans.to_s(2).count('1') >= set.to_s(2).count('1')
      next
    end

    ok = true
    n.times do |i|
      i.times do |j|
        if (set >> i & 1) != 0 && (set >> j & 1) != 0
          if ng[i][j]
            ok = false
          end
        end
      end
    end
    if ok
      ans = set
    end
  }
  puts ans.to_s(2).count('1')
  n.times {|i|
    if (ans >> i & 1) == 1
      puts names[i]
    end
  }

end

if __FILE__ == $0
  main
  STDIN.gets;
end


Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first.Consider the 2D plane. There is a token which is initially at $$$(0,0)$$$. In one move a player must increase either the $$$x$$$ coordinate or the $$$y$$$ coordinate of the token by exactly $$$k$$$. In doing so, the player must ensure that the token stays within a (Euclidean) distance $$$d$$$ from $$$(0,0)$$$.In other words, if after a move the coordinates of the token are $$$(p,q)$$$, then $$$p^2 + q^2 \leq d^2$$$ must hold.The game ends when a player is unable to make a move. It can be shown that the game will end in a finite number of moves. If both players play optimally, determine who will win.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The only line of each test case contains two space separated integers $$$d$$$ ($$$1 \leq d \leq 10^5$$$) and $$$k$$$ ($$$1 \leq k \leq d$$$).

For each test case, if Ashish wins the game, print "Ashish", otherwise print "Utkarsh" (without the quotes).

NoteIn the first test case, one possible sequence of moves can be$$$(0, 0) \xrightarrow{\text{Ashish }} (0, 1) \xrightarrow{\text{Utkarsh }} (0, 2)$$$.Ashish has no moves left, so Utkarsh wins.


One fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the  desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n.But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.

The first input line contains a single even integer n (4 ≤ n ≤ 100) — the number of students in the class. The second line contains exactly n capital English letters "L" and "R". If the i-th letter at the second line equals "L", then the student number i is a lefthander, otherwise he is a righthander.

Print  integer pairs, one pair per line. In the i-th line print the numbers of students that will sit at the i-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.

$stdin = File.new( "input.txt", 'r' )
$stdout = File.new( "output.txt", 'w' )

n = gets.strip.to_i
stds = gets.strip.split("")
mid = n / 2
i = 0
(mid...n).each do |j|
    if stds[i] == 'R' && stds[j] == 'L'
        puts "#{j + 1} #{i + 1}"
    else
        puts "#{i + 1} #{j + 1}"
    end
    i += 1
end

n = 0
arr = []
open("input.txt") {|f|
  n = f.gets.to_i
  arr = f.gets.to_s.chomp.split(//)
}
File.open("output.txt", "w"){|f|
(n/2).times do |i|
  if arr[i] == "R" && arr[i+n/2] == "L"
    f.write "#{i+n/2+1} #{i+1}\n"
  else
    f.write "#{i+1} #{i+n/2+1}\n"
  end
end
}

$stdin=open("input.txt")
$stdout=open("output.txt","w")
n=gets.to_i/2
a=gets
i=0
n.times do
    k=a[i]=='L'?0:1
    puts [i+1+n*k, i+1+n*(1-k)]*' '
    i+=1
end

$stdin=open("input.txt")
$stdout=open("output.txt","w")
n=gets.to_i/2
a=gets
i=0
n.times do
    if a[i]=='L' then
        puts [i+1,i+1+n]*' '
    else
        puts [i+1+n,i+1]*' '
    end
    i+=1
end

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
n=gets.to_i
s=gets
(n/2).times{|i|
	x,y=i,i+n/2
	x,y=y,x if s[x]=='R'&&s[y]=='L'
	puts [x+1,y+1]*' '
}

line = File.read("input.txt")
n,hand = line.split("\n")

n = n.to_i
res = []

arr = hand.split("")

nos = [*(0..n-1).step(2),*(1..n-1).step(2)]

nos.each_slice(2) do |a|
	o = arr[a[0]]
	e = arr[a[1]]
	odd_ind = a[0]
	even_ind = a[1]
	odd_ind,even_ind = even_ind,odd_ind if o != e && o != "R"
	res << [even_ind+1,odd_ind+1]
end
File.open("output.txt", 'w') { |file|
	res.each do |a|
		file.puts(a.join(" "))
	end
}

if ENV['USER'] != 'watashi'
  ARGV << 'input.txt'
  $> = open('output.txt', 'w')
end

n = gets.to_i / 2
m = gets
puts [*1..n].map{|i| (m[i-1] == 'L' ? [i, n+i] : [n+i, i]) * ' '} * "\n"

if ENV['USER'] != 'watashi'
  $stdin = open('input.txt')
  $> = open('output.txt', 'w')
end

n = gets.to_i / 2
m = gets
puts [*1..n].map{|i| (m[i-1] == 'L' ? [i, n+i] : [n+i, i]) * ' '} * "\n"

input = File.open("input.txt", "r")
output = File.open("output.txt", "w")

n = input.gets.to_i
lr = " "+input.gets.strip

for i in 1..n-2
  desk = Array.new(2)
  if lr[i] != "0"
    if lr[i] == "L"
	  desk[0] = i
	  desk[1] = n/2+i
	else
	  desk[0] = n/2+i
	  desk[1] = i
	end
	lr[i] = "0"
	lr[n/2+i] = "0"
	output.puts "#{desk[0]} #{desk[1]}"
  end
end

input.close
output.close

input = File.open("input.txt", "r")
output = File.open("output.txt", "w")

n = input.gets.to_i
lr = " "+input.gets.strip

for i in 1..n/2
  desk = Array.new(2)
  if lr[i] == "L"
	desk[0] = i
	desk[1] = n/2+i
  else
	desk[0] = n/2+i
	desk[1] = i
  end
  output.puts "#{desk[0]} #{desk[1]}"
end

input.close
output.close

$stdin=open("input.txt")
$stdout=open("output.txt","w")
n=gets.to_i
a=gets.chomp.split('').unshift(0)
for i in 1..n/2
	puts "#{i} #{i+n/2}" if a[i]=='L'
	puts "#{i+n/2} #{i}" if a[i]=='R'
end

n = gets.to_i
arr = gets.to_s.chomp.split(//)
(n/2).times do |i|
  if arr[i] == "R" && arr[i+n/2] == "L"
    puts "#{i+n/2+1} #{i+1}"
  else
    puts "#{i+1} #{i+n/2+1}"
  end
end

n=0
a=[]
open("input.txt") do |f|
    n=f.gets.to_i
    a=f.gets.chomp.split('')
end

res=Array.new(n/2).map!{Array.new(2)}
l=r=0
a.each_with_index do |v,i|
    if v=='L' then
        if l<n/2 then
            res[l][0]=i+1
            l+=1
        else
            res[r][1]=i+1
            r+=1
        end
    else
        if r<n/2 then
            res[r][1]=i+1
            r+=1
        else
            res[l][0]=i+1
            l+=1
        end
    end
end
open("output.txt","w") do |f|
    res.each do |v|
        f.puts v*' '
    end
end

n=0
a=[]
open("input.txt") do |f|
    n=f.gets.to_i/2
    f.gets.chomp.split('').each_with_index do |v,i|
        a.push([v,i+1])
    end
end

a.sort!
res=Array.new(n).map!{Array.new(2)}
a.each_with_index do |v,i|
    res[i%n][i/n]=v[1]
end
open("output.txt","w") do |f|
    res.each do |v|
        f.puts v*' '
    end
end

n = gets.to_i
# res = []

# arr = gets.chomp.split("")

# nos = [*(0..n-1).step(2),*(1..n-1).step(2)]

# nos.each_slice(2) do |a|
# 	o = arr[a[0]]
# 	e = arr[a[1]]
# 	odd_ind = a[0]
# 	even_ind = a[1]
# 	odd_ind,even_ind = even_ind,odd_ind if o != e && o != "R"
# 	res << [even_ind+1,odd_ind+1]
# end
# res.each do |a|
# 	puts a.join(" ")
# end

# p ENV
var = %w(RUBY_COPYRIGHT RUBY_ENGINE RUBY_PLATFORM RUBY_REVISION RUBY_DESCRIPTION RUBY_PATCHLEVEL RUBY_RELEASE_DATE RUBY_VERSION)
var.map{|_| puts "#{_} = #{eval(_)}"}

if ENV['USER'] != 'watashi'
  $stdin = open('input.txt')
  $> = open('output.txt', 'w')
end

n = gets.to_i
m = gets.scan(/[LR]/).zip([*1..n]).sort
n /= 2
n.times do |i|
  puts "#{m[i][1]} #{m[n + i][1]}"
end


You work in the quality control department of technical support for a large company. Your job is to make sure all client issues have been resolved.Today you need to check a copy of a dialog between a client and a technical support manager. According to the rules of work, each message of the client must be followed by one or several messages, which are the answer of a support manager. However, sometimes clients ask questions so quickly that some of the manager's answers to old questions appear after the client has asked some new questions.Due to the privacy policy, the full text of messages is not available to you, only the order of messages is visible, as well as the type of each message: a customer question or a response from the technical support manager. It is guaranteed that the dialog begins with the question of the client.You have to determine, if this dialog may correspond to the rules of work described above, or the rules are certainly breached.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 500$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the total number of messages in the dialog. The second line of each test case consists of $$$n$$$ characters "Q" and "A", describing types of messages in the dialog in chronological order. Character "Q" denotes the message with client question, and character "A" — the message with technical support manager answer. It is guaranteed that the first character in the line equals to "Q".

For each test case print "Yes" (without quotes) if dialog may correspond to the rules of work, or "No" (without quotes) otherwise.

5

4

QQAA

4

QQAQ

3

QAA

1

Q

14

QAQQAQAAQQQAAA

NoteIn the first test case the two questions from the client are followed with two specialist's answers. So this dialog may correspond to the rules of work.In the second test case one of the first two questions was not answered.In the third test case the technical support manager sent two messaged as the answer to the only message of the client.

=begin

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

=end

t=gets.to_i

for i in 1..t
    n =gets.to_i
    s=gets.chomp
    a=0
    q=0
    feil=0
    for j in 1..n
        if s[n-j]=="A"
            a+=1
        else
            q+=1
        end
        if q>a
            puts "No"
            feil=1
            break
        end
    end
    if (feil==0)
        puts "Yes"
    end
end


We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".Given a string, you have to find two values:  the number of good substrings of even length;  the number of good substrings of odd length.

The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.

Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.

NoteIn example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.DefinitionsA substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.

a=gets.chomp
e=[0,0]
o=[0,0]
ea=oa=0
a.size.times{|i|
	t=a[i].ord-'a'.ord
	if i%2==0
		e[t]+=1
		ea+=o[t]
		oa+=e[t]
	else
		o[t]+=1
		ea+=e[t]
		oa+=o[t]
	end
}
puts "#{ea} #{oa}"


You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. Is it possible to arrange them on a circle so that each number is strictly greater than both its neighbors or strictly smaller than both its neighbors?In other words, check if there exists a rearrangement $$$b_1, b_2, \ldots, b_n$$$ of the integers $$$a_1, a_2, \ldots, a_n$$$ such that for each $$$i$$$ from $$$1$$$ to $$$n$$$ at least one of the following conditions holds: $$$b_{i-1} < b_i > b_{i+1}$$$ $$$b_{i-1} > b_i < b_{i+1}$$$To make sense of the previous formulas for $$$i=1$$$ and $$$i=n$$$, one shall define $$$b_0=b_n$$$ and $$$b_{n+1}=b_1$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 3\cdot 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 10^5$$$)  — the number of integers. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.

For each test case, if it is not possible to arrange the numbers on the circle satisfying the conditions from the statement, output $$$\texttt{NO}$$$. You can output each letter in any case. Otherwise, output $$$\texttt{YES}$$$. In the second line, output $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$, which are a rearrangement of $$$a_1, a_2, \ldots, a_n$$$ and satisfy the conditions from the statement. If there are multiple valid ways to arrange the numbers, you can output any of them.

NoteIt can be shown that there are no valid arrangements for the first and the third test cases.In the second test case, the arrangement $$$[1, 8, 4, 9]$$$ works. In this arrangement, $$$1$$$ and $$$4$$$ are both smaller than their neighbors, and $$$8, 9$$$ are larger.In the fourth test case, the arrangement $$$[1, 11, 1, 111, 1, 1111]$$$ works. In this arrangement, the three elements equal to $$$1$$$ are smaller than their neighbors, while all other elements are larger than their neighbors.

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  a.sort!
  m = (n+1)/2
  ans1 = a[0..(m-1)].reverse.rotate
  ans2 = a[m..(n-1)].rotate
  g = ans2.size
  g.times do
    if ans2[-1] == ans1[-1]
      ans2.rotate!
    else
      break
    end
  end
  ans = []
  #puts ans1.inspect
  #puts ans2.inspect
  0.upto(n-1) do |i|
    ans.push( (i%2==0) ? ans1.pop : ans2.pop)
  end
  #puts ans.inspect
  check = 0
  0.upto(n-1) do |i|
    if i % 2 == 0 then
      check += 1 if (ans[i]<ans[i-1]) and (ans[i]<ans[(i+1)%n])
    else
      check += 1 if (ans[i]>ans[i-1]) and (ans[i]>ans[(i+1)%n])
    end
  end
  if check == n then
    puts "YES"
    puts ans.join(" ")
  else
    puts "NO"
  end
end

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i).sort
  ys = (0..xs.size - 1).map { |i| xs[i % 2 == 0 ? i / 2 : (xs.size / 2 + i / 2)] }
  ok = (0..ys.size - 1).all? do |i|
    a, b, c = ys[i - 1], ys[i], ys[(i + 1) % ys.size]
    (a < b && b > c) || (a > b && b < c)
  end
  if ok
    puts "YES"
    puts ys.join(" ")
  else
    puts "NO"
  end
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  a.sort!
  ans = []
  0.upto(n-1) do |i|
    if i % 2 == 0 then
      ans.push(a[i/2])
    else
      ans.push(a[n-1-i/2])
    end
  end
  check = 0
  0.upto(n-1) do |i|
    if i % 2 == 0 then
      check += 1 if (ans[i]<ans[i-1]) and (ans[i]<ans[(i+1)%n])
    else
      check += 1 if (ans[i]>ans[i-1]) and (ans[i]>ans[(i+1)%n])
    end
  end
  if check == n then
    puts "YES"
    puts ans.join(" ")
  else
    puts "NO"
  end
end


Alica and Bob are playing a game.Initially they have a binary string $$$s$$$ consisting of only characters 0 and 1.Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string $$$s$$$ and delete them. For example, if $$$s = 1011001$$$ then the following moves are possible:   delete $$$s_1$$$ and $$$s_2$$$: $$$\textbf{10}11001 \rightarrow 11001$$$;  delete $$$s_2$$$ and $$$s_3$$$: $$$1\textbf{01}1001 \rightarrow 11001$$$;  delete $$$s_4$$$ and $$$s_5$$$: $$$101\textbf{10}01 \rightarrow 10101$$$;  delete $$$s_6$$$ and $$$s_7$$$: $$$10110\textbf{01} \rightarrow 10110$$$. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.

First line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Only line of each test case contains one string $$$s$$$ ($$$1 \le |s| \le 100$$$), consisting of only characters 0 and 1.

For each test case print answer in the single line. If Alice can win print DA (YES in Russian) in any register. Otherwise print NET (NO in Russian) in any register.

NoteIn the first test case after Alice's move string $$$s$$$ become empty and Bob can not make any move.In the second test case Alice can not make any move initially.In the third test case after Alice's move string $$$s$$$ turn into $$$01$$$. Then, after Bob's move string $$$s$$$ become empty and Alice can not make any move.

t = gets.to_i
t.times do
    s = gets.chomp.chars
    alice = true
    while s.size >= 2
        i = s.each_cons(2).find_index { |c| c[0] != c[1] }
        break unless i
        s.slice! i, 2
        alice = !alice
    end
    puts (alice ? "NET" : "DA")
end

def run
  s = gets.chomp
  a = s.split("").map(&:to_i)

  if a.size == 1
    puts "NET"
    return
  end

  c = 0

  while true
    idx = find_idx(a)
    if idx == -1
      if c % 2 == 1
        puts "DA"
        return
      else
        puts "NET"
        return
      end
    else
      c += 1
      a.slice!(idx, 2)
    end
  end
end

def find_idx(a)
  (0..(a.length - 2)).each do |idx|
    if a[idx] != a[idx + 1]
      return idx
    end
  end

  return -1
end

def main
  t = gets.chomp.to_i

  t.times do
    run
  end
end

main

n = gets.chomp.to_i
(0...n).each do
    s = gets.chomp.split("")
    #p s
    count = 1
    #while true
    i = 1
    100.times do
        if s[i] != s[i-1] && s.size >= 2
            s[i] = " "
            s[i-1] = " "
            count += 1
        # elsif
        #     i += 1
        #     count += 1
        end
        #p s
        if s.include?(" ")
            s.delete(" ")
            if i >= 1
            i -= 1
            end
        else
            i += 1
        end
        #p s
        ss = s.size

        #p count
        if s.count("1") == ss || s.count("0") == ss || s == []
            if count % 2 == 1
                puts "NET"
            elsif count % 2 == 0
                puts "DA"
            end
            break
        end
    end

end

n = gets.chomp.to_i
(0...n).each do
    s = gets.chomp.split("")
    #p s
    count = 1
    #while true
    i = 1
    250.times do
        if s[i] != s[i-1]
            s[i] = " "
            s[i-1] = " "
            count += 1
        # elsif
        #     i += 1
        #     count += 1
        end
        #p s
        if s.include?(" ")
            s.delete(" ")
            i = 1
        else
            i += 1
        end
        #p s
        ss = s.size
        #p i
        if s.count("1") == ss || s.count("0") == ss || s == []
            if count % 2 == 1
                puts "NET"
            elsif count % 2 == 0
                puts "DA"
            end
            break
        end
    end

end

n = gets.chomp.to_i
(0...n).each do
    s = gets.chomp.split("")
    #p s
    count = 1
    #while true
    i = 1
    200.times do
    #while
        if s[i] != s[i-1]
            s[i] = " "
            s[i-1] = " "
            count += 1
        # elsif
        #     i += 1
        #     count += 1
        end
        #p s
        if s.include?(" ")
            s.delete(" ")
            i = 1
        else
            i += 1
        end
        #p s
        ss = s.size
        #p i
        if s.count("1") == ss || s.count("0") == ss || s == []
            if count % 2 == 1
                puts "NET"
            elsif count % 2 == 0
                puts "DA"
            end
            break
        end
    end

end

n = gets.chomp.to_i
(0...n).each do
    s = gets.chomp.split("")
    #p s
    count = 1
    #while true
    i = 1
    100.times do
        if s[i] != s[i-1]
            s[i] = " "
            s[i-1] = " "
            count += 1
        # elsif
        #     i += 1
        #     count += 1
        end
        #p s
        if s.include?(" ")
            s.delete(" ")
            if i >= 1
            i -= 1
            end
        else
            i += 1
        end
        #p s
        ss = s.size

        #p i
        if s.count("1") == ss || s.count("0") == ss || s == []
            if count % 2 == 1
                puts "NET"
            elsif count % 2 == 0
                puts "DA"
            end
            break
        end
    end

end

n = gets.chomp.to_i
(0...n).each do
    s = gets.chomp.split("")
    #p s
    count = 1
    #while true
    i = 1
    110.times do
        if s[i] != s[i-1]
            s[i] = " "
            s[i-1] = " "
            count += 1
        # elsif
        #     i += 1
        #     count += 1
        end
        #p s
        if s.include?(" ")
            s.delete(" ")
            i = 1
        else
            i += 1
        end
        #p s
        ss = s.size
        #p i
        if s.count("1") == ss || s.count("0") == ss || s == []
            if count % 2 == 1
                puts "NET"
            elsif count % 2 == 0
                puts "DA"
            end
            break
        end
    end
end

n = gets.chomp.to_i
(0...n).each do
    s = gets.chomp.split("")
    #p s
    count = 1
    #while true
    i = 1
    100.times do
        if s[i] != s[i-1]
            s[i] = " "
            s[i-1] = " "
            count += 1
        # elsif
        #     i += 1
        #     count += 1
        end
        #p s
        if s.include?(" ")
            s.delete(" ")
            if i >= 1
            i -= 1
            end
        else
            i += 1
        end
        #p s
        ss = s.size

        #p count
        if s.count("1") == ss || s.count("0") == ss || s == []
            if count % 2 == 1
                puts "NET"
            elsif count % 2 == 0
                puts "DA"
            end
            break
        end
    end

end


You are given an array $$$a_1, a_2, \dots, a_n$$$ where all $$$a_i$$$ are integers and greater than $$$0$$$. In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$). If $$$gcd(a_i, a_j)$$$ is equal to the minimum element of the whole array $$$a$$$, you can swap $$$a_i$$$ and $$$a_j$$$. $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Now you'd like to make $$$a$$$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this. An array $$$a$$$ is non-decreasing if and only if $$$a_1 \le a_2 \le \ldots \le a_n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.  The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of array $$$a$$$.  The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \ldots a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array itself.  It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, output "YES" if it is possible to make the array $$$a$$$ non-decreasing using the described operation, or "NO" if it is impossible to do so.

Note In the first and third sample, the array is already non-decreasing. In the second sample, we can swap $$$a_1$$$ and $$$a_3$$$ first, and swap $$$a_1$$$ and $$$a_5$$$ second to make the array non-decreasing. In the forth sample, we cannot the array non-decreasing using the operation.

def gcd(x,y)
    return y==0?x:gcd(y,x%y)
end

t =gets.to_i

t.times do
    n = gets.to_i
    a = gets.split.map(&:to_i)
    b = a.sort
    ma = a.min
    res ="YES"
    for i in 0...n do
        if gcd(a[i], ma) != ma and b[i] != a[i] then
            res ="NO"
        end
    end
    puts res
end

def solve
  _ = gets
  a = gets.strip.split(' ').map(&:to_i)
  mn = a.min
  slc = a.select { |e| e % mn == 0 }.sort
  p = 0
  a.each_with_index { |e, i|
    if e % mn == 0
      a[i] = slc[p]
      p += 1
    end
  }
  if a == a.sort
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times { solve }

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  b = a.sort
  min = b[0]
  ok = true
  n.times do |i|
    if a[i] != b[i] && a[i].gcd(min) != min
      ok = false
    end
  end
  if ok
    ans << "YES"
  else
    ans << "NO"
  end
end
ans.each do |x|
  puts x
end

require 'set'

def taskA
  a, b = gets.chomp.split(" ").map(&:to_i)
  puts b > a ? b - a : (a + b) % 2
end

def taskB
  a, b, c = gets.chomp.split(" ").map(&:to_i)
  z, x, y = gets.chomp.split(" ").map(&:to_i)
  minCX = [c, x].min
  puts (minCX - [0, y - a - c + minCX].max)*2
end

def taskC
  n = gets.chomp.split(" ").map(&:to_i)
  tab = gets.chomp.split(" ").map(&:to_i)
  min = tab.min
  good = tab.select{ |a| a % min == 0 }.sort
  good.push(1100000000)
  # puts good.join(" ")
  iter = 0
  prev = min
  tab.map do |a|
    #  puts "now #{a} iter = #{iter}"
    if a % min == 0
      if prev > good[iter]
        puts "NO"
        return
      end
      prev = good[iter]
      iter+=1
    elsif prev > a
      puts "NO"
      return
    else
      prev = a
    end
  end
  puts "YES"
end

t = gets.chomp.to_i
while (t-=1) >= 0
  taskC
end

require 'set'

def taskA
  a, b = gets.chomp.split(" ").map(&:to_i)
  puts b > a ? b - a : (a + b) % 2
end

def taskB
  a, b, c = gets.chomp.split(" ").map(&:to_i)
  z, x, y = gets.chomp.split(" ").map(&:to_i)
  minCX = [c, x].min
  puts (minCX - [0, y - a - c + minCX].max)*2
end

def taskC
  n = gets.chomp.split(" ").map(&:to_i)
  tab = gets.chomp.split(" ").map(&:to_i)
  min = tab.min
  good = tab.select{ |a| a % min == 0 }.sort
  good.push(1100000000)
  # puts good.join(" ")
  iter = 0
  tab.map do |a|
    #  puts "now #{a} iter = #{iter}"
    if a % min == 0
      iter+=1
    elsif good[iter] < a
      puts "NO"
      return
    end
  end
  puts "YES"
end

t = gets.chomp.to_i
while (t-=1) >= 0
  taskC
end

require 'set'

def taskA
  a, b = gets.chomp.split(" ").map(&:to_i)
  puts b > a ? b - a : (a + b) % 2
end

def taskB
  a, b, c = gets.chomp.split(" ").map(&:to_i)
  z, x, y = gets.chomp.split(" ").map(&:to_i)
  minCX = [c, x].min
  puts (minCX - [0, y - a - c + minCX].max)*2
end

def taskC
  n = gets.chomp.split(" ").map(&:to_i)
  tab = gets.chomp.split(" ").map(&:to_i)
  min = tab.min
  good = tab.select{ |a| a % min == 0 }.sort
  good.push(10000000)
  # puts good.join(" ")
  iter = 0
  tab.map do |a|
    #  puts "now #{a} iter = #{iter}"
    if a % min == 0
      iter+=1
    elsif good[iter] < a
      puts "NO"
      return
    end
  end
  puts "YES"
end

t = gets.chomp.to_i
while (t-=1) >= 0
  taskC
end