This is an interactive problem.Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and  sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions.

At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions.

To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or  - 1. The hacked solution will not have direct access to the sequence ai.

NoteInput-output in statements illustrates example interaction.In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2In the second sample the selection sequence is 1, 2, 3, 2, 1, 0.

def getnum(i)
    puts "? #{i+1}"
    $stdout.flush
    $info[i] = gets.to_i
end

N = gets.to_i
$info = Array.new(N+1)

getnum(0)
getnum(N/2)
$info[N] = $info[0]

diff = ($info[0] - $info[N/2]).abs
if diff > N/2 || diff % 2 == 1
    puts "! -1"
    exit
end
if diff == 0
    puts "! 1"
    exit
end

llb = 0
lub = N/2
rlb = N/2
rub = N

loop do
    left = (llb+lub)/2
    right = (rlb+rub)/2
    getnum(left)
    getnum(right)
    if $info[left] == $info[right]
        puts "! #{left+1}"
        exit
    end
    if ($info[llb] > $info[rlb]) == ($info[left] > $info[right])
        llb = left
        rlb = right
    else
        lub = left
        rub = right
    end
end


Ilya lives in a beautiful city of Chordalsk.There are $$$n$$$ houses on the street Ilya lives, they are numerated from $$$1$$$ to $$$n$$$ from left to right; the distance between every two neighboring houses is equal to $$$1$$$ unit. The neighboring houses are $$$1$$$ and $$$2$$$, $$$2$$$ and $$$3$$$, ..., $$$n-1$$$ and $$$n$$$. The houses $$$n$$$ and $$$1$$$ are not neighboring.The houses are colored in colors $$$c_1, c_2, \ldots, c_n$$$ so that the $$$i$$$-th house is colored in the color $$$c_i$$$. Everyone knows that Chordalsk is not boring, so there are at least two houses colored in different colors.Ilya wants to select two houses $$$i$$$ and $$$j$$$ so that $$$1 \leq i < j \leq n$$$, and they have different colors: $$$c_i \neq c_j$$$. He will then walk from the house $$$i$$$ to the house $$$j$$$ the distance of $$$(j-i)$$$ units.Ilya loves long walks, so he wants to choose the houses so that the distance between them is the maximum possible.Help Ilya, find this maximum possible distance.

The first line contains a single integer $$$n$$$ ($$$3 \leq n \leq 300\,000$$$) — the number of cities on the street. The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq n$$$) — the colors of the houses. It is guaranteed that there is at least one pair of indices $$$i$$$ and $$$j$$$ so that $$$1 \leq i < j \leq n$$$ and $$$c_i \neq c_j$$$.

Print a single integer — the maximum possible distance Ilya can walk.

NoteIn the first example the optimal way is to walk from the first house to the last one, where Ilya can walk the distance of $$$5-1 = 4$$$ units.In the second example the optimal way is to either walk from the first house to the second or from the second to the third. Both these ways have the distance of $$$1$$$ unit.In the third example the optimal way is to walk from the third house to the last one, where Ilya can walk the distance of $$$7-3 = 4$$$ units.

N = gets.to_i
C = gets.split.map(&:to_i)

d1 = C.rindex { |c| C[0] != c }
d2 = N - C.index { |c| C[-1] != c } - 1

puts [d1, d2].max

n = gets.to_i
c = gets.split.map(&:to_i)
ans = 0
for i in 1..n-1
    if c[0] != c[i]
        ans = i
    end
end
(n-2).downto(0) do |i|
    if c[-1] != c[i] && ans < n-1-i
        ans = n-1-i
    end
end
puts ans

n = gets.to_i
c = gets.split.map(&:to_i)
l = []
r = []
n.times do |i|
  break if l.length == 2
  if l.length == 0
    l << [c[i],i]
  elsif l.length == 1 && l[0][0] != c[i]
    l << [c[i],i]
  end
end
n.times do |i|
  break if r.length == 2
  if r.length == 0
    r << [c[-i-1],n-i-1]
  elsif r.length == 1 && r[0][0] != c[-i-1]
    r << [c[-i-1],n-i-1]
  end
end
ans = 0
if l[0][0] != r[0][0]
  ans = r[0][1] - l[0][1]
else
  ans = [r[1][1] - l[0][1],r[0][1] - l[1][1]].max
end
p ans


Moscow is hosting a major international conference, which is attended by n scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from 1 to 109.In the evening after the conference, all n scientists decided to go to the cinema. There are m movies in the cinema they came to. Each of the movies is characterized by two distinct numbers — the index of audio language and the index of subtitles language. The scientist, who came to the movie, will be very pleased if he knows the audio language of the movie, will be almost satisfied if he knows the language of subtitles and will be not satisfied if he does not know neither one nor the other (note that the audio language and the subtitles language for each movie are always different). Scientists decided to go together to the same movie. You have to help them choose the movie, such that the number of very pleased scientists is maximum possible. If there are several such movies, select among them one that will maximize the number of almost satisfied scientists.

The first line of the input contains a positive integer n (1 ≤ n ≤ 200 000) — the number of scientists. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the index of a language, which the i-th scientist knows. The third line contains a positive integer m (1 ≤ m ≤ 200 000) — the number of movies in the cinema.  The fourth line contains m positive integers b1, b2, ..., bm (1 ≤ bj ≤ 109), where bj is the index of the audio language of the j-th movie. The fifth line contains m positive integers c1, c2, ..., cm (1 ≤ cj ≤ 109), where cj is the index of subtitles language of the j-th movie. It is guaranteed that audio languages and subtitles language are different for each movie, that is bj ≠ cj.

Print the single integer — the index of a movie to which scientists should go. After viewing this movie the number of very pleased scientists should be maximum possible. If in the cinema there are several such movies, you need to choose among them one, after viewing which there will be the maximum possible number of almost satisfied scientists.  If there are several possible answers print any of them.

NoteIn the first sample, scientists must go to the movie with the index 2, as in such case the 1-th and the 3-rd scientists will be very pleased and the 2-nd scientist will be almost satisfied.In the second test case scientists can go either to the movie with the index 1 or the index 3. After viewing any of these movies exactly two scientists will be very pleased and all the others will be not satisfied.

#!/usr/bin/ruby
class Counter < Hash
	def initialize(a=[])
		super
		self.default=0
		a.each{|e|self[e]+=1}
	end
	def self.[](*a)
		new(a)
	end
end
def Counter(a=[]) Counter.new(a) end

n=gets.to_i
b=Counter(gets.split.map(&:to_i))
m=gets.to_i
p gets.split.map(&:to_i).zip(gets.split.map(&:to_i)).each_with_index.map{|(k,l),z|[b[k],b[l],z+1]}.max[2]

n = readline.to_i
arr = readline.split(' ').collect(&:to_i)
map = Hash.new(0)
arr.each{|n| map[n] = map[n] + 1}

m = readline.to_i
b = readline.split(' ').collect(&:to_i)
c = readline.split(' ').collect(&:to_i)
besti, bestb, bestc = -1, -1, -1
b.zip(c).each_with_index do |item, ind|
  bb, cc = item
  thisb, thisc = map[bb], map[cc]
  if thisb > bestb || thisb == bestb && thisc > bestc
    besti, bestb, bestc = ind, thisb, thisc
  end
end

puts besti + 1

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

scientists = gets.to_i
sc_langs = parse_int.call
films = gets.to_i
film_voice = parse_int.call
film_sub = parse_int.call

#p film_voice.to_s
#p film_sub.to_s

ppl_in_lang = Hash.new
ppl_in_lang.default = 0

sc_langs.each { |_|
  if ppl_in_lang[_] == 0
    ppl_in_lang[_]=1
  else
    ppl_in_lang[_]+=1
  end
}

#p ppl_in_lang.to_s

film_good, film_ok = [0]*films, [0]*films

films.times { |_|
  film_good[_] += ppl_in_lang[film_voice[_]]
  film_ok[_]   += ppl_in_lang[film_sub[_]  ]
}
#p sc_langs.to_s
#p sc_langs[3]

best = 0
films.times { |_|
  best = _ if film_good[_] > film_good[best]
  best = _ if (film_good[_] == film_good[best]) and (film_ok[_] > film_ok[best])
}
#p film_good.to_s
#p film_ok.to_s

p best+1


Alice and Bob are playing a fun game of tree tag.The game is played on a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. Recall that a tree on $$$n$$$ vertices is an undirected, connected graph with $$$n-1$$$ edges.Initially, Alice is located at vertex $$$a$$$, and Bob at vertex $$$b$$$. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most $$$da$$$ from the current vertex. And in a move, Bob can jump to a vertex with distance at most $$$db$$$ from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.If after at most $$$10^{100}$$$ moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.Determine the winner if both players play optimally.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains five integers $$$n,a,b,da,db$$$ ($$$2\le n\le 10^5$$$, $$$1\le a,b\le n$$$, $$$a\ne b$$$, $$$1\le da,db\le n-1$$$)  — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following $$$n-1$$$ lines describe the edges of the tree. The $$$i$$$-th of these lines contains two integers $$$u$$$, $$$v$$$ ($$$1\le u, v\le n, u\ne v$$$), denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, output a single line containing the winner of the game: "Alice" or "Bob".

NoteIn the first test case, Alice can win by moving to vertex $$$1$$$. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.  In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices $$$1$$$ or $$$6$$$ is farthest from Alice.

gets.to_i.times{n,a,b,c,d=gets.split.map &:to_i
h=Hash.new{[]}
(2..n).map{p,q=gets.split.map &:to_i;h[p]<<=q;h[q]<<=p}
e=->s{z={};v=-1
f=->c{z[c]||(z[c]=v+=1;h[c].map &f;v-=1)}
f[s];z}
i=e[a]
puts i[b]>c&&e[i.max_by{|k,v|v}[0]].values.max>2*c&&d>2*c ?"Bob":"Alice"}


There is a game called "Unique Bid Auction". You can read more about it here: https://en.wikipedia.org/wiki/Unique_bid_auction (though you don't have to do it to solve this problem).Let's simplify this game a bit. Formally, there are $$$n$$$ participants, the $$$i$$$-th participant chose the number $$$a_i$$$. The winner of the game is such a participant that the number he chose is unique (i. e. nobody else chose this number except him) and is minimal (i. e. among all unique values of $$$a$$$ the minimum one is the winning one).Your task is to find the index of the participant who won the game (or -1 if there is no winner). Indexing is $$$1$$$-based, i. e. the participants are numbered from $$$1$$$ to $$$n$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 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 participants. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th participant chosen number. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the index of the participant who won the game (or -1 if there is no winner). Note that the answer is always unique.

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  dp = Hash.new(0)
  min = 10 ** 10
  arr.each do |el|
    dp[el] += 1
  end
  dp.each do |k, v|
    if v == 1
      min = [min, k].min
    end
  end
  puts (arr.index(min) || -2) + 1
end

t = gets.to_i

1.upto t do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  list = a.tally.keep_if {|_, v| v == 1}.keys
  if list.empty?
    puts -1
  else
    puts a.index(list.min)+1
  end
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i)
    count = Hash.new(0)
    index = Hash.new(0)
    ans = []
    a.each_with_index do |i,j|
        count[i] += 1
    end
    #p index
    min = Float::INFINITY
    count.each do |i,j|
        if j == 1
            min = [min,i].min
        end
    end
    if min == Float::INFINITY
        puts "-1"
    else
        a.each_with_index do |i,j|
            if i == min
                puts j+1
            end
        end
    end
end


The only difference between easy and hard versions are constraints on $$$n$$$ and $$$k$$$.You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $$$k$$$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $$$0$$$).Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.You (suddenly!) have the ability to see the future. You know that during the day you will receive $$$n$$$ messages, the $$$i$$$-th message will be received from the friend with ID $$$id_i$$$ ($$$1 \le id_i \le 10^9$$$).If you receive a message from $$$id_i$$$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.Otherwise (i.e. if there is no conversation with $$$id_i$$$ on the screen):  Firstly, if the number of conversations displayed on the screen is $$$k$$$, the last conversation (which has the position $$$k$$$) is removed from the screen.  Now the number of conversations on the screen is guaranteed to be less than $$$k$$$ and the conversation with the friend $$$id_i$$$ is not displayed on the screen.  The conversation with the friend $$$id_i$$$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $$$n$$$ messages.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 200)$$$ — the number of messages and the number of conversations your smartphone can show. The second line of the input contains $$$n$$$ integers $$$id_1, id_2, \dots, id_n$$$ ($$$1 \le id_i \le 10^9$$$), where $$$id_i$$$ is the ID of the friend which sends you the $$$i$$$-th message.

In the first line of the output print one integer $$$m$$$ ($$$1 \le m \le min(n, k)$$$) — the number of conversations shown after receiving all $$$n$$$ messages. In the second line print $$$m$$$ integers $$$ids_1, ids_2, \dots, ids_m$$$, where $$$ids_i$$$ should be equal to the ID of the friend corresponding to the conversation displayed on the position $$$i$$$ after receiving all $$$n$$$ messages.

NoteIn the first example the list of conversations will change in the following way (in order from the first to last message):  $$$[]$$$;  $$$[1]$$$;  $$$[2, 1]$$$;  $$$[3, 2]$$$;  $$$[3, 2]$$$;  $$$[1, 3]$$$;  $$$[1, 3]$$$;  $$$[2, 1]$$$. In the second example the list of conversations will change in the following way:  $$$[]$$$;  $$$[2]$$$;  $$$[3, 2]$$$;  $$$[3, 2]$$$;  $$$[1, 3, 2]$$$;  and then the list will not change till the 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 C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) 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
########### ( ˘ω˘ )ｽﾔｧ… ###########
n, k = gsmi
ids = gsmi

dis = []

ids.each do |id|
  if h[id]==0
    dis.unshift(id)
    h[id]=1
  end
  if dis.size>k
    nn = dis.pop
    h[nn]=0
  end
end

puts "#{dis.size}\n#{dis.join(' ')}"

n, k = gets.split.map(&:to_i)
id = gets.split.map(&:to_i)
ans = []
id.each {|idi|
  unless ans.include?(idi)
    ans.pop if ans.size == k
    ans.unshift(idi)
  end
}
p ans.size
puts ans.join(" ")

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 C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) 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
########### ( ˘ω˘ )ｽﾔｧ… ###########
n, k = gsmi
ids = gsmi

dis = []

ids.each do |id|
  dis.unshift(id) if dis.index(id).nil?
  dis.pop if dis.size>k
end

puts "#{dis.size}\n#{dis.join(' ')}"


There are $$$n$$$ rectangles in a row. You can either turn each rectangle by $$$90$$$ degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of rectangles. Each of the next $$$n$$$ lines contains two integers $$$w_i$$$ and $$$h_i$$$ ($$$1 \leq w_i, h_i \leq 10^9$$$) — the width and the height of the $$$i$$$-th rectangle.

Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].In the second test, there is no way the second rectangle will be not higher than the first one.

def can_arrage_non_ascending(rects)

  limit = 10**10

  rects.each do |w, h|
    a, b = [w, h].sort
    if b <= limit
      limit = b
    elsif a <= limit
      limit = a
    else
      return false
    end
  end

  true

end

def solution
  count = read_int
  rects = []
  count.times do
    rects << read_ints
  end

  puts can_arrage_non_ascending(rects) ? "YES" : "NO"
end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map &:to_i
end

def read_string
  gets.chomp
end

solution

N = gets.to_i
wh = N.times.map{gets.split.map(&:to_i)}

num = 10**10
wh.each do |arr|
    num = arr.select{|e| e <= num}.max
    unless num
        puts 'NO'
        exit
    end
end
puts 'YES'

n = gets.to_i
rects = []
n.times do
  mn, mx = gets.strip.split.map(&:to_i)
  rects << [mn, mx].sort
end

mxh = rects[0][1]
possible = true
1.upto(n-1).each do |i|
  if rects[i][0] > mxh
    possible = false
    break
  else
    if rects[i][1] <= mxh
      mxh = rects[i][1]
    else
      mxh = rects[i][0]
    end
  end
end

puts (possible ? "YES" : "NO")

x = gets.chomp.to_i

best = Integer(1e9+100)
f = true
for i in 0... x
  y =  gets.strip.split(' ').map(&:to_i);
  mx = [y[0], y[1]].max
  mn = [y[0] , y[1]].min
  if mx <= best
    best = mx;
  elsif mn <= best
    best = mn
  else
    f = false
  end

end
unless f
  print "NO"
else
  print "YES"
end


The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$.    The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.

The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	ans = Array.new(n, 0)
	if a.count(a[0]) == n
		ans = Array.new(n, 1)
	elsif a[0] == a[n - 1] || n % 2 == 0
		ans = (0...n).map{|i| i % 2 + 1}
	else
		ans = (0...n).map{|i| i % 2 + 1}
		pos = (0...(n - 1)).to_a.index{|i| a[i] == a[i + 1]}
		if pos
			((pos + 1)...n).each{|i| ans[i] = (ans[i] == 1 ? 2 : 1)}
		else
			ans[n - 1] = 3
		end
	end

	puts ans.uniq.size
	puts ans.join(' ')
end

t = gets.to_i
(1..t).each do
  n = gets.to_i
  a = gets.split(' ')
  mp = Hash.new(0)
  a.each do |i|
    mp[i]+=1
  end
  if mp.length == 1
    puts 1
    (1..n).each do
      print "1 "
    end
    puts ""
  elsif n.modulo(2)==0
    puts "2"
    (1..n).each do |i|
      print "#{i.modulo(2)+1} "
    end
    puts ""
    elsif a[0]==a[n-1]
      puts "2"
      (1..n).each do |i|
        print "#{i.modulo(2)+1} "
      end
      puts ""
    else
      x = -1
      (1..n-1).each do |i|
        if(a[i]==a[i-1])
          x = i
          break
        end
      end
      if x!=-1
        puts "2"
        (0..n-1).each do |i|
          if i<x
            print "#{i.modulo(2)+1} "
          else
            print "#{(i+1).modulo(2)+1} "
          end
        end
        puts ""
      else
        puts "3"
        (1..n-1).each do |i|
          print "#{i.modulo(2)+1} "
        end
        puts "3"
      end
    end
  end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	b = a.sort.uniq
	ans = a.map do |i|
		l, r = -1, b.size
		while r - l > 1
			mid = (r + l) / 2
			if b[mid] >= i
				r = mid
			else
				l = mid
			end
		end
		r + 1
	end
	puts ans.uniq.size
	puts ans.join(' ')
end


There is a classroom with two rows of computers. There are $$$n$$$ computers in each row and each computer has its own grade. Computers in the first row has grades $$$a_1, a_2, \dots, a_n$$$ and in the second row — $$$b_1, b_2, \dots, b_n$$$.Initially, all pairs of neighboring computers in each row are connected by wire (pairs $$$(i, i + 1)$$$ for all $$$1 \le i < n$$$), so two rows form two independent computer networks.Your task is to combine them in one common network by connecting one or more pairs of computers from different rows. Connecting the $$$i$$$-th computer from the first row and the $$$j$$$-th computer from the second row costs $$$|a_i - b_j|$$$.You can connect one computer to several other computers, but you need to provide at least a basic fault tolerance: you need to connect computers in such a way that the network stays connected, despite one of its computer failing. In other words, if one computer is broken (no matter which one), the network won't split in two or more parts.That is the minimum total cost to make a fault-tolerant network?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of computers in each row. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the grades of computers in the first row. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$) — the grades of computers in the second row. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the minimum total cost to make a fault-tolerant network.

NoteIn the first test case, it's optimal to connect four pairs of computers:   computer $$$1$$$ from the first row with computer $$$2$$$ from the second row: cost $$$|1 - 4| = 3$$$;  computer $$$3$$$ from the first row with computer $$$2$$$ from the second row: cost $$$|1 - 4| = 3$$$;  computer $$$2$$$ from the first row with computer $$$1$$$ from the second row: cost $$$|10 - 20| = 10$$$;  computer $$$2$$$ from the first row with computer $$$3$$$ from the second row: cost $$$|10 - 25| = 15$$$;  In total, $$$3 + 3 + 10 + 15 = 31$$$.In the second test case, it's optimal to connect $$$1$$$ from the first row with $$$1$$$ from the second row, and $$$4$$$ from the first row with $$$4$$$ from the second row.

main = -> {
  # nearest end-end or farthest end-end or end-other

  t = int
  t.times do
    n = int
    a = ints
    b = ints

    end1a = a[0]
    end2a = a[-1]
    end1b = b[0]
    end2b = b[-1]

    ends = [[a[0], b[0]], [a[-1], b[-1]]]

    # farthest end-end
    ans = [
      (end1a - end2b).abs + (end2a - end1b).abs,
      (end1a - end1b).abs + (end2a - end2b).abs
    ].min

    ans1b = a.map { (_1 - end1b).abs }.min
    ans1a = b.map { (_1 - end1a).abs }.min

    # nearest end-end
    ans1 = [
      (end1a - end1b).abs,
      ans1b + ans1a
    ].min

    ans2b = a.map { (_1 - end2b).abs }.min
    ans2a = b.map { (_1 - end2a).abs }.min

    # nearest end-end
    ans2 = [
      (end2a - end2b).abs,
      ans2b + ans2a
    ].min

    # farthest end-end
    ans3 = [
      (end1a - end2b).abs,
      ans1a + ans2b
    ].min
    ans4 = [
      (end2a - end1b).abs,
      ans2a + ans1b
    ].min

    ans = [ans, ans1 + ans2, ans3 + ans4].min

    # p [ans, ans1, ans2, ans1a, ans1b, ans2a, ans2b]
    # p [low1a, up1a, low1b, up1b]
    # p [sorted_a, sorted_b]

    puts ans
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**18

require "set"
require "prime"

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def strings; gets.to_s.split end
def rep(n, &b); Array.new(n, &b) end
def yes; puts $yesno[1] end
def no; puts $yesno[0] end
def yesno t; puts $yesno[t] end
def YesNo t; puts YesNo[t] end
def YESNO t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * y.mod_inv(mod) % mod end
  def mod_nCr(r, mod = MOD); x = y = 1; (1..r).each { |i| x = x * (self + 1 - i) % mod; y = y * i % mod }; x.mod_div(y, mod); end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
  def compress(kinds = uniq.sort!); map { |x| kinds.bsearch_index { _1 >= x } }; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main[]

main = -> {
  # nearest end-end or farthest end-end or end-other

  t = int
  t.times do
    n = int
    a = ints
    b = ints

    end1a = a[0]
    end2a = a[-1]
    end1b = b[0]
    end2b = b[-1]

    ends = [[a[0], b[0]], [a[-1], b[-1]]]

    # farthest end-end
    ans = [
      (end1a - end2b).abs + (end2a - end1b).abs,
      (end1a - end1b).abs + (end2a - end2b).abs
    ].min

    ans1 = INF
    ans2 = INF

    # nearest end-end
    ans1 = [
      (end1a - end1b).abs,
      a.map { (_1 - end1b).abs }.min + b.map { (_1 - end1a).abs }.min
    ].min

    # nearest end-end
    ans2 = [
      (end2a - end2b).abs,
      a.map { (_1 - end2b).abs }.min + b.map { (_1 - end2a).abs }.min
    ].min

    ans = [ans, ans1 + ans2].min

    # p [ans, ans1, ans2, ans1a, ans1b, ans2a, ans2b]
    # p [low1a, up1a, low1b, up1b]
    # p [sorted_a, sorted_b]

    puts ans
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**18

require "set"
require "prime"

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def strings; gets.to_s.split end
def rep(n, &b); Array.new(n, &b) end
def yes; puts $yesno[1] end
def no; puts $yesno[0] end
def yesno t; puts $yesno[t] end
def YesNo t; puts YesNo[t] end
def YESNO t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * y.mod_inv(mod) % mod end
  def mod_nCr(r, mod = MOD); x = y = 1; (1..r).each { |i| x = x * (self + 1 - i) % mod; y = y * i % mod }; x.mod_div(y, mod); end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
  def compress(kinds = uniq.sort!); map { |x| kinds.bsearch_index { _1 >= x } }; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main[]

main = -> {
  # nearest end-end or farthest end-end or end-other

  t = int
  t.times do
    n = int
    a = ints
    b = ints

    end1a = a[0]
    end2a = a[-1]
    end1b = b[0]
    end2b = b[-1]

    ends = [[a[0], b[0]], [a[-1], b[-1]]]

    # farthest end-end
    ans = (end1a - end2b).abs + (end2a - end1b).abs

    ans1 = INF
    ans2 = INF

    # nearest end-end
    ans1 = [
      (end1a - end1b).abs,
      a.map { (_1 - end1b).abs }.min + b.map { (_1 - end1a).abs }.min
    ].min

    # nearest end-end

    ans2 = [
      (end2a - end2b).abs,
      a.map { (_1 - end2b).abs }.min + b.map { (_1 - end2a).abs }.min
    ].min

    ans = [ans, ans1 + ans2].min

    # p [ans, ans1, ans2, ans1a, ans1b, ans2a, ans2b]
    # p [low1a, up1a, low1b, up1b]
    # p [sorted_a, sorted_b]

    puts ans
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**18

require "set"
require "prime"

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def strings; gets.to_s.split end
def rep(n, &b); Array.new(n, &b) end
def yes; puts $yesno[1] end
def no; puts $yesno[0] end
def yesno t; puts $yesno[t] end
def YesNo t; puts YesNo[t] end
def YESNO t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * y.mod_inv(mod) % mod end
  def mod_nCr(r, mod = MOD); x = y = 1; (1..r).each { |i| x = x * (self + 1 - i) % mod; y = y * i % mod }; x.mod_div(y, mod); end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
  def compress(kinds = uniq.sort!); map { |x| kinds.bsearch_index { _1 >= x } }; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main[]

main = -> {
  # nearest end-end or farthest end-end or end-other

  t = int
  t.times do
    n = int
    a = ints
    b = ints

    end1a = a[0]
    end2a = a[-1]
    end1b = b[0]
    end2b = b[-1]

    ends = [[a[0], b[0]], [a[-1], b[-1]]]

    sorted_a = a.sort
    sorted_b = b.sort

    # farthest end-end
    ans = (end1a - end2b).abs + (end2a - end1b).abs

    ans1 = INF
    ans2 = INF

    # nearest end-end
    ans1 = (end1a - end1b).abs

    # other-a
    low1b = sorted_b.bsearch_index { |x| x >= end1a } || 0
    up1b = sorted_b.bsearch_index { |x| x > end1a } || n
    ans1a = INF
    ans1a = (sorted_b[low1b] - end1a).abs if low1b
    ans1a = [ans1a, (sorted_b[up1b - 1] - end1a).abs].min if up1b
    # other-b
    low1a = sorted_a.bsearch_index { |x| x >= end1b } || 0
    up1a = sorted_a.bsearch_index { |x| x > end1b } || n
    ans1b = INF
    ans1b = (sorted_a[low1a] - end1b).abs if low1a
    ans1b = [ans1b, (sorted_a[up1a - 1] - end1b).abs].min if up1a

    ans1 = [ans1, ans1a + ans1b].min

    # nearest end-end
    ans2 = (end2a - end2b).abs

    # other-a
    low2b = sorted_b.bsearch_index { |x| x >= end2a } || 0
    up2b = sorted_b.bsearch_index { |x| x > end2a } || n
    ans2a = INF
    ans2a = (sorted_b[low2b] - end2a).abs if low2b
    ans2a = [ans2a, (sorted_b[up2b - 1] - end2a).abs].min if up2b and up2b > 0
    # other-b
    low2a = sorted_a.bsearch_index { |x| x >= end2b } || 0
    up2a = sorted_a.bsearch_index { |x| x > end2b } || n
    ans2b = INF
    ans2b = (sorted_a[low2a] - end2b).abs if low2a
    ans2b = [ans2b, (sorted_a[up2a - 1] - end2b).abs].min if up2a and up2a > 0

    ans2 = [ans2, ans2a + ans2b].min

    ans = [ans, ans1 + ans2].min

    # p [ans, ans1, ans2, ans1a, ans1b, ans2a, ans2b]
    # p [low1a, up1a, low1b, up1b]
    # p [sorted_a, sorted_b]

    puts ans
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**18

require "set"
require "prime"

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def strings; gets.to_s.split end
def rep(n, &b); Array.new(n, &b) end
def yes; puts $yesno[1] end
def no; puts $yesno[0] end
def yesno t; puts $yesno[t] end
def YesNo t; puts YesNo[t] end
def YESNO t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * y.mod_inv(mod) % mod end
  def mod_nCr(r, mod = MOD); x = y = 1; (1..r).each { |i| x = x * (self + 1 - i) % mod; y = y * i % mod }; x.mod_div(y, mod); end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
  def compress(kinds = uniq.sort!); map { |x| kinds.bsearch_index { _1 >= x } }; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main[]


Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. $$$2 \cdot n$$$ students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly $$$n$$$ people in each row). Students are numbered from $$$1$$$ to $$$n$$$ in each row in order from left to right.  Now Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one taken) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all $$$2n$$$ students (there are no additional constraints), and a team can consist of any number of students. Demid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of students in each row. The second line of the input contains $$$n$$$ integers $$$h_{1, 1}, h_{1, 2}, \ldots, h_{1, n}$$$ ($$$1 \le h_{1, i} \le 10^9$$$), where $$$h_{1, i}$$$ is the height of the $$$i$$$-th student in the first row. The third line of the input contains $$$n$$$ integers $$$h_{2, 1}, h_{2, 2}, \ldots, h_{2, n}$$$ ($$$1 \le h_{2, i} \le 10^9$$$), where $$$h_{2, i}$$$ is the height of the $$$i$$$-th student in the second row.

Print a single integer — the maximum possible total height of players in a team Demid can choose.

NoteIn the first example Demid can choose the following team as follows:   In the second example Demid can choose the following team as follows:

def solve(io)
    n = io.gets.to_i
    arr = 2.times.map{ io.gets.split(" ").map{|s| s.to_i} }
    max = n.times.inject([0, 0, 0]) do |prev, i|
        [[prev[1], prev[2]].max, [prev[0], prev[2]].max + arr[0][i], [prev[0], prev[1]].max + arr[1][i]]
    end.max
    puts max
end

solve(STDIN)

def check(num, team, row, column, opp_row)
    max = team[ row ][ column ]
    if column + 1 < num
        max += team[ opp_row ][ column + 1 ]
    end
    if column + 2 < num
        sum2 = team[ row ][ column ] + team[ opp_row ][ column + 2 ]
        if(max < sum2)
            max = sum2;
        end
    end
    team[ row ][ column ] = max
end
def start(num, team)
    column = num - 1
    while column >= 0 do
        check(num, team, 0, column, 1)
        check(num, team, 1, column, 0)
        column -= 1;
    end
    if(team[ 0 ][ 0 ] > team[ 1 ][ 0 ])
        return team[ 0 ][ 0 ]
    end
    return team[ 1 ][ 0 ]
end
team = []
num = gets.chomp.to_i
team.push(gets.chomp.split(' ').collect{|var| var.to_i})
team.push(gets.chomp.split(' ').collect{|var| var.to_i})
puts start(num,team.clone)

def recur(num,team,row,column)
    sum1 = 0
    if(column == num)
        return 0
    else
        if row == 1
            sum_1 = team[row][column] + recur(num,team,0,column + 1)
            sum_2 = recur(num,team,row,column + 1)
            if(sum_1 > sum_2)
                sum1 = sum_1
            else
                sum1 = sum_2
            end
        else
            sum_1 = team[row][column] + recur(num,team,1,column + 1)
            sum_2 = recur(num,team,row,column + 1)
            if(sum_1 > sum_2)
                sum1 = sum_1
            else
                sum1 = sum_2
            end
        end
        return sum1
    end
end
def start(num, team)
    sum1 = team[1][0] + recur(num,team,0,1)
    sum2 = team[0][0] + recur(num,team,1,1)
    if(sum1 > sum2)
        return sum1
    end
    return sum2
end
team = []
num = gets.chomp.to_i
team.push(gets.chomp.split(' ').collect{|var| var.to_i})
team.push(gets.chomp.split(' ').collect{|var| var.to_i})

def recur(num,team,row,column)
    sum1 = 0
    if(column == num)
        return 0
    else
        if row == 1
            sum_1 = team[row][column] + recur(num,team,0,column + 1)
            sum_2 = recur(num,team,row,column)
            if(sum_1 > sum_2)
                sum1 = sum_1
            else
                sum1 = sum_2
            end
        else
            sum_1 = team[row][column] + recur(num,team,1,column + 1)
            sum_2 = recur(num,team,row,column)
            if(sum_1 > sum_2)
                sum1 = sum_1
            else
                sum1 = sum_2
            end
        end
        return sum1
    end
end
def start(num, team)
    sum1 = team[1][0] + recur(num,team,0,1)
    sum2 = team[0][0] + recur(num,team,1,1)
    if(sum1 > sum2)
        return sum1
    end
    return sum2
end
team = []
num = gets.chomp.to_i
team.push(gets.chomp.split(' ').collect{|var| var.to_i})
team.push(gets.chomp.split(' ').collect{|var| var.to_i})


One beautiful day Vasily the bear painted 2m circles of the same radius R on a coordinate plane. Circles with numbers from 1 to m had centers at points (2R - R, 0), (4R - R, 0), ..., (2Rm - R, 0), respectively. Circles with numbers from m + 1 to 2m had centers at points (2R - R, 2R), (4R - R, 2R), ..., (2Rm - R, 2R), respectively. Naturally, the bear painted the circles for a simple experiment with a fly. The experiment continued for m2 days. Each day of the experiment got its own unique number from 0 to m2 - 1, inclusive. On the day number i the following things happened:   The fly arrived at the coordinate plane at the center of the circle with number  ( is the result of dividing number x by number y, rounded down to an integer).  The fly went along the coordinate plane to the center of the circle number  ( is the remainder after dividing number x by number y). The bear noticed that the fly went from the center of circle v to the center of circle u along the shortest path with all points lying on the border or inside at least one of the 2m circles. After the fly reached the center of circle u, it flew away in an unknown direction. Help Vasily, count the average distance the fly went along the coordinate plane during each of these m2 days.

The first line contains two integers m, R (1 ≤ m ≤ 105, 1 ≤ R ≤ 10).

In a single line print a single real number — the answer to the problem. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.

def g(r, n)
    d = (2 * r * r) ** 0.5

    return 0 if n == 0
    return 2 * r + d if n == 1

    2 * r + d + (2 * d + r * n) * (n - 1)
end

m, r = gets.chomp.split(' ').map { |x| x.to_i }

total = 0.0

for n in 1..m
    total += g(r, n - 1) + g(r, m - n) + 2 * r
end

puts total / m ** 2

#def f(n, r)
#  return 2 * r if n == 0
#  return 2 * n * r + (2 * r ** 2) ** 0.5
#end

def g(n, r)
  return 0 if n == 0
  (r * (n + 1) + (2 * r ** 2) ** 0.5) * n
end

m, r = gets.chomp.split(' ').map { |x| x.to_i }
total_sum = 0
for n in 1..m
  total_sum += g(n - 1, r) + g(m - n, r) + 2 * r
end

puts total_sum * 1.0 / m ** 2
=begin
if f(0, 1) != 2
  puts "Error"
  exit
end

if f(2, 1) != 4 * 1 + 2 ** 0.5
  puts "Error"
  exit
end

if g(2, 1) != 4 * 1 + 2 ** 0.5
  puts "Error"
  exit
end
=end

def g(n, r)
  return 0 if n == 0
  (r * (n + 1) + (2 * r ** 2) ** 0.5) * n
end

m, r = gets.chomp.split(' ').map { |x| x.to_i }
total_sum = 0.0
for n in 1..m
  total_sum += g(n - 1, r) + g(m - n, r) + 2 * r
end

puts total_sum / m ** 2


Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds:  $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$;  There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i < b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j < i$$$.

The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.

For each test case, output a single line containing a single string, which is either   the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them;  three dashes (the string "---" without quotes) if it is impossible.

3
AZAMON APPLE
AZAMON AAAAAAAAAAALIBABA
APPLE BANANA

NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".

N=STDIN.gets.strip.to_i
(0..N-1).each do |i|
  s,t=STDIN.gets.strip.split
  if s<t
    puts s
  else
    sorteds=s.chars.sort.join

    #puts sorteds

    changeindex=-1
    (0..s.size-1).each do |i|
      if sorteds[i]!=s[i]
        changeindex=i
        break
      end
    end
    if changeindex==-1
      puts '---'
      next
    end
    #p changeindex

    ss=sorteds[changeindex]
    index=-1
    c=0
    s.chars do |i|
      if i==ss
        index=c
      end
      c+=1
    end
    tmp=s[index]
    s[index]=s[changeindex]
    s[changeindex]=tmp
    if s<t
      puts s
    else
      puts '---'
    end
  end
end

def solution
  n = gets.chomp.to_i
  mi = Array.new(n-1)
  n.times do
    s, c = gets.chomp.split(' ')
    n = s.size
    mi[n-1] = n-1
    (n-2).downto(0) do |i|
      mi[i] = s[i] < s[mi[i+1]] ? i : mi[i+1]
    end
    0.upto(n-1) do |i|
      if s[i] > s[mi[i]]
        s[i], s[mi[i]] = s[mi[i]], s[i]
        break
      end
    end
    puts (s < c ? s : '---')
  end
end

solution

def smallest(w)
  ary = w.chars
  ary_with_index = ary.each_with_index.sort
  ary_with_index.each_with_index do |(a, i), j|
    if i > j
      a = ary[i]
      _, i = ary_with_index.select { |(x, y)| x == a }.max_by { |x, y| y}
      ary[i], ary[j] = ary[j], ary[i]
      return ary.join('')
    end
  end
  ary.join('')
end

nb = gets.to_i
nb.times do
  w1, w2 = gets.chomp.split
  w = smallest(w1)
  puts w < w2 ? w : '---'
end

def smallest(w)
  ary = w.chars
  ary_with_index = ary.each_with_index.sort
  ary_with_index.each_with_index do |(a, i), j|
    if i > j
      ary[i], ary[j] = ary[j], ary[i]
      break
    end
  end
  ary.join('')
end

nb = gets.to_i
nb.times do
  w1, w2 = gets.chomp.split
  w = smallest(w1)
  puts w < w2 ? w : '---'
end

def smallest(w)
  ary = w.chars
  ary_with_index = ary.each_with_index.sort
  ary_with_index.each_with_index do |(a, i), j|
    if i > j
      ary[i], ary[j] = ary[j], ary[i]
      return ary.join('')
    end
  end
  ary.join('')
end

nb = gets.to_i
nb.times do
  w1, w2 = gets.chomp.split
  w = smallest(w1)
  puts w < w2 ? w : '---'
end

def smallest(w)
  ary = w.chars
  ary_with_index = ary.each_with_index.sort
  ary_with_index.each_with_index do |(a, i), j|
    if i > j
      ary[i], ary[j] = ary[j], ary[i]
      break
    end
  end
  ary.join('')
end

nb = gets.to_i
nb.times do
  w1, w2 = gets.chomp.split
  w = smallest(w1)
  print w < w2 ? w : '---'
end


Polar bears like unique arrays — that is, arrays without repeated elements. You have got a unique array s with length n containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays a and b that are also of length n, with the following conditions for all i (1 ≤ i ≤ n):  ai, bi are non-negative integers;  si = ai + bi . Ideally, a and b should also be unique arrays. However, life in the Arctic is hard and this is not always possible. Fortunately, Alice and Bob are still happy if their arrays are almost unique. We define an array of length n to be almost unique, if and only if it can be turned into a unique array by removing no more than  entries.For example, the array [1, 2, 1, 3, 2] is almost unique because after removing the first two entries, it becomes [1, 3, 2]. The array [1, 2, 1, 3, 1, 2] is not almost unique because we need to remove at least 3 entries to turn it into a unique array.So, your task is to split the given unique array s into two almost unique arrays a and b.

The first line of the input contains integer n (1 ≤ n ≤ 105). The second line contains n distinct integers s1, s2, ... sn (0 ≤ si ≤ 109).

If it is possible to make Alice and Bob happy (if you can split the given array), print "YES" (without quotes) in the first line. In the second line, print the array a. In the third line, print the array b. There may be more than one solution. Any of them will be accepted. If it is impossible to split s into almost unique arrays a and b, print "NO" (without quotes) in the first line.

NoteIn the sample, we can remove the first two entries from a and the second entry from b to make them both unique.

n = gets.to_i;
c = gets.split(' ').map(&:to_i);
idx = (0..n-1).to_a.sort{|x, y|
  c[x] <=> c[y]
}
a = Array.new(n); b = Array.new(n);
cnt = (n+2)/3;

n.times{|i|
  j = idx[i];
  if i < cnt
    a[j] = i; b[j] = c[j] - a[j];
  elsif i < 2*cnt
    b[j] = i; a[j] = c[j] - b[j];
  else
    b[j] = n - i - 1; a[j] = c[j] - b[j];
  end
}
puts "YES"
puts a.map(&:to_s).join(' ')
puts b.map(&:to_s).join(' ')

n = gets.to_i;
c = gets.split(' ').map(&:to_i);
idx = (0..n-1).to_a.sort{|x, y|
  c[x] <=> c[y]
}
a = Array.new(n); b = Array.new(n);
cnt = (n+2)/3;

n.times{|i|
  j = idx[i];
  if i < cnt
    a[j] = i; b[j] = c[j] - a[j];
  elsif i < 2*cnt
    b[j] = i; a[j] = c[j] - b[j];
  else
    b[j] = n - i; a[j] = c[j] - b[j];
  end
}
puts "YES"
puts a.map(&:to_s).join(' ')
puts b.map(&:to_s).join(' ')

n = gets.to_i;
c = gets.split(' ').map(&:to_i);
idx = (0..n-1).to_a.sort{|x, y|
  c[x] <=> c[y]
}
a = Array.new(n); b = Array.new(n);
cnt = (n+2)/3;

n.times{|i|
  j = idx[i];
  if i < cnt
    a[j] = i; b[j] = c[j] - a[j];
  elsif i < 2*cnt
    b[j] = i; a[j] = c[j] - b[j];
  else
    b[j] = n - i; a[j] = c[j] - b[j];
  end
}
puts a.map(&:to_s).join(' ')
puts b.map(&:to_s).join(' ')


For an array $$$[b_1, b_2, \ldots, b_m]$$$ define its number of inversions as the number of pairs $$$(i, j)$$$ of integers such that $$$1 \le i < j \le m$$$ and $$$b_i>b_j$$$. Let's call array $$$b$$$ odd if its number of inversions is odd. For example, array $$$[4, 2, 7]$$$ is odd, as its number of inversions is $$$1$$$, while array $$$[2, 1, 4, 3]$$$ isn't, as its number of inversions is $$$2$$$.You are given a permutation $$$[p_1, p_2, \ldots, p_n]$$$ of integers from $$$1$$$ to $$$n$$$ (each of them appears exactly once in the permutation). You want to split it into several consecutive subarrays (maybe just one), so that the number of the odd subarrays among them is as large as possible. What largest number of these subarrays may be odd?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)  — the size of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct)  — the elements of the permutation. The sum of $$$n$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.

For each test case output a single integer  — the largest possible number of odd subarrays that you can get after splitting the permutation into several consecutive subarrays.

NoteIn the first and third test cases, no matter how we split our permutation, there won't be any odd subarrays.In the second test case, we can split our permutation into subarrays $$$[4, 3], [2, 1]$$$, both of which are odd since their numbers of inversions are $$$1$$$.In the fourth test case, we can split our permutation into a single subarray $$$[2, 1]$$$, which is odd.In the fifth test case, we can split our permutation into subarrays $$$[4, 5], [6, 1, 2, 3]$$$. The first subarray has $$$0$$$ inversions, and the second has $$$3$$$, so it is odd.

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  ans = 0
  i = 1
  while i < n do
    if a[i]<a[i-1] then
      ans += 1
      i += 1
    end
    i += 1
  end
  puts ans
end


— Hey folks, how do you like this problem?— That'll do it. BThero is a powerful magician. He has got $$$n$$$ piles of candies, the $$$i$$$-th pile initially contains $$$a_i$$$ candies. BThero can cast a copy-paste spell as follows:   He chooses two piles $$$(i, j)$$$ such that $$$1 \le i, j \le n$$$ and $$$i \ne j$$$.  All candies from pile $$$i$$$ are copied into pile $$$j$$$. Formally, the operation $$$a_j := a_j + a_i$$$ is performed. BThero can cast this spell any number of times he wants to — but unfortunately, if some pile contains strictly more than $$$k$$$ candies, he loses his magic power. What is the maximum number of times BThero can cast the spell without losing his power?

The first line contains one integer $$$T$$$ ($$$1 \le T \le 500$$$) — the number of test cases. Each test case consists of two lines:    the first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 1000$$$, $$$2 \le k \le 10^4$$$);  the second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le k$$$).  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$, and the sum of $$$k$$$ over all test cases does not exceed $$$10^4$$$.

For each test case, print one integer — the maximum number of times BThero can cast the spell without losing his magic power.

NoteIn the first test case we get either $$$a = [1, 2]$$$ or $$$a = [2, 1]$$$ after casting the spell for the first time, and it is impossible to cast it again.

T = gets.to_i

T.times do
  n, k = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i).sort

  x = a.first
  ans = 0

  puts a[1..-1].map { |v| (k - v) / x }.sum
end


Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is negative, then the company suffered losses on the i-th day.Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the n days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (ai < 0), he loses his temper and his wrath is terrible.Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.Write a program that, given sequence ai, will print the minimum number of folders.

The first line contains integer n (1 ≤ n ≤ 100), n is the number of days. The second line contains a sequence of integers a1, a2, ..., an (|ai| ≤ 100), where ai means the company profit on the i-th day. It is possible that the company has no days with the negative ai.

Print an integer k — the required minimum number of folders. In the second line print a sequence of integers b1, b2, ..., bk, where bj is the number of day reports in the j-th folder. If there are multiple ways to sort the reports into k days, print any of them.

NoteHere goes a way to sort the reports from the first sample into three folders:  1 2 3 -4 -5 | -6 5 -5 | -6 -7 6 In the second sample you can put all five reports in one folder.

n = gets.to_i
nums = gets.split.map{|i| i.to_i}

i = 0
folder = []
while i < n do
    folder << 1
    if nums[i] >= 0 then
        k = 0
    else
        k = 1
    end
    i += 1
    while k < 2 && i < n do
        folder[-1] += 1
        if nums[i] < 0 then
            k += 1
        end
        i += 1
    end
    while i < n && nums[i] >= 0 do
        folder[-1] += 1
        i += 1
    end
end

puts folder.size
puts folder.join(" ")

n = gets.to_i
a = gets.split.map(&:to_i)
count = 0
neg = 0
files = Array.new
for i in a
  if i < 0 then neg += 1 end
  if neg == 3
    files << count
    count = 0
    neg = 1
  end
  count += 1
end
files << count
puts files.count
files.each {|x| print x, " "}

e = []
nn = 1
gets
ns = gets.chomp.split.map{|a| Integer(a)}
ns.each.with_index{|x,i| if x < 0 then e.insert(-1,i+1) end }
e=e.each_slice(2).map{|x| x.last}
if e.length == 0 then
  puts [1,ns.length]
else
  puts e.length
  e[e.length-1]=ns.length
  e.insert(0,0)
  puts e[1..e.length-1].zip(e[0..e.length-2]).map{|a,b| a-b}.join(" ")
end

n=gets.to_i
a=gets.split.map(&:to_i)
res=[]
c=k=0
a.each do |v|
    c+=1
    k+=1 if v<0
    if k==2 then
        res.push(c)
        c=k=0
    end
end
if res.empty? then
    puts 1
    puts n
else
    if k > 0 then
        res.push(c)
    else
        res[res.size()-1]+=c
    end
    puts res.size
    puts res*' '
end

def main()
	n=gets.chomp.to_i;
	ar=gets.chomp.split(" ");
	ar=ar.map{|i| i.to_i};
	nof=0;non=0;noeinf=[];
	noe=0;
	for i in 0...(ar.length)
		if ar[i]<0
			non+=1
		else
			noe+=1;
		end
		if non==3
			noeinf << noe+2;
			nof+=1;
			non=1;
			noe=0;
		end
	end
	if non>0 || noe >0
		nof+=1;
		noeinf << (non+noe);
	end
	puts nof;
	puts noeinf.join(" ")
end
main()

n=readline.to_i
a=gets.chomp.split.map{|i| i.to_i}
counter=0
num=0
res=[]

a.each do |i|
if i<0 then
 counter=counter+1
end
if counter==3 then
 res.push num
 num=0
counter=1
end
num=num+1
end

if num>0
 res.push num
end

puts res.size
res.each do |i|
 print i.to_s+' '
end
print "\n"

n=gets.to_i
a=gets.split.collect{|e| e.to_i}
b=[]
k=0
l=0
for i in 0..n-1 do
  l+=1
  if (a[i]<0) then
    if (k==2) then
      b<<l-1
      l=1
      k=0
    end
    k+=1
  end
end
b<<l
puts b.size
b.each{|e| print e," "}
puts

e = []
nn = 1
gets
ns = gets.chomp.split.map{|a| Integer(a)}
ns.each.with_index{|x,i| if x < 0 then e.insert(-1,i+1) end }
e=e.each_slice(2).map{|x| x.last}
if e.length == 0 then
  puts [1,1]
else
  puts e.length
  e[e.length-1]=ns.length
  e.insert(0,0)
  puts e[1..e.length-1].zip(e[0..e.length-2]).map{|a,b| a-b}.join(" ")
end

n=gets.to_i
a=gets.split.map(&:to_i)
res=[]
c=k=0
a.each do |v|
    c+=1
    k+=1 if v<0
    if k==2 then
        res.push(c)
        c=k=0
    end
end
if res.empty? then
    puts 1
    puts n
else
    res[res.size()-1]+=c
    puts res.size
    puts res*' '
end

def main()
	n=gets.chomp.to_i;
	ar=gets.chomp.split(" ");
	ar=ar.map{|i| i.to_i};
	nof=0;non=0;noeinf=[];
	noe=0;
	for i in 0...(ar.length)
		if ar[i]<0
			non+=1
		else
			noe+=1;
		end
		if non==3
			noeinf << noe+non;
			nof+=1;
			non=0;
			noe=0;
		end
	end
	if non>0 || noe >0
		nof+=1;
		noeinf << (non+noe);
	end
	puts nof;
	puts noeinf.join(" ")
end
main()

def main()
	n=gets.chomp.to_i;
	ar=gets.chomp.split(" ");
	ar=ar.map{|i| i.to_i};
	nof=0;non=0;noeinf=[];
	noe=0;
	for i in 0...(ar.length)
		if ar[i]<0
			non+=1
		else
			noe+=1;
		end
		if non==2 && noe>=1
			noeinf << noe+non;
			nof+=1;
			non=0;
			noe=0;
		end
	end
	if non>0 || noe >0
		nof+=1;
		noeinf << (non+noe);
	end
	puts nof;
	puts noeinf.join(" ")
end
main()

def main()
	n=gets.chomp.to_i;
	ar=gets.chomp.split(" ");
	ar=ar.map{|i| i.to_i};
	ar=ar.sort
	nof=0;non=0;noeinf=[];
	for i in 0...(ar.length)
		if ar[i]<0
			non+=1
		else
			nof+=1;
			noef=(ar.length)-i;
			noeinf << noef+non;
 			break;
		end
		if non==3
			non=0;
			nof+=1;
			noeinf << 3;
		end
	end
	puts nof;
	puts noeinf.join(" ")
end
main()

def main()
	n=gets.chomp.to_i;
	ar=gets.chomp.split(" ");
	ar=ar.map{|i| i.to_i};
	ar=ar.sort
	nof=0;non=0;noeinf=[];
	for i in 0...(ar.length)
		if ar[i]<0
			non+=1
		else
			nof+=1;
			noef=(ar.length)-i;
			noeinf << noef+non;
 			break;
		end
		if non==3
			non=0;
			nof+=1;
			noeinf << 3;
		end
	end
	puts nof;
	noeinf=noeinf.sort
	puts noeinf.join(" ")
end
main()

def main()
	n=gets.chomp.to_i;
	ar=gets.chomp.split(" ");
	ar=ar.map{|i| i.to_i};
	nof=0;non=0;noeinf=[];
	noe=0;
	for i in 0...(ar.length)
		if ar[i]<0
			non+=1
		else
			noe+=1;
		end
		if non==2
			noeinf << noe+non;
			nof+=1;
			non=0;
			noe=0;
		end
	end
	if non>0 || noe >0
		nof+=1;
		noeinf << (non+noe);
	end
	puts nof;
	puts noeinf.join(" ")
end
main()


You are given a string $$$s$$$. You have to determine whether it is possible to build the string $$$s$$$ out of strings aa, aaa, bb and/or bbb by concatenating them. You can use the strings aa, aaa, bb and/or bbb any number of times and in any order.For example:  aaaabbb can be built as aa $$$+$$$ aa $$$+$$$ bbb;  bbaaaaabbb can be built as bb $$$+$$$ aaa $$$+$$$ aa $$$+$$$ bbb;  aaaaaa can be built as aa $$$+$$$ aa $$$+$$$ aa;  abab cannot be built from aa, aaa, bb and/or bbb.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 50$$$), consisting of characters a and/or b.

For each test case, print YES if it is possible to build the string $$$s$$$. Otherwise, print NO. You may print each letter in any case (for example, YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).

8

aaaabbb

bbaaaaabbb

aaaaaa

abab

a

b

aaaab

bbaaa

NoteThe first four test cases of the example are described in the statement.

gets.to_i.times do
  s = gets.chomp
  puts s.chars.chunk { |a| a }.map(&:last).map(&:size).min == 1 ? "NO" : "YES"
end

gets.to_i.times do
  s = gets.chomp.split('')
  c = 1
  flag = true
  1.upto(s.size-1) do |i|
    if s[i]==s[i-1] then
      c += 1
    else
      flag = false if c < 2
      c = 1
    end
  end
  flag = false if c < 2
  puts flag ? "YES":"NO"
end


You are given a string $$$s$$$, consisting only of characters '0' and '1'.You have to choose a contiguous substring of $$$s$$$ and remove all occurrences of the character, which is a strict minority in it, from the substring.That is, if the amount of '0's in the substring is strictly smaller than the amount of '1's, remove all occurrences of '0' from the substring. If the amount of '1's is strictly smaller than the amount of '0's, remove all occurrences of '1'. If the amounts are the same, do nothing.You have to apply the operation exactly once. What is the maximum amount of characters that can be removed?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The only line of each testcase contains a non-empty string $$$s$$$, consisting only of characters '0' and '1'. The length of $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the maximum amount of characters that can be removed after applying the operation exactly once.

NoteIn the first testcase, you can choose substrings "0", "1" or "01". In "0" the amount of '0' is $$$1$$$, the amount of '1' is $$$0$$$. '1' is a strict minority, thus all occurrences of it are removed from the substring. However, since there were $$$0$$$ of them, nothing changes. Same for "1". And in "01" neither of '0' or '1' is a strict minority. Thus, nothing changes. So there is no way to remove any characters.In the second testcase, you can choose substring "10101010101". It contains $$$5$$$ characters '0' and $$$6$$$ characters '1'. '0' is a strict minority. Thus, you can remove all its occurrences. There exist other substrings that produce the same answer.In the third testcase, you can choose substring "011000100". It contains $$$6$$$ characters '0' and $$$3$$$ characters '1'. '1' is a strict minority. Thus, you can remove all its occurrences.

gets.to_i.times do
  s = gets.strip
  count = [0, 0]
  s.each_char { |c| count[c.ord - '0'.ord] += 1 }
  if count[0] == count[1]
    c = s[s.size - 1]
    count[c.ord - '0'.ord] -= 1
  end
  puts count.min
end


You are given an array $$$a$$$ of size $$$n$$$. Each element in this array is an integer between $$$1$$$ and $$$10^9$$$.You can perform several operations to this array. During an operation, you can replace an element in the array with any integer between $$$1$$$ and $$$10^9$$$. Output the minimum number of operations needed such that the resulting array doesn't contain any local maximums, and the resulting array after the operations.An element $$$a_i$$$ is a local maximum if it is strictly larger than both of its neighbors (that is, $$$a_i > a_{i - 1}$$$ and $$$a_i > a_{i + 1}$$$). Since $$$a_1$$$ and $$$a_n$$$ have only one neighbor each, they will never be a local maximum.

Each test contains multiple test cases. The first line will contain a single integer $$$t$$$ $$$(1 \leq t \leq 10000)$$$ — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ $$$(2 \leq n \leq 2 \cdot 10^5)$$$ — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots ,a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$, the elements of array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, first output a line containing a single integer $$$m$$$ — minimum number of operations required. Then ouput a line consist of $$$n$$$ integers — the resulting array after the operations. Note that this array should differ in exactly $$$m$$$ elements from the initial array. If there are multiple answers, print any.

NoteIn the first example, the array contains no local maximum, so we don't need to perform operations.In the second example, we can change $$$a_2$$$ to $$$3$$$, then the array don't have local maximums.

t = readline.strip.to_i
t.times do
  n = readline.strip.to_i
  nums = readline.strip.split(/\s+/).map(&:to_i)

  c = nums.count

  if c <= 2
    puts 0
    puts nums.join(' ')
    next
  end

  i = 1
  changes = 0
  while i < c - 1
    if nums[i] > nums[i-1] && nums[i] > nums[i+1] # local max
      if i+2 < c && nums[i+1] < nums[i+2]
        nums[i+1] = [nums[i], nums[i+2]].max
        changes += 1
        i += 1
        # puts "i=#{i} next is local min"
      else
        changes += 1
        nums[i] = [nums[i-1], nums[i+1]].max
      end
    end
    i += 1
  end

#  1 3 2 3 1
#    i

  puts changes
  puts nums.join(' ')
end

t = readline.strip.to_i
t.times do
  n = readline.strip.to_i
  nums = readline.strip.split(/\s+/).map(&:to_i)

  c = nums.count

  if c <= 3
    puts 0
    puts nums.join(' ')
    next
  end

  i = 1
  changes = 0
  while i < c - 1
    if nums[i] > nums[i-1] && nums[i] > nums[i+1] # local max
      if i+2 < c && nums[i+1] < nums[i+2]
        nums[i+1] = [nums[i], nums[i+2]].max
        changes += 1
        i += 1
        # puts "i=#{i} next is local min"
      else
        changes += 1
        nums[i] = [nums[i-1], nums[i+1]].max
      end
    end
    i += 1
  end

#  1 3 2 3 1
#    i

  puts changes
  puts nums.join(' ')
end


There are $$$n$$$ emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The $$$i$$$-th emote increases the opponent's happiness by $$$a_i$$$ units (we all know that emotes in this game are used to make opponents happy).You have time to use some emotes only $$$m$$$ times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you cannot use the same emote more than $$$k$$$ times in a row (otherwise the opponent will think that you're trolling him).Note that two emotes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that $$$a_i = a_j$$$ are considered different.You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.

The first line of the input contains three integers $$$n, m$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le k \le m \le 2 \cdot 10^9$$$) — the number of emotes, the number of times you can use emotes and the maximum number of times you may use the same emote in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is value of the happiness of the $$$i$$$-th emote.

Print one integer — the maximum opponent's happiness if you use emotes in a way satisfying the problem statement.

NoteIn the first example you may use emotes in the following sequence: $$$4, 4, 5, 4, 4, 5, 4, 4, 5$$$.

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

nmk = gets.chomp.split(' ').map(&:to_i)
n = nmk[0]
m = nmk[1]
k = nmk[2]

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

max=0
maxtwo=0

(0..n-1).each do |i|
	if(arr[i]>max)
    	maxtwo = max
    	max=arr[i]
    elsif(arr[i]>maxtwo)
    	maxtwo = arr[i]
    end
end

ans=(m/(k+1))*(max*(k)+maxtwo)
leftover = m-(m/(k+1))*(k+1);
ans+=max*leftover

puts ans


You are given an array $$$a$$$ of length $$$n$$$.Let's define the eversion operation. Let $$$x = a_n$$$. Then array $$$a$$$ is partitioned into two parts: left and right. The left part contains the elements of $$$a$$$ that are not greater than $$$x$$$ ($$$\le x$$$). The right part contains the elements of $$$a$$$ that are strictly greater than $$$x$$$ ($$$> x$$$). The order of elements in each part is kept the same as before the operation, i. e. the partition is stable. Then the array is replaced with the concatenation of the left and the right parts.For example, if the array $$$a$$$ is $$$[2, 4, 1, 5, 3]$$$, the eversion goes like this: $$$[2, 4, 1, 5, 3] \to [2, 1, 3], [4, 5] \to [2, 1, 3, 4, 5]$$$.We start with the array $$$a$$$ and perform eversions on this array. We can prove that after several eversions the array $$$a$$$ stops changing. Output the minimum number $$$k$$$ such that the array stops changing after $$$k$$$ eversions.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer $$$k$$$ — the number of eversions after which the array stops changing.

testcases = Integer(gets.chomp)
resultados = []

for i in 0..testcases-1
    n = Integer(gets.chomp)
    n -= 1
    arreglo = gets.chomp
    a = arreglo.split(" ")
    aux = a.sort
    mayor = aux[n].to_i
    k = a[n].to_i
    n -= 1
    divisiones = 0
    while n != -1
        if a[n] == mayor
            n = -1
        elsif !(a[n].to_i <= k)
            k = a[n].to_i
            divisiones += 1
        end
        n-=1
    end
    resultados.push(divisiones)
end
puts resultados


Vasya has a multiset $$$s$$$ consisting of $$$n$$$ integer numbers. Vasya calls some number $$$x$$$ nice if it appears in the multiset exactly once. For example, multiset $$$\{1, 1, 2, 3, 3, 3, 4\}$$$ contains nice numbers $$$2$$$ and $$$4$$$.Vasya wants to split multiset $$$s$$$ into two multisets $$$a$$$ and $$$b$$$ (one of which may be empty) in such a way that the quantity of nice numbers in multiset $$$a$$$ would be the same as the quantity of nice numbers in multiset $$$b$$$ (the quantity of numbers to appear exactly once in multiset $$$a$$$ and the quantity of numbers to appear exactly once in multiset $$$b$$$).

The first line contains a single integer $$$n~(2 \le n \le 100)$$$. The second line contains $$$n$$$ integers $$$s_1, s_2, \dots s_n~(1 \le s_i \le 100)$$$ — the multiset $$$s$$$.

If there exists no split of $$$s$$$ to satisfy the given requirements, then print "NO" in the first line. Otherwise print "YES" in the first line. The second line should contain a string, consisting of $$$n$$$ characters. $$$i$$$-th character should be equal to 'A' if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$a$$$ and 'B' if if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$b$$$. Elements are numbered from $$$1$$$ to $$$n$$$ in the order they are given in the input. If there exist multiple solutions, then print any of them.

n = gets.to_i
s = gets.split.map(&:to_i)
a = Hash.new(0)
n.times do |i|
  a[s[i]] += 1
end
if a.values.count(1).odd? && a.values.count{|j|j > 2} == 0
  puts "NO"
  exit
end
puts "YES"
ans = "A"*n
p = 0
n.times do |i|
  if a[s[i]] == 1
    if p == 1
      ans[i] = "B"
    end
    p = 1-p
  end
end
if p == 1
  n.times do |i|
    if a[s[i]] > 2
      ans[i] = "B"
      break
    end
  end
end
puts ans


During the hypnosis session, Nicholas suddenly remembered a positive integer $$$n$$$, which doesn't contain zeros in decimal notation. Soon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes not prime, that is, either composite or equal to one?For some numbers doing so is impossible: for example, for number $$$53$$$ it's impossible to delete some of its digits to obtain a not prime integer. However, for all $$$n$$$ in the test cases of this problem, it's guaranteed that it's possible to delete some of their digits to obtain a not prime number.Note that you cannot remove all the digits from the number.A prime number is a number that has no divisors except one and itself. A composite is a number that has more than two divisors. $$$1$$$ is neither a prime nor a composite number.

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$k$$$ ($$$1 \le k \le 50$$$) — the number of digits in the number. The second line of each test case contains a positive integer $$$n$$$, which doesn't contain zeros in decimal notation ($$$10^{k-1} \le n < 10^{k}$$$). It is guaranteed that it is always possible to remove less than $$$k$$$ digits to make the number not prime. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^4$$$.

For every test case, print two numbers in two lines. In the first line print the number of digits, that you have left in the number. In the second line print the digits left after all delitions.  If there are multiple solutions, print any.

NoteIn the first test case, you can't delete $$$2$$$ digits from the number $$$237$$$, as all the numbers $$$2$$$, $$$3$$$, and $$$7$$$ are prime. However, you can delete $$$1$$$ digit, obtaining a number $$$27 = 3^3$$$.In the second test case, you can delete all digits except one, as $$$4 = 2^2$$$ is a composite number.

require 'prime'

t = gets.to_i
t.times do

k = gets.to_i
n = gets.chomp.chars.map!(&:to_i)

q = n.map.with_index { |x, i| x << 8 | i }
while (x = q.shift)
  d = x & 0xff
  x >>= 8

  unless Prime.prime?(x)
    puts x.digits.size
    puts x
    break
  end

  n[d.succ..-1].each.with_index(d.succ) do |y, i|
    q << ((x * 10 + y) << 8 | i)
  end
end

end


Let's call the following process a transformation of a sequence of length $$$n$$$.If the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of $$$n$$$ integers: the greatest common divisors of all the elements in the sequence before each deletion.You are given an integer sequence $$$1, 2, \dots, n$$$. Find the lexicographically maximum result of its transformation.A sequence $$$a_1, a_2, \ldots, a_n$$$ is lexicographically larger than a sequence $$$b_1, b_2, \ldots, b_n$$$, if there is an index $$$i$$$ such that $$$a_j = b_j$$$ for all $$$j < i$$$, and $$$a_i > b_i$$$.

The first and only line of input contains one integer $$$n$$$ ($$$1\le n\le 10^6$$$).

Output $$$n$$$ integers  — the lexicographically maximum result of the transformation.

NoteIn the first sample the answer may be achieved this way:  Append GCD$$$(1, 2, 3) = 1$$$, remove $$$2$$$.  Append GCD$$$(1, 3) = 1$$$, remove $$$1$$$.  Append GCD$$$(3) = 3$$$, remove $$$3$$$. We get the sequence $$$[1, 1, 3]$$$ as the result.

# require 'prime'

def gcd(a, b)
  (b==0 ? a : gcd(b, a%b))
end

def arygcd(ary)
  ans = ary[0]
  ary.each do |x|
    ans = gcd(ans, x)
  end
  ans
end

n = gets.to_i

def solve(ary)
  n = ary.size
  if n==1
    return [1]
  elsif n==2
    return [1, 2]
  elsif n==3
    return [1, 1, 3]
  end
  ans = []
  nary = []
  ary.each do |x|
    if x%2 != 0
      ans << 1
    else
      nary << x/2
    end
  end
  solve(nary).each do |x|
    ans << 2*x
  end
  ans
end

ary = (1..n).to_a
puts solve(ary).join(" ")

n = gets.to_f
x = Math.log(n,2)

count = 0
expon = 0
curr = 2**expon

minicount = 0

while (count < n-2)
  print "#{curr} "
  count += 1
  minicount += 1
  if minicount == (n/(curr*2)).round(0)
    minicount = 0
    expon += 1
    curr = 2**expon
  end
end

thisthing = 2**((x.floor)-1)
if n==1
  puts 1
  exit
end
print "#{thisthing} "
puts "#{(n.to_i/thisthing)*thisthing}"

n = gets.to_f
x = Math.log(n,2)

count = 0
expon = 0
curr = 2**expon

minicount = 0

while (count < n-2)
  print "#{curr} "
  count += 1
  minicount += 1
  if minicount == (n/(curr*2)).round(0)
    minicount = 0
    expon += 1
    curr = 2**expon
  end
end

thisthing = 2**((x.floor)-1)
if n==1
  exit
end
print "#{thisthing} "
puts "#{(n.to_i/thisthing)*thisthing}"


An array $$$b$$$ of length $$$k$$$ is called good if its arithmetic mean is equal to $$$1$$$. More formally, if $$$$$$\frac{b_1 + \cdots + b_k}{k}=1.$$$$$$Note that the value $$$\frac{b_1+\cdots+b_k}{k}$$$ is not rounded up or down. For example, the array $$$[1,1,1,2]$$$ has an arithmetic mean of $$$1.25$$$, which is not equal to $$$1$$$.You are given an integer array $$$a$$$ of length $$$n$$$. In an operation, you can append a non-negative integer to the end of the array. What's the minimum number of operations required to make the array good?We have a proof that it is always possible with finitely many operations.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the initial array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$-10^4\leq a_i \leq 10^4$$$), the elements of the array.

For each test case, output a single integer — the minimum number of non-negative integers you have to append to the array so that the arithmetic mean of the array will be exactly $$$1$$$.

NoteIn the first test case, we don't need to add any element because the arithmetic mean of the array is already $$$1$$$, so the answer is $$$0$$$.In the second test case, the arithmetic mean is not $$$1$$$ initially so we need to add at least one more number. If we add $$$0$$$ then the arithmetic mean of the whole array becomes $$$1$$$, so the answer is $$$1$$$.In the third test case, the minimum number of elements that need to be added is $$$16$$$ since only non-negative integers can be added.In the fourth test case, we can add a single integer $$$4$$$. The arithmetic mean becomes $$$\frac{-2+4}{2}$$$ which is equal to $$$1$$$.

$\ = "\n"
gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    s = a.sum
    if s < n
        print 1
    else
        print s - n
    end
end

gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    s = a.sum
    if s < n
        puts 1
    else
        puts s - n
    end
end

gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    s = a.sum
    puts s < n ? 1 : s - n
end

t = Integer(gets.chomp)
t.times{
    n = Integer(gets.chomp)
    a = gets.chomp.split().map!{|c| Integer(c)}

    som = a.sum()
    len = a.size()

    if(som < len)
        puts 1
    elsif(som == len)
        puts 0
    else
        puts som - len
    end
}