There is a robot on a coordinate plane. Initially, the robot is located at the point $$$(0, 0)$$$. Its path is described as a string $$$s$$$ of length $$$n$$$ consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move:   'L' (left): means that the robot moves from the point $$$(x, y)$$$ to the point $$$(x - 1, y)$$$;  'R' (right): means that the robot moves from the point $$$(x, y)$$$ to the point $$$(x + 1, y)$$$;  'U' (up): means that the robot moves from the point $$$(x, y)$$$ to the point $$$(x, y + 1)$$$;  'D' (down): means that the robot moves from the point $$$(x, y)$$$ to the point $$$(x, y - 1)$$$. The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point $$$(x_e, y_e)$$$, then after optimization (i.e. removing some single substring from $$$s$$$) the robot also ends its path at the point $$$(x_e, y_e)$$$.This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string $$$s$$$).Recall that the substring of $$$s$$$ is such string that can be obtained from $$$s$$$ by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The next $$$2t$$$ lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the robot's path. The second line of the test case contains one string $$$s$$$ consisting of $$$n$$$ characters 'L', 'R', 'U', 'D' — the robot's path. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers $$$l$$$ and $$$r$$$ such that $$$1 \le l \le r \le n$$$ — endpoints of the substring you remove. The value $$$r-l+1$$$ should be minimum possible. If there are several answers, print any of them.

t= gets.to_i
t.times do |v|
    n= gets.to_i
    s= gets
    q= Hash.new()
    pos= [0,0]
    l,r= -1,n
    for i in 0...n do
        dd=pos*1
        q[dd]=i
        if s[i]=='L' then
            pos[0]-=1
        elsif s[i]=='R' then
            pos[0]+=1
        elsif s[i]=='U' then
            pos[1]+=1
        else
            pos[1]-=1
        end
        if q[pos]
            if i - q[pos]+1 < r-l+1 then
                l,r=q[pos],i
            end
        end
        dd= pos*1
        q[dd]=i+1
    end
    if l == -1 then
        puts -1
    else
        print l+1,' ',r+1,"\n"
    end
end

t=gets.to_i
for g in 1..t do
    n=gets.to_i
    s=gets
    d=Hash.new
    pos=[0,0]
    d[pos]=0
    l,r=-1,n-1
    for i in 0...n do
        if s[i]=='R'
            pos[0]+=1
        elsif s[i]=='L'
            pos[0]-=1
        elsif s[i]=='U'
            pos[1]+=1
        else
            pos[1]-=1
        end
        if d.include?(pos)
            if i-d[pos]+1 < r - l + 1
                l,r=d[pos],i
            end
        end
        d[pos]=i+1
    end
    if l == -1
        puts -1
    else
        print l + 1,' ',r + 1,"\n"
    end
    #p ans
end

t=gets.to_i
for g in 1..t do
    n=gets.to_i
    s=gets
    d=Hash.new
    pos=[0,0]
    d[pos]=0
    ans=[1,1000000000]
    for i in 0...n do
        if s[i]=='R'
            pos[0]+=1
        elsif s[i]=='L'
            pos[0]-=1
        elsif s[i]=='U'
            pos[1]+=1
        else
            pos[1]-=1
        end
        if d.include?(pos)
            if ans[1]-ans[0] > i-d[pos]
                ans=[d[pos]+1,i+1]
            end
        end
        d[pos]=i+1
    end
    if ans != [1,1000000000]
        print ans[0],' ',ans[1],"\n"
    else
        puts -1
    end
    #p ans
end

t=gets.to_i
for g in 1..t do
    n=gets.to_i
    s=gets
    d=Hash.new
    pos=[0,0]
    d[pos]=0
    ans=[]
    for i in 0...n do
        if s[i]=='R'
            pos[0]+=1
        elsif s[i]=='L'
            pos[0]-=1
        elsif s[i]=='U'
            pos[1]+=1
        else
            pos[1]-=1
        end
        if d.include?(pos)
            ans << [d[pos]+1,i+1]
        end
        d[pos]=i+1
    end
    ans.sort! {|a,b| a[0]+a[1]<=>b[0]+b[1]}
    if ans != []
        print ans[0][0],' ',ans[0][1],"\n"
    else
        puts -1
    end
end

t=gets.to_i
for g in 1..t do
    n=gets.to_i
    s=gets
    d=Hash.new
    pos=[0,0]
    d[pos]=0
    l,r=-1,n
    for i in 0...n do
        if s[i]=='R'
            pos[0]+=1
        elsif s[i]=='L'
            pos[0]-=1
        elsif s[i]=='U'
            pos[1]+=1
        else
            pos[1]-=1
        end
        if d.include?(pos)
            if i-d[pos] < r - l
                l,r=d[pos],i
            end
        end
        d[pos]=i+1
    end
    if l != -1
        print l+1,' ',r+1,"\n"
    else
        puts -1
    end
    #p ans
end

t=gets.to_i
for g in 1..t do
    n=gets.to_i
    s=gets
    d=Hash.new
    pos=[0,0]
    d[pos]=0
    l,r=-1,n+1
    for i in 0...n do
        if s[i]=='R'
            pos[0]+=1
        elsif s[i]=='L'
            pos[0]-=1
        elsif s[i]=='U'
            pos[1]+=1
        else
            pos[1]-=1
        end
        if d.include?(pos)
            if i-d[pos] < r - l
                l,r=d[pos],i
            end
        end
        d[pos]=i+1
    end
    if l == -1
        puts -1
    else
        print l+1,' ',r+1,"\n"
    end
    #p ans
end

t= gets.to_i
t.times do |v|
    n= gets.to_i
    s= gets
    q= Hash.new()
    pos= [0,0]
    l,r= -1,n
    for i in 0...n do
        dd=pos
        q[dd]=i
        if s[i]=='L' then
            pos[0]-=1
        elsif s[i]=='R' then
            pos[0]+=1
        elsif s[i]=='U' then
            pos[1]+=1
        else
            pos[1]-=1
        end
        if q[pos]
            if i - q[pos]+1 < r-l+1 then
                l,r=q[pos],i
            end
        end
        dd= pos
        q[dd]=i+1
    end
    if l == -1 then
        puts -1
    else
        print l+1,' ',r+1,"\n"
    end
end

t=gets.to_i
for g in 1..t do
    n=gets.to_i
    s=gets
    d=Hash.new
    pos=[0,0]
    d[pos]=0
    l,r=-1,n
    for i in 0..n do
        if s[i]=='R'
            pos[0]+=1
        elsif s[i]=='L'
            pos[0]-=1
        elsif s[i]=='U'
            pos[1]+=1
        else
            pos[1]-=1
        end
        if d.include?(pos)
            if i-d[pos] < r - l
                l,r=d[pos],i
            end
        end
        d[pos]=i+1
    end
    if l == -1
        puts -1
    else
        print l+1,' ',r+1,"\n"
    end
    #p ans
end

t= gets.to_i
t.times do |v|
    n=gets.to_i
    s=gets
    q=Hash.new()
    pos= [0,0]
    l,r= -1,n
    for i in 0...n do
        q[pos]=i
        if s[i]=='L' then
            pos[0]-=1
        elsif s[i]=='R' then
            pos[0]+=1
        elsif s[i]=='U' then
            pos[1]+=1
        else
            pos[1]-=1
        end
        if q.include?(pos)
            if i - q[pos]+1 < r-l+1 then
                l,r=q[pos],i
            end
        end
        q[pos]=i+1
    end
    if l == -1 then
        puts -1
    else
        print l+1,' ',r+1,"\n"
    end
end

gets.to_i.times do
    n=gets.to_i
    s=gets
    d=Hash.new
    pos=[0,0]
    d[pos]=0
    l,r=-1,n-1
    for i in 0...n do
        if s[i]=='R'
            pos[0]+=1
        elsif s[i]=='L'
            pos[0]-=1
        elsif s[i]=='U'
            pos[1]+=1
        else
            pos[1]-=1
        end
        if d.include?(pos)
            if i - d[pos] + 1 < r - l + 1
                l,r=d[pos],i
            end
        end
        d[pos]=i+1
    end
    if l == -1 then
        puts -1
    else
        print l + 1,' ',r + 1,"\n"
    end
    #p ans
end

t=gets.to_i
for g in 1..t do
    n=gets.to_i
    s=gets
    d=Hash.new
    pos=[0,0]
    d[pos]=0
    ans=[]
    for i in 0...n do
        if s[i]=='R'
            pos[0]+=1
        elsif s[i]=='L'
            pos[0]-=1
        elsif s[i]=='U'
            pos[1]+=1
        else
            pos[1]-=1
        end
        if d.include?(pos)
            ans << [d[pos]+1,i+1]
        end
        d[pos]=i+1
    end
    ans.sort! {|a,b| a[0]+a[1]<=>b[0]+b[1]}
    if ans != []
        print ans[-1][0],' ',ans[-1][1],"\n"
    else
        puts -1
    end
end

t=gets.to_i
for g in 1..t do
    n=gets.to_i
    s=gets
    d=Hash.new
    pos=[0,0]
    d[pos]=0
    l,r=-1,n-1
    for i in 0..n do
        if s[i]=='R'
            pos[0]+=1
        elsif s[i]=='L'
            pos[0]-=1
        elsif s[i]=='U'
            pos[1]+=1
        else
            pos[1]-=1
        end
        if d.include?(pos)
            if i-d[pos]+1 < r - l + 1
                l,r=d[pos],i
            end
        end
        d[pos]=i+1
    end
    if l == -1
        puts -1
    else
        print l + 1,' ',r + 1,"\n"
    end
    #p ans
end

t=gets.to_i
for g in 1..t do
    n=gets.to_i
    s=gets
    d=Hash.new
    pos=[0,0]
    d[pos]=0
    ans=[]
    for i in 0...n do
        if s[i]=='R'
            pos[0]+=1
        elsif s[i]=='L'
            pos[0]-=1
        elsif s[i]=='U'
            pos[1]+=1
        else
            pos[1]-=1
        end
        if d.include?(pos)
            ans << [d[pos]+1,i+1]
        end
        d[pos]=i+1
    end
    ans.sort! {|a,b| a[0]+a[1]<=>b[0]+b[1]}
    if ans != []
        print ans[0][0],' ',ans[0][1],"\n"
    else
        puts -1
    end
    #p ans
end


Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches. The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.

Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.

NoteIn the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.

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

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

c = gets.chop.to_i
word = gets.chop

fb_b = 0
fb_r = 0
fr_b = 0
fr_r = 0

i = 0;
word.chars.each_with_index do |x, i|
    if i.even?
        if x == 'b'
             fr_b += 1
        elsif x == 'r'
            fb_r += 1
        end
    else
        if x == 'b'
            fb_b += 1
        elsif x == 'r'
            fr_r += 1
        end
    end
end

puts min(max(fb_b, fb_r), max(fr_b, fr_r))

gets; s = gets.chomp
def min1(s,k)
  r = b = i = 0
  s.chars{ |c|
    r +=1 if c==?r and i%2 == k
    b +=1 if c==?b and i%2 != k
    i += 1
  }
  x,y = [r,b].minmax
  y-x+x
end
puts [min1(s,0), min1(s,1)].min

def func(s, k)
    r=b=i=0
    s.chars{|c|
        r+=1 if c==?r and i%2==k
        b+=1 if c==?b and i%2!=k
        i+=1
    }
    x, y=[r, b].minmax
    y-x+x
end

gets
s=gets.chomp
puts [func(s, 0), func(s, 1)].min

def func(n, s, k)
    r=b=i=0
    s.chars{|c|
        r+=1 if c==?r and i%2==k
        b+=1 if c==?b and i%2!=k
        i+=1
    }
    x, y=[r, b].minmax
    y-x+x
end

n=gets.to_i
s=gets.chomp
puts [func(n, s, 0), func(n, s, 1)].min

#!/usr/local/rvm/rubies/ruby-2.3.0/bin/ruby

class Task2
  attr_accessor :cockroach, :n, :result

  def initialize()
    @n=0
    @cockroach = []
    @result = 0
  end

  def getData()
    ln=$stdin.readline
    @n=ln.chomp.to_i
    tmp=$stdin.readline
    @cockroach = tmp.chomp
  end

  def getFileData()
    file = File.new("test.txt","r")
    ln=file.readline
    @n=ln.chomp.to_i
    tmp=file.readline
    @cockroach = tmp.chomp
  end

  def getResult()
    @result = getSubResult()
    if @n%2 == 1
      @cockroach=@cockroach.reverse
      result = getSubResult()
      @result=[@result,result].min
    end
  end

  def getSubResult()
    result=0
    cnt={rr:0,rb:0,br:0,bb:0}
    (0..@n/2-1).each {|x| cnt[@cockroach[x*2..x*2+1].to_sym]+=1} if @n>1
    # print cnt
    # puts
    # exit(0)
    result = (cnt[:br]>cnt[:rb]) ? cnt[:rb]: cnt[:br]
    lst = (cnt[:br]>cnt[:rb]) ? 'r': 'b'
    result+=[cnt[:rr],cnt[:bb]].min
    delta = [cnt[:rr],cnt[:bb]].max-[cnt[:rr],cnt[:bb]].min
    result+=delta
    result+= (@n%2==1 && @cockroach[@n-1]==lst)?1:0  if cnt[:br]+cnt[:rb]>0
    return result
  end

  def printResult()
    puts @result
  end

  def run()
    if ARGV[0] == 'DEBUG'
      getFileData
    else
      getData
    end
    # print @n
    # print @cockroach
    # puts
    getResult
    printResult
  end

end
if __FILE__ == $0
  pc = Task2.new
  pc.run
end

n = gets.chomp.to_i
colors = gets.chomp.split('')

if n == 1
	puts 0
	exit
end

def getA colors, init
current = init

bWrong = []
rWrong = []

for i in (0...colors.length)
	if current == colors[i]
		bWrong << i if current == 'b'
		rWrong << i if current == 'r'

		current = 'r' if colors[i] == 'b'
		current = 'b' if colors[i] == 'r'
	else
		current = colors[i]
	end
end

swap = 0
change = 0

bWrongSize = bWrong.length
rWrongSize = rWrong.length

until bWrongSize == 0 || rWrongSize == 0
	bWrongSize -= 1
	rWrongSize -= 1
	swap += 1
end

change = bWrongSize + rWrongSize

return swap + change
end

forward = getA colors, 'r'
backward = getA colors, 'b'

#puts forward
#puts backward

puts [forward, backward].min

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

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

c = gets.chop.to_i
word = gets.chop

bfb = 0
bfr = 0
rfr = 0
rfb = 0

i = 0;
while i < word.size
    if i.even?
        if word[i] == 'b'
            rfr += 1
        elsif word[i] == 'r'
            bfr += 1
        end
    else
        if word[i] == 'b'
            bfr += 1
        elsif word[i] == 'r'
            rfb += 1
        end
    end
    i += 1
end

puts min(max(bfb, bfr), max(rfr, rfb))

c = gets.chop.to_i
word = gets.chop

cnt = { 'r' => 0, 'b' => 0 }

i = 0;
while i < word.size - 1
    if word[i] == word[i+1]
        #puts i
        if i + 2 < word.size && word[i+1] != word[i]
            word[i+1], word[i+2] = word[i+2], word[i+1]
        elsif i + 2 < word.size
            cnt[word[i]] += 1
        else
            cnt[word[i]] += 1
        end
        i += 2
    else
        i += 1
    end
end

puts (cnt['r'] > cnt['b']) ? cnt['r'] : cnt['b']

c = gets.chop.to_i
word = gets.chop

cnt = { 'r' => 0, 'b' => 0 }

k = 0

i = 0;
while i < word.size - 1
    if word[i] == word[i+1]
        #puts i
        if i + 2 < word.size && word[i+1] != word[i+2]
            word[i+1], word[i+2] = word[i+2], word[i+1]
            k += 1
            i += 2
        elsif i + 2 < word.size && word[i+1] == word[i+2]
            cnt[word[i]] += 1
            i += 3
        else
            cnt[word[i]] += 1
            i += 2
        end
    else
        i += 1
    end
end

puts ((cnt['r'] > cnt['b']) ? cnt['r'] : cnt['b']) + k

c = gets.chop.to_i
word = gets.chop

cnt = { 'r' => 0, 'b' => 0 }

k = 0

i = 0;
while i < word.size - 1
    if word[i] == word[i+1]
        #puts i
        if i + 2 < word.size && word[i+1] != word[i+2]
            word[i+1], word[i+2] = word[i+2], word[i+1]
            k += 1
            i += 2
        elsif i + 2 < word.size && word[i+1] == word[i+2]
            cnt[word[i]] += 1
            i += 2
        else
            cnt[word[i]] += 1
            i += 2
        end
    else
        i += 1
    end
end

puts ((cnt['r'] > cnt['b']) ? cnt['r'] : cnt['b']) + k

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

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

c = gets.chop.to_i
word = gets.chop

bfb = 0
bfr = 0
rfr = 0
rfb = 0

i = 0;
while i < word.size
    if i % 2 == 0
        if word[i] == 'b'
            rfr += 1
        elsif word[i] == 'r'
            bfr += 1
        end
    else
        if word[i] == 'b'
            bfr += 1
        elsif word[i] == 'r'
            rfb += 1
        end
    end
    i += 1
end

puts min(max(bfb, bfr), max(rfr, rfb))

c = gets.chop.to_i
word = gets.chop

cnt = { 'r' => 0, 'b' => 0 }

k = 0

i = 0;
while i < word.size - 1
    if word[i] == word[i+1]
        #puts i
        if i + 2 < word.size && word[i+1] != word[i+2]
            word[i+1], word[i+2] = word[i+2], word[i+1]
            k += 1
        elsif i + 2 < word.size
            cnt[word[i]] += 1
        else
            cnt[word[i]] += 1
        end
        i += 2
    else
        i += 1
    end
end

puts ((cnt['r'] > cnt['b']) ? cnt['r'] : cnt['b']) + k

c = gets.chop.to_i
word = gets.chop

cnt = { 'r' => 0, 'b' => 0 }

k = 0

i = 0;
while i < word.size - 1
    if word[i] == word[i+1]
        #puts i
        if i + 2 < word.size && word[i+1] != word[i+2]
            word[i+1], word[i+2] = word[i+2], word[i+1]
            k += 1
            i += 2
        elsif i + 2 < word.size && word[i+1] == word[i+2]
            cnt[word[i]] += 1
            i += 3
        else
            cnt[word[i]] += 1
            i += 2
        end
    else
        i += 2
    end
end

puts ((cnt['r'] > cnt['b']) ? cnt['r'] : cnt['b']) + k

def func(n, s, a)
    res=0
    i=0
    while i<n
        if s[i]!=a[i]
            i+=1 if i+1<n and s[i]!=s[i+1]
            res+=1
        end
        i+=1
    end
    res
end

n=gets.to_i
s=gets.chomp
brbr="br"*n
puts [func(n, s, brbr), func(n, s, brbr.reverse!)].min

def func(n, s, b)
    f=[]
    s.each_with_index{|c, i| f<<(c==b[i])}

    res=0
    j=n-1
    s.each_with_index{|c, i|
        unless f[i]
            while j>i
                j-=1
                break if c!=s[j] and !f[j]
            end
            f[j]=true if j>i
            res+=1
        end
    }
    res
end

n=gets.to_i
s=gets.chomp.chars
brbr="br"*n
puts [func(n, s, brbr), func(n, s, brbr.reverse)].min

n = gets.chomp.to_i
colors = gets.chomp.split('')

if n == 1
	puts 0
	exit
end

current = colors[0]

bWrong = []
rWrong = []

for i in (1...colors.length)
	if current == colors[i]
		bWrong << i if current == 'b'
		rWrong << i if current == 'r'

		current = 'r' if colors[i] == 'b'
		current = 'b' if colors[i] == 'r'
	else
		current = colors[i]
	end
end

swap = 0
change = 0

bWrongSize = bWrong.length
rWrongSize = rWrong.length

until bWrongSize == 0 || rWrongSize == 0
	bWrongSize -= 1
	rWrongSize -= 1
	swap += 1
end

change = bWrongSize + rWrongSize

forward = swap + change

current = colors[colors.length - 1]
bWrong = []
rWrong = []

(colors.length - 2).downto(0).each do |i|
	if current == colors[i]
		bWrong << i if current == 'b'
		rWrong << i if current == 'r'

		current = 'r' if colors[i] == 'b'
		current = 'b' if colors[i] == 'r'
	else
		current = colors[i]
	end
end

swap = 0
change = 0

bWrongSize = bWrong.length
rWrongSize = rWrong.length

until bWrongSize == 0 || rWrongSize == 0
	bWrongSize -= 1
	rWrongSize -= 1
	swap += 1
end

change = bWrongSize + rWrongSize
backward = swap + change

puts [forward, backward].min

n = gets.chomp.to_i
colors = gets.chomp.split('')

if n == 1
	puts 0
	exit
end

def getA colors, init
current = init

bWrong = []
rWrong = []

for i in (1...colors.length)
	if current == colors[i]
		bWrong << i if current == 'b'
		rWrong << i if current == 'r'

		current = 'r' if colors[i] == 'b'
		current = 'b' if colors[i] == 'r'
	else
		current = colors[i]
	end
end

swap = 0
change = 0

bWrongSize = bWrong.length
rWrongSize = rWrong.length

until bWrongSize == 0 || rWrongSize == 0
	bWrongSize -= 1
	rWrongSize -= 1
	swap += 1
end

change = bWrongSize + rWrongSize

return swap + change
end

forward = getA colors, 'r'
backward = getA colors, 'b'

puts [forward, backward].min

n = gets.chomp.to_i
colors = gets.chomp.split('')

current = colors[0]

bWrong = []
rWrong = []

for i in (1...colors.length)
	if current == colors[i]
		bWrong << i if current == 'b'
		rWrong << i if current == 'r'

		current = 'r' if colors[i] == 'b'
		current = 'b' if colors[i] == 'r'
	else
		current = colors[i]
	end
end

swap = 0
change = 0

bWrongSize = bWrong.length
rWrongSize = rWrong.length

until bWrongSize == 0 || rWrongSize == 0
	bWrongSize -= 1
	rWrongSize -= 1
	swap += 1
end

change = bWrongSize + rWrongSize

puts swap + change


You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.

The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.

Print a number in the decimal notation without leading zeroes — the result of the permutation. If it is impossible to rearrange the digits of the number a in the required manner, print 0.

require 'scanf'
STDIN.read.split("\n").each do |line|
	num = line
	zeros_count = num.count('0')
	num = num.tr("0", '')
	num = num.sub("1", '')
	num = num.sub("6", '')
	num = num.sub("8", '')
	num = num.sub("9", '')
	num = "" if num == "0"
	reminder = 0
	num.split('').each do |digit|
		reminder *= 10
		reminder += digit.to_i
		reminder %= 7
	end
	reminder = reminder * 10000 % 7
	permutation = case reminder
		when 0
			"8169"
		when 1
			"8196"
		when 2
			"9861"
		when 3
			"8691"
		when 4
			"6891"
		when 5
			"1689"
		when 6
			"6189"
		end
	puts num + permutation + "0" * zeros_count
end

require 'scanf'
STDIN.read.split("\n").each do |line|
	num = line
	zeros_count = num.count('0')
	num = num.tr("0", '')
	num = num.sub("1", '')
	num = num.sub("6", '')
	num = num.sub("8", '')
	num = num.sub("9", '')
	num = "" if num == "0"
	num = num + "0000"
	reminder = 0
	num.split('').each do |digit|
		reminder *= 10
		reminder += digit.to_i
		reminder %= 7
	end
	permutation = case reminder
		when 0
			"8169"
		when 1
			"8196"
		when 2
			"9861"
		when 3
			"8691"
		when 4
			"6891"
		when 5
			"1689"
		when 6
			"6189"
		end
	puts num + permutation + "0" * zeros_count
end


Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling.  It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.

For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.

NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).

tc=gets.to_i

ans=[]

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

    h=Hash.new(0)

    a.each do |x|
        h[x]+=1
    end

    mx=h.each_value.max
    cnt=h.each_value.count(mx)

    if cnt==1
        ans<< ((n-mx)/(mx-1))
    elsif mx==2
        ans<< n-cnt-1

    else
        dis=n-cnt-1
        rest=dis-(mx-2)
        ans<< rest/(mx-1)
    end
end

ans.each do|x|
    puts x
end

t = gets.to_i
ans = []
t.times do |i|
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  hash = Hash.new(0)
  a.each do |x|
    hash[x] += 1
  end
  max = hash.each_value.max
  num = hash.each_value.count(max)
  if num == 1
    ans << ((n-max) / (max-1))
  elsif max == 2
    ans << n - num - 1
  else
    dis = n - num - 1
    rest = (dis - (max - 2))
    ans << rest / (max-1)
  end
end
ans.each do |x|
  puts x
end


Phoenix is playing with a new puzzle, which consists of $$$n$$$ identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below.    A puzzle piece The goal of the puzzle is to create a square using the $$$n$$$ pieces. He is allowed to rotate and move the pieces around, but none of them can overlap and all $$$n$$$ pieces must be used (of course, the square shouldn't contain any holes as well). Can he do it?

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the number of puzzle pieces.

For each test case, if Phoenix can create a square with the $$$n$$$ puzzle pieces, print YES. Otherwise, print NO.

NoteFor $$$n=2$$$, Phoenix can create a square like this:    For $$$n=4$$$, Phoenix can create a square like this:    For $$$n=6$$$, it is impossible for Phoenix to create a square.

def solve(n)
  while true
    return true if n == 2
    return false if n % 2 == 1
    n >>= 1
    sqrtn = Integer.sqrt(n)
    return true if sqrtn * sqrtn == n
  end
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  printf("%s\n", solve(n) ? "YES" : "NO")
end

Integer(gets.chomp).times{
    n = Integer(gets.chomp)
    if(n%2 == 1)
        puts "NO"
        next
    else
        sq4 = Float(1)
        isq4 = 0
        if(n%4 == 0)
            sq4 = Math.sqrt(n/4)
            isq4 = Integer(sq4)
        end
        sq2 = Math.sqrt(n/2)
        isq2 = Integer(sq2)

        puts (sq2 == isq2 || sq4 == isq4) ? "YES" : "NO"
    end
}

def solve(n)
  return true if n == 2
  while true
    return false if n % 2 == 1
    sqrtn = Integer.sqrt(n)
    return true if sqrtn * sqrtn == n
    n >>= 1
  end
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  printf("%s\n", solve(n) ? "YES" : "NO")
end

def solve(n)
  while true
    return true if n == 2
    return false if n % 2 == 1
    sqrtn = Integer.sqrt(n)
    return true if sqrtn * sqrtn == n
    n >>= 1
  end
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  printf("%s\n", solve(n) ? "YES" : "NO")
end


Walking along a riverside, Mino silently takes a note of something."Time," Mino thinks aloud."What?""Time and tide wait for no man," explains Mino. "My name, taken from the river, always reminds me of this.""And what are you recording?""You see it, tide. Everything has its own period, and I think I've figured out this one," says Mino with confidence.Doubtfully, Kanno peeks at Mino's records. The records are expressed as a string $$$s$$$ of characters '0', '1' and '.', where '0' denotes a low tide, '1' denotes a high tide, and '.' denotes an unknown one (either high or low).You are to help Mino determine whether it's possible that after replacing each '.' independently with '0' or '1', a given integer $$$p$$$ is not a period of the resulting string. In case the answer is yes, please also show such a replacement to Mino.In this problem, a positive integer $$$p$$$ is considered a period of string $$$s$$$, if for all $$$1 \leq i \leq \lvert s \rvert - p$$$, the $$$i$$$-th and $$$(i + p)$$$-th characters of $$$s$$$ are the same. Here $$$\lvert s \rvert$$$ is the length of $$$s$$$.

The first line contains two space-separated integers $$$n$$$ and $$$p$$$ ($$$1 \leq p \leq n \leq 2000$$$) — the length of the given string and the supposed period, respectively. The second line contains a string $$$s$$$ of $$$n$$$ characters — Mino's records. $$$s$$$ only contains characters '0', '1' and '.', and contains at least one '.' character.

Output one line — if it's possible that $$$p$$$ is not a period of the resulting string, output any one of such strings; otherwise output "No" (without quotes, you can print letters in any case (upper or lower)).

NoteIn the first example, $$$7$$$ is not a period of the resulting string because the $$$1$$$-st and $$$8$$$-th characters of it are different.In the second example, $$$6$$$ is not a period of the resulting string because the $$$4$$$-th and $$$10$$$-th characters of it are different.In the third example, $$$9$$$ is always a period because the only constraint that the first and last characters are the same is already satisfied.Note that there are multiple acceptable answers for the first two examples, you can print any of them.

# https://codeforces.com/problemset/problem/989/B
def check_possible(records, p)
  len = records.size
  return 'No' if len == 1

  0.upto(len - p - 1) do |i|
    end_idx = i + p

    if records[i] == '.' || records[end_idx] == '.'
      s_v, e_v = get_solution(records, i, end_idx)
      ret = records.dup
      ret[i] = s_v
      ret[end_idx] = e_v
      replace(ret)
      return ret
    end

    if records[i] != records[end_idx]
      replace(records)
      return records
    end
  end

  'No'
end

def replace(records)
  0.upto(records.size - 1) do |i|
    records[i] = '0' if records[i] == '.'
  end
end

def get_solution(records, start_idx, end_idx)
  if records[start_idx] == '.' && records[end_idx] == '.'
    return ['0', '1']
  end

  if records[start_idx] == '.'
    start = records[end_idx] == '0' ? '1' : '0'
    return [start, records[end_idx]]
  end

  [records[start_idx], records[start_idx] == '0' ? '1' : '0']
end

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

puts check_possible(records, p)

def bnot(a)
  a == '0' ? '1' : '0'
end

n, p = gets.split.map(&:to_i)
s = gets.chomp
fuck = false
n.times do |i|
  if i < n - p
    if s[i] == '.' and s[i+p] == '.'
      s[i] = '0'
      s[i+p] = '1'
      fuck = true
    elsif s[i] == '.'
      s[i] = bnot s[i+p]
      fuck = true
    elsif s[i+p] == '.'
      s[i+p] = bnot s[i]
      fuck = true
    elsif s[i] != s[i+p]
      fuck = true
    end
  elsif s[i] == '.'
    s[i] = '0'
  end
end

if fuck
  puts s
else
  puts :No
end


Polycarp has come up with a new game to play with you. He calls it "A missing bigram".A bigram of a word is a sequence of two adjacent letters in it.For example, word "abbaaba" contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba".The game goes as follows. First, Polycarp comes up with a word, consisting only of lowercase letters 'a' and 'b'. Then, he writes down all its bigrams on a whiteboard in the same order as they appear in the word. After that, he wipes one of them off the whiteboard.Finally, Polycarp invites you to guess what the word that he has come up with was.Your goal is to find any word such that it's possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with.The tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the length of the word Polycarp has come up with. The second line of each testcase contains $$$n-2$$$ bigrams of that word, separated by a single space. Each bigram consists of two letters, each of them is either 'a' or 'b'. Additional constraint on the input: there exists at least one string such that it is possible to write down all its bigrams, except one, so that the resulting sequence is the same as the sequence in the input. In other words, the answer exists.

For each testcase print a word, consisting of $$$n$$$ letters, each of them should be either 'a' or 'b'. It should be possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with. The tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them.

4
7
ab bb ba aa ba
7
ab ba aa ab ba
3
aa
5
bb ab bb

NoteThe first two testcases from the example are produced from the word "abbaaba". As listed in the statement, it contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba".In the first testcase, the $$$5$$$-th bigram is removed. In the second testcase, the $$$2$$$-nd bigram is removed. However, that sequence could also have been produced from the word "abaabaa". It contains bigrams "ab", "ba", "aa", "ab", "ba" and "aa". The missing bigram is the $$$6$$$-th one.In the third testcase, all of "baa", "aab" and "aaa" are valid answers.

gets.to_i.times do
  n = gets.to_i
  s = ''

  gets.strip.split.each do |big|
    a, b = big.chars

    if s.empty?
      s = big
      next
    end

    if s[-1] == a
      s += b
      next
    end

    s += big
  end

  if s.size < n
    s += 'b'
  end

  puts s
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  s = gets.split(" ")
  str = [s[0][0],s[0][1]]
  s[1..].each do |v|
    if str[-1] == v[0]
      str << v[1]
    else
      str << v[0]
      str << v[1]
    end
  end
  if str.size != n
    str << "a"
  end
  ans << str
end
ans.each do |v|
  puts v.join
end

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

for i in 0..testcases-1
    n = Integer(gets.chomp)
    arreglo = gets.chomp
    bigram = arreglo.split(" ")
    longitudTotal = bigram.length * 2
    if longitudTotal >= n
        letrasAQuitar = longitudTotal - n
        for j in 0..bigram.length-2
            if letrasAQuitar == 0
                break
            end
            bigram1 = bigram[j]
            bigram2 = bigram[j+1]
            if bigram1.length == 1
                if bigram1[0] == bigram2[0]
                    bigram[j+1] = bigram2[1]
                    letrasAQuitar -= 1
                end
            else
                if bigram1[1] == bigram2[0]
                    bigram[j+1] = bigram2[1]
                    letrasAQuitar -= 1
                end
            end
        end
    else
        letrasAAgregar = n-longitudTotal
        for j in 1..letrasAAgregar
            bigram[bigram.length-1] += "a"
        end
    end
    string = ""
    for j in 0..bigram.length-1
        string += bigram[j]
    end
    resultados.push(string)
end
puts resultados


There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.

If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.

NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
seq = gets.split(//)[0...-1].map { |c| c == 'B' ? 0 : 1 }
stand = seq[0]

i = 0
flipIdx = []
maximumTries = seq.length * 3
maximumIdx = seq.length - 1 - 1
while flipIdx.length <= maximumTries
    if seq[i] != stand
        seq[i] ^= 1
        seq[i+1] ^= 1
        flipIdx << i+1 # 1-based index
    end

    if i == maximumIdx
        if seq.count(stand) != seq.length
            stand ^= 1
            i = 0
        else
            break
        end
    else
        i += 1
    end
end

if flipIdx.length > maximumTries || seq.count(stand) != seq.length
    # puts flipIdx.length
    # puts flipIdx.join ' '
    # p seq
    puts -1
else
    puts flipIdx.length

    if flipIdx.length > 0
        puts flipIdx.join ' '
    end
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 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=gi
s=gs

putsend(0) if s.count('W')==n||s.count('B')==n

ans=[]
# Wにする
(n-1).times do |i|
  if s[i]!='W'
    s[i]='W'
    ans<<i+1
    #反転
    if s[i+1]=='W'
      s[i+1]='B'
    else
      s[i+1]='W'
    end
  end
end
if s[n-1]==s[n-2]
  puts ans.size
  putsend(ans.join(" "))
end

# Bにする
(n-1).times do |i|
  if s[i]!='B'
    s[i]='B'
    ans<<i+1
    #反転
    if s[i+1]=='W'
      s[i+1]='B'
    else
      s[i+1]='W'
    end
  end
end
if s[n-1]==s[n-2]
  puts ans.size
  putsend(ans.join(" "))
end
puts -1

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
seq = gets.split(//)[0...-1].map { |c| c == 'B' ? 0 : 1 }

if seq.count(0) == seq.length || seq.count(1) == seq.length
    puts 0
else
    i = 0
    flipIdx = []
    stand = seq[0] ^ 1 # first flipping always occurs
    maximumTries = seq.length * 3
    while i < seq.length-1 && flipIdx.length <= maximumTries
        if seq[i] != stand
            seq[i] ^= 1
            seq[i+1] ^= 1
            flipIdx << i+1 # 1-based index
        end

        if seq[i] == seq[i+1]
            i += 2
        else
            i += 1
        end
    end

    if flipIdx.length > maximumTries || seq.count(stand) != seq.length
        puts -1
    else
        puts flipIdx.length
        puts flipIdx.join ' '
    end
end


Carol is currently curling.She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100.She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.

The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.

Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if  for all coordinates.

NoteThe final positions of the disks will look as follows:  In particular, note the position of the last disk.

x = gets.chomp.split(' ')
n = x[0].to_i
r = x[1].to_i
arr = gets.chomp.split(' ')
ans = []
for i in (0...n)
  ans.push(r)
  arr[i] = arr[i].to_i
  for j in (0...i)
    if (arr[i] - arr[j]).abs <= 2 * r
      x = ans[j] + (4 * r * r - (arr[i] - arr[j]) ** 2) ** 0.5
      if(x > ans[i])
        ans[i] = x
      end
    end
  end
  printf("%.12f ", ans[i])
end

def puta ary

  n = ary.size
  # p n
  n.times do |i|
    print ary[i]
    print i == n - 1 ? "\n" : " "
  end
end

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

y = Array.new(n, r)

n.times do |i|

  tmp = r
  (0...i).each do |j|

    dx = ( x[i] - x[j] ).abs
    next if dx > 2 * r
    tmp = y[j] +  ( (2*r)**2 - dx**2 ) ** 0.5

    y[i] = tmp if y[i] < tmp
    # p [j, tmp] if i == 25
  end
end

puta y

def puta ary

  n = ary.size
  n.times do |i|
    print ary[i]
    print i == n - 1 ? "\n" : " "
  end
end

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

y = Array.new(n, r)

n.times do |i|

  tmp = r
  (0...i).each do |j|

    dx = ( x[i] - x[j] ).abs
    next if dx > 2 * r
    tmp = y[j] +  ( (2*r)**2 - dx**2 ) ** 0.5

  end

  y[i] = [ y[i], tmp ].max

end

puta y


Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number , in particular that q2 = q + 1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression a0a1...an equals to .Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.Given two numbers written in golden system notation, determine which of them has larger decimal value.

Input consists of two lines — one for each number. Each line contains non-empty string consisting of '0' and '1' characters. The length of each string does not exceed 100000.

Print ">" if the first number is larger, "<" if it is smaller and "=" if they are equal.

NoteIn the first example first number equals to , while second number is approximately 1.6180339882 + 1.618033988 + 1 ≈ 5.236, which is clearly a bigger number.In the second example numbers are equal. Each of them is  ≈ 2.618.


The process of mammoth's genome decoding in Berland comes to its end!One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.

The first line contains the integer n (4 ≤ n ≤ 255) — the length of the genome. The second line contains the string s of length n — the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.

If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).

NoteIn the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.In the third and the fourth examples it is impossible to decode the genom.

n=gets.to_i
s=gets.chomp
h=Hash.new 0
g=Hash.new n/4
s.each_char{|c|h[c]+=1 if c!='?'}
if n%4>0||h.any?{|k,v|g[k]-=v;v>n/4}
puts '==='
exit
end
s.each_char{|c|
if c!='?'
print c
else
x='ATGC'.chars.find{|x|g[x]>0}
g[x]-=1
print x
end
}
puts

n = gets.to_i
s = gets.chomp.split('')
if n % 4 != 0
  puts '==='
  exit
end
h = {}
['A', 'G', 'C', 'T'].each { |x| h[x] = 0 }
s.each do |x|
  h[x] += 1 if x != '?'
end
if h.values.any? { |m| m > n / 4 }
  puts '==='
  exit
end
ss = s.map do |x|
  if x != '?'
    x
  else
    y = h.keys.find { |z| h[z] < n / 4 }
    h[y] += 1
    y
  end
end
puts ss.join('')

n = gets
s = gets

if n.to_i() % 4 > 0
  puts("===")
else
  a = s.count("A")
  t = s.count("T")
  c = s.count("C")
  g = s.count("G")

  if a.to_i() > n.to_i() / 4 || t.to_i() > n.to_i() / 4 || c.to_i() > n.to_i() / 4 || g.to_i() > n.to_i() / 4
    puts("===")
  else
    while a < n.to_i() / 4
      s[s.index('?')] = 'A'
      a += 1
    end

    while t < n.to_i() / 4
      s[s.index('?')] = 'T'
      t += 1
    end

    while c < n.to_i() / 4
      s[s.index('?')] = 'C'
      c += 1
    end

    while g < n.to_i() / 4
      s[s.index('?')] = 'G'
      g += 1
    end

    puts(s)
  end
end

CODES = ['A', 'G', 'C', 'T']

def count(code)
  result = {'A'=> 0, 'G'=> 0, 'C'=> 0, 'T'=> 0, '?'=> 0}
  code.each_char{|c| result[c]+=1}
  return result
end

def eval(code)
  max = code.length/4
  count(code).all? { |ch, cnt|
    ch == '?' || cnt <= max
  }
end

def find(code)
  return nil if !eval(code)
  i = code.index('?')
  if i.nil?
    return code
  else
    for ch in CODES
      copy = code.dup
      copy[i] = ch
      result = find(copy)
      return result if result
    end
    return nil
  end
end

def solve(n, code)
  return "===" if n < 4 || n%4 != 0
  find(code) || "==="
end

puts solve(STDIN.readline.to_i, STDIN.readline.chomp)

a2 = gets.to_i
str = gets.to_s
count_a = count_g = count_c = count_t = 0
for i in 0..a2-1
  e = str[i]
  a = e.ord
  if (a==65)
    count_a = count_a + 1
  end
  if (a==67)
    count_c = count_c + 1
  end
  if (a==71)
    count_g = count_g + 1
  end
  if (a==84)
    count_t = count_t + 1
  end
end
count_q = a2 - (count_a + count_c + count_g + count_t)
no = a2 / 4

if (a2%4 !=0)||(count_a > no) || (count_c > no) || (count_g > no) || (count_t > no) || ((count_a + count_c + count_g + count_t) > a2)
  print("===")
  flag = 1
elsif count_q == 0
  print str
  flag = 1
end

if (flag != 1)
  count_a = -count_a + no
  count_g = -count_g + no
  count_c = -count_c + no
  count_t = -count_t + no

  stack = Array.new
  for i in 1..count_a
    stack.push("A")
  end
  for i in 1..count_g
    stack.push("G")
  end
  for i in 1..count_c
    stack.push("C")
  end
  for i in 1..count_t
    stack.push("T")
  end
  k =0
  for i in 0..a2-1
    a= str[i].ord
    if (a==63)
      str[i]=stack[k]
      k = k+1
    end
  end
  puts str
end

n=gets.to_i
s=gets.chomp

c=[0]*128
s.bytes{|e|c[e]+=1}

for i in 0..n-1
    if s[i]==??
        "AGCT".bytes{|e|
            if c[e]<n/4
                s[i]=e.chr
                c[e]+=1
                break
            end
        }
    end
end

c=[0]*128
s.bytes{|e|c[e]+=1}
puts ((n%4>0 or c.uniq!=[0,n/4]) ? "===" : s)

class Genome
  attr_reader(:gen)
  def initialize(gen)
    @gen = gen.split("")
    @memo = Hash[
      "A" => 0,
      "C" => 0,
      "G" => 0,
      "T" => 0
    ]
  end

  def length
    @length ||= gen.length
  end

  def gcount
    length / 4
  end

  def _gen_count
    gen.each do |i|
      if(i != "?")
        @memo[i] += 1
      end
    end
    @memo
  end

  def gen_count
    @gen_count ||= _gen_count
  end

  def max_gen_count
    @max_gen_count ||= gen_count.map{|k, v| v}.max
  end

  def possible?
    return false if gen.length % 4 != 0
    @possible ||= max_gen_count <= gcount
  end

  def _solver
    @_solver = []
    gen_count.each do |k, v|
      if(v < gcount)
        (1..(gcount - v)).each{ @_solver << (k) }
      end
    end
    return @_solver
  end

  def solver
    @solver ||= _solver
  end

  def solutions
    return "===" unless possible?
    @solutions = []
    i = 0
    gen.each do |g|
      if(g == "?")
        @solutions << solver[i];
        i += 1
      else
        @solutions << g
      end
    end
    @solutions.join("")
  end

end

gets
puts Genome.new(gets.strip).solutions

def miss
  puts "==="
  exit 0
end

n=gets.to_i
s=gets.chomp
if n % 4 != 0
  miss
end
inv_t={'A'=>0,'G'=>1,'C'=>2,'T'=>3,'?'=>4}
t='AGCT?'.split('')
freq=Array.new(5, 0)
s.split('').each {|c|
  freq[inv_t[c]] += 1
}
(0 .. 3).each {|i|
  if freq[i] > n / 4
    miss
  end
}
(0 ... n).each {|i|
  if s[i] == '?'
    for j in 0 .. 3
      if freq[j] < n / 4
        s[i] = t[j]
        freq[j] += 1
        break
      end
    end
  end
}
puts s

CODES = ['A', 'G', 'C', 'T']

def count(code)
  result = {'A'=> 0, 'G'=> 0, 'C'=> 0, 'T'=> 0, '?'=> 0}
  code.each_char{|c| result[c]+=1}
  return result
end

def eval(code)
  max = code.length/4
  count(code).all? { |ch, cnt|
    ch == '?' || cnt <= max
  }
end

def find(code)
  return nil if !eval(code)
  i = code.index('?')
  if i.nil?
    return code
  else
    for ch in CODES
      copy = code.dup
      copy[i] = ch
      result = find(copy)
      return result if result
    end
    return nil
  end
end

def solve(n, code)
  return "===" if n < 4 || n%4 != 0
  find(code)
end

puts solve(STDIN.readline.to_i, STDIN.readline.chomp)

n=gets.to_i
s=gets.chomp

c=[0]*128
s.bytes{|e|c[e]+=1}

for i in 0..n-1
    if s[i]==??
        "AGCT".bytes{|e|
            if c[e]<n/4
                s[i]=e.chr
                c[e]+=1
                break
            end
        }
    end
end

c=[0]*128
s.bytes{|e|c[e]+=1}
puts (n%4>0 or c.uniq!=[0,n/4] ? "===" : s)

n=gets.to_i
s=gets.chomp

c=[0]*128
s.bytes{|e|c[e]+=1}

for i in 0..n-1
    if s[i]==??
        "AGCT".bytes{|e|
            if c[e]<n/4
                s[i]=e.chr
                c[e]+=1
                break
            end
        }
    end
end

c=[0]*128
s.bytes{|e|c[e]+=1}
puts (c.uniq.size>2 ? "===" : s)

n=gets.to_i
c=[0]*128
s=gets.chomp
s.bytes{|e|c[e]+=1}
m=0
"AGCT".bytes{|e|m=c[e] if m<c[e]}
d=0
"AGCT".bytes{|e|d+=m-c[e]}

if c[??.ord]!=d
    puts "==="
else
    for i in 0..n-1
        if s[i]==??
            "AGCT".bytes{|e|
                if c[e]<m
                    s[i]=e.chr
                    c[e]+=1
                    break
                end
            }
        end
    end
    puts s
end

n=gets.to_i
c=[0]*128
s=gets.chomp
s.bytes{|e|c[e]+=1}
m=0
"AGCT".bytes{|e|m=c[e] if m<c[e]}
d=0
"AGCT".bytes{|e|d+=m-c[e]}

if n%4>0 or (m>0 and c[??.ord]!=d)
    puts "==="
else
    m=n/4 if m==0
    for i in 0..n-1
        if s[i]==??
            "AGCT".bytes{|e|
                if c[e]<m
                    s[i]=e.chr
                    c[e]+=1
                    break
                end
            }
        end
    end
    puts s
end

n=gets.to_i
s=gets.chomp

c=[0]*128
s.bytes{|e|c[e]+=1}

for i in 0..n-1
    if s[i]==??
        "AGCT".bytes{|e|
            if c[e]<n/4
                s[i]=e.chr
                c[e]+=1
                break
            end
        }
    end
end

c=[0]*128
s.bytes{|e|c[e]+=1}
puts (c.uniq!=[0,n/4] ? "===" : s)

class Genome
  attr_reader(:gen)
  def initialize(gen)
    @gen = gen.split("")
    @memo = Hash[
      "A" => 0,
      "C" => 0,
      "G" => 0,
      "T" => 0
    ]
  end

  def length
    @length ||= gen.length
  end

  def gcount
    length / 4
  end

  def _gen_count
    gen.each do |i|
      if(i != "?")
        @memo[i] += 1
      end
    end
    @memo
  end

  def gen_count
    @gen_count ||= _gen_count
  end

  def max_gen_count
    @max_gen_count ||= gen_count.map{|k, v| v}.max
  end

  def possible?
    @possible ||= max_gen_count <= gcount
  end

  def _solver
    @_solver = []
    gen_count.each do |k, v|
      if(v < gcount)
        (1..(gcount - v)).each{ @_solver << (k) }
      end
    end
    return @_solver
  end

  def solver
    @solver ||= _solver
  end

  def solutions
    return "===" unless possible?
    @solutions = []
    i = 0
    gen.each do |g|
      if(g == "?")
        @solutions << solver[i];
        i += 1
      else
        @solutions << g
      end
    end
    @solutions.join("")
  end

end

gets
puts Genome.new(gets.strip).solutions


Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $$$1$$$. Each person is looking through the circle's center at the opposite person.    A sample of a circle of $$$6$$$ persons. The orange arrows indicate who is looking at whom. You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $$$c$$$? If, for the specified $$$a$$$, $$$b$$$, and $$$c$$$, no such circle exists, output -1.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a,b,c \le 10^8$$$).

For each test case output in a separate line a single integer $$$d$$$ — the number of the person being looked at by the person with the number $$$c$$$ in a circle such that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$. If there are multiple solutions, print any of them. Output $$$-1$$$ if there's no circle meeting the given conditions.

NoteIn the first test case, there's a desired circle of $$$8$$$ people. The person with the number $$$6$$$ will look at the person with the number $$$2$$$ and the person with the number $$$8$$$ will look at the person with the number $$$4$$$.In the second test case, there's no circle meeting the conditions. If the person with the number $$$2$$$ is looking at the person with the number $$$3$$$, the circle consists of $$$2$$$ people because these persons are neighbors. But, in this case, they must have the numbers $$$1$$$ and $$$2$$$, but it doesn't meet the problem's conditions.In the third test case, the only circle with the persons with the numbers $$$2$$$ and $$$4$$$ looking at each other consists of $$$4$$$ people. Therefore, the person with the number $$$10$$$ doesn't occur in the circle.

def solve(a, b, c)
  n = (a - b).abs
  return -1 if [a, b, c].max > 2 * n
  a -= 1
  b -= 1
  c -= 1
  (c+n) % (2*n) + 1
end

t = gets.chomp.to_i

t.times do
  a, b, c = gets.chomp.split(' ').map(&:to_i)
  puts "#{solve(a, b, c)}\n"
end

MOD = 10 ** 9 + 7
def gs; gets.chomp; end
def gi; gets.to_i; end
def gli; gets.split.map(&:to_i); end
def cyesno(x); puts x ? :Yes : :No; end
def uyesno(x); puts x ? :YES : :NO; end
def array_to_hash_by_count(c); Hash.new(0).tap { |x| c.each { |z| x[z] += 1 } }; end

gets.to_i.times do
  a, b, c = gli
  n = 2 * (a - b).abs
  if n < [a, b, c].max
    puts "-1"
  else
    if c > n / 2
      puts c - n / 2
    else
      puts n / 2+c
    end
  end
end


Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?You can assume that initially Vanya had infinitely many cards with each integer number from  - x to x.

The first line contains two integers: n (1 ≤ n ≤ 1000) — the number of found cards and x (1 ≤ x ≤ 1000) — the maximum absolute value of the number on a card. The second line contains n space-separated integers — the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value.

Print a single number — the answer to the problem.

NoteIn the first sample, Vanya needs to find a single card with number -2.In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value.

card = gets.split(" ").map { |e| e.to_i }
mas = gets.split(" ").map { |e| e.to_i }
sum = 0
mas.map { |e| sum += e }
sum = sum.abs
puts (sum.abs + card[1] - 1) / card[1]

n, m = $stdin.gets.split(' ').map{|e| e.to_i}
cards = $stdin.gets.split(' ').map{|e| e.to_i}

result = (cards.inject(:+).abs.to_f / m).ceil
puts result

first_line = (gets()).split()
second_line = (gets()).split()

found_num = (first_line.shift).to_i
max_abs = (first_line.shift).to_i
num_ary = 0

second_line.each do |c|
	num_ary += c.to_i
end
result = (num_ary).abs / max_abs
if ((num_ary % max_abs) != 0)
	result += 1
end
p result

a=gets.chomp.split(" ")
ans=0.0
b=gets.chomp.split(" ").each {|i|  ans+=i.to_i  }
ans=ans.abs
ans=(ans/a[1].to_i).ceil
puts "#{ans}"

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

def solve(max, cards)
  sum = cards.inject(:+).abs
  div = sum / max
  rem = sum % max
  div += 1 if rem > 0
  div
end

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

if __FILE__ == $0
  puts solve(read_next_line[1], read_next_line)
end

n, x = gets.split.map(&:to_i)
given = gets.split.map(&:to_i)
sum = 0

given.each do |i|
    sum += i
end
ans = sum.abs / Float(x)
ans = ans.ceil
p Integer(ans)

#f = File.open('test1.txt', 'r')
f = STDIN
n, x = f.gets.chomp.split.map &:to_i
sum = f.gets.chomp.split.map(&:to_i).reduce(&:+).abs
puts (sum / x + (sum % x != 0 ? 1 : 0))

ri=->{gets.split.map(&:to_i)}
n,x=ri[]
p (ri[].inject(:+).abs+x-1)/x

n, x = gets.split.map { |x| x.to_i }
sum = gets.split.map { |x| x.to_i }.reduce(:+).abs
puts (sum + x - 1) / x

n, x = gets.split(' ').map(&:to_i)
s = gets.split(' ').map(&:to_i).inject(:+).abs
puts s/x + ( s%x == 0 ? 0 : 1 )

n,x = gets.chomp.split

g = gets.chomp.split

n = n.to_i
x = x.to_i
s = 0

for i in 0...n
  s += g[i].to_i
end

s = s.abs

s = s/x.to_f

s = s.ceil

puts s.to_i

#!/usr/bin/ruby
n,x=gets.split.map(&:to_i)
s=gets.split.map(&:to_i).reduce(:+).abs
p (s+x-1)/x

n, x = gets.chomp.split(" ").map{ |e| e.to_i }
cards = gets.chomp.split(" ").map{ |e| e.to_i }

sum = cards.inject{ |s, i| s += i }.abs
puts (sum.to_f / x.to_f).ceil

def run
  n, x = $stdin.gets.split.map(&:to_i)
  c = $stdin.gets.split.map(&:to_i)
  s = c.reduce(&:+)
  puts (s.abs.to_f / x).ceil
end

run if $0 == __FILE__

n, x = gets.split.map &:to_i
sum = gets.split.map { |x| x.to_i }.inject(:+)
puts (sum.abs/x.to_f).ceil

class A
  def initialize
    n, x = gets.chomp.split(' ').map(&:to_i)

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

    sum = num_list.inject(:+)

    puts (sum.abs/x.to_f).ceil
  end
end

A.new

(n , x) = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
(sum , res) = 0,0
n.times do |i|
  sum += arr[i]
end

sum = sum.abs
if sum != 0
  res += (sum/x) + (sum%x==0?0:1)
end
puts res

n, x = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
sum = a.reduce(:+).abs
p (sum + x - 1) / x

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum != 0 && sum <= @max_abs-1
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs).downto(1) do |elem|
      if sum >= elem
        d = sum / elem
        sum -= elem * d
        count_ret += d
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

n, x = gets.split.map(&:to_i)
as = gets.split.map(&:to_f)

puts (as.inject(:+)/x).abs.ceil

a = readline.split().map {|x| x.to_i}
s = 0
readline.split().map {|i| s += i.to_i}
puts (s.abs + a[1] - 1) / a[1]

n, x = readline.split().map {|i| i.to_i}
s = 0
readline.split().map {|i| s += i.to_i}
puts (s.abs + x - 1) / x

n,x = gets.chomp!.split.map { |e|  e.to_i}

sum = gets.split.collect{|x| x.to_i}.inject{|y, x| y += x}

sum = sum.abs

k = (sum + x -1)/x

p k

n,x = gets.chomp!.split.map { |e|  e.to_i}
sum = gets.split.collect{|x| x.to_i}.inject{|y, x| y += x}
p (sum.abs + x -1)/x

input = gets.chomp
num = input.split
n = Integer(num[0])
x = Integer(num[1])
input2 = gets.chomp
nums= input2.split
card = Array.new
for i in 0...n
    card[i] = Integer(nums[i])
end

sum = 0
for i in 0...n
    sum += card[i]
end
if sum == 0
    puts 0
else
    if sum.abs <= x
        puts 1
    else
        if sum.abs % x == 0
            puts sum.abs / x
        else
            puts sum.abs / x + 1
        end
    end
end

input = gets.chomp
num = input.split
n = Integer(num[0])
x = Integer(num[1])
input2 = gets.chomp
nums= input2.split
card = Array.new
for i in 0...n
    card[i] = Integer(nums[i])
end

sum = 0
for i in 0...n
    sum += card[i]
end
if sum.abs <= x
    puts 1
else
    if sum.abs % x == 0
        puts sum.abs / x
    else
        puts sum.abs / x + 1
    end
end

card = gets.split(" ").map { |e| e.to_i }
mas = gets.split(" ").map { |e| e.to_i }
sum = 0
mas.map { |e| sum += e }
if sum % 2 != 0 then
    sum = sum / 2 + 1
else
    sum = sum / 2
end
puts sum.abs

card = gets.split(" ").map { |e| e.to_i }
mas = gets.split(" ").map { |e| e.to_i }
sum = 0
mas.map { |e| sum += e }
if sum % card[1] != 0 then
    sum = sum / card[1] + 1
else
    sum = sum / card[1]
end
puts sum.abs

def check_pair (pos_ary,neg_ary,surplus_cards)
	if (pos_ary.first and neg_ary.first)
		num = pos_ary.first
		overlap = neg_ary.index(num)
		if overlap
			pos_ary.shift
			neg_ary.delete_at(overlap)
			return check_pair(pos_ary,neg_ary,surplus_cards)
		else
			pos_ary.shift
			surplus_cards += 1
			return check_pair(pos_ary,neg_ary,surplus_cards)
		end
	else
		surplus_cards = pos_ary.length + neg_ary.length
		return surplus_cards
	end
end

first_line = (gets()).split()
second_line = (gets()).split()
pos_cards = []
neg_cards = []

found_num = (first_line.shift).to_i
mux_abs = (first_line.shift).to_i

second_line.each do |c|
	num = c.to_i
	if num > 0
		pos_cards << num
	elsif num < 0
		neg_cards << num
	end
end

p check_pair(pos_cards,neg_cards,0)

n, x = gets.split.map(&:to_i)
given = gets.split.map(&:to_i)
sum = 0

given.each do |i|
    sum += i
end
sum += x - 1
p sum / x

n, x = gets.split.map(&:to_i)
given = gets.split.map(&:to_i)
sum = 0

given.each do |i|
    sum += i
end
p (sum / x).abs.ceil

#f = File.open('test1.txt', 'r')
f = STDIN
n, x = f.gets.chomp.split.map &:to_i
sum = f.gets.chomp.split.map(&:to_i).reduce(&:+).abs
puts (sum / x + sum % x)

#!/usr/bin/ruby
n,x=gets.split.map(&:to_i)
s=gets.split.map(&:to_i).reduce(:+).abs
p (x+s-1)/s

n, x = gets.split.map &:to_i
sum = gets.split.map { |x| x.to_i }.inject(:+)
puts (sum/x).ceil.abs

n, x = gets.split.map &:to_i
sum = gets.split.map { |x| x.to_i }.inject(:+)
puts (sum/x.to_f).ceil.abs

(n , x) = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
print arr
sum = 0
res = 0
n.times do |i|
  sum += arr[i]
end

sum = sum.abs
if sum != 0
  res += (sum/x)+1
end
puts res

(n , x) = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
(sum , res) = 0,0
n.times do |i|
  sum += arr[i]
end

sum = sum.abs
if sum != 0
  res += (sum/x)+1
end
puts res

(n , x) = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
sum = 0
res = 0
n.times do |i|
  sum += arr[i]
end

sum = sum.abs
if sum != 0
  res += (sum%x)+1
end
puts res

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs-1
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs).downto(1) do |elem|
      if sum >= elem
        d = sum / elem
        sum -= elem * d
        count_ret += d
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs-1).downto(1) do |elem|
      if sum > elem
        count_ret += 1
        sum -= elem
      elsif sum == 1
        return count_ret+1
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs-1).downto(1) do |elem|
      if sum >= elem
        count_ret += 1
        sum -= elem
      elsif sum == 1
        return count_ret+1
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs-1).downto(1) do |elem|
      if sum >= elem
        count_ret += 1
        sum -= elem
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs-1
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs-1).downto(1) do |elem|
      if sum >= elem
        d = sum / elem
        sum -= elem * d
        count_ret += d
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs
    return 0 if @max_abs == 0

    count_ret = 0
    @max_abs.downto(1) do |elem|
      if sum > elem
        count_ret += 1
        sum -= elem
      elsif sum == 1
        return count_ret+1
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs-1
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs-1).downto(1) do |elem|
      if sum >= elem
        count_ret += 1
        sum -= elem
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve


Bob has a rectangular chocolate bar of the size W × H. He introduced a cartesian coordinate system so that the point (0, 0) corresponds to the lower-left corner of the bar, and the point (W, H) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parallel to one of the coordinate axes, which connects the edges of the bar. More formally, each break goes along the line x = xc or y = yc, where xc and yc are integers. It should divide one part of the bar into two non-empty parts. After Bob breaks some part into two parts, he breaks the resulting parts separately and independently from each other. Also he doesn't move the parts of the bar. Bob made n breaks and wrote them down in his notebook in arbitrary order. At the end he got n + 1 parts. Now he wants to calculate their areas. Bob is lazy, so he asks you to do this task.

The first line contains 3 integers W, H and n (1 ≤ W, H, n ≤ 100) — width of the bar, height of the bar and amount of breaks. Each of the following n lines contains four integers xi, 1, yi, 1, xi, 2, yi, 2 — coordinates of the endpoints of the i-th break (0 ≤ xi, 1 ≤ xi, 2 ≤ W, 0 ≤ yi, 1 ≤ yi, 2 ≤ H, or xi, 1 = xi, 2, or yi, 1 = yi, 2). Breaks are given in arbitrary order. It is guaranteed that the set of breaks is correct, i.e. there is some order of the given breaks that each next break divides exactly one part of the bar into two non-empty parts.

Output n + 1 numbers — areas of the resulting parts in the increasing order.

class Rectnode
	def initialize(isrect, x1,y1,x2,y2)
		@isrect = isrect
		@x1 = x1
		@x2 = x2
		@y1 = y1
		@y2 = y2
		@div1 = nil
		@div2 = nil
	end

	def rdiv(x1,y1,x2,y2)
		if @isrect
			if intersects(x1,y1,x2,y2)
				@div1 = Rectnode.new(true, @x1,@y1,x2,y2)
				@div2 = Rectnode.new(true, x1,y1,@x2,@y2)
				@isrect = false
				return true
			else
				return false
			end
		else
			if @div1.intersects(x1,y1,x2,y2)
				return @div1.rdiv(x1,y1,x2,y2)
			else
				return @div2.rdiv(x1,y1,x2,y2)
			end
		end
	end

	def intersects(x1,y1,x2,y2)
		return false if (@x2 <= x1) || (@x1 >= x2 )
		return false if (@y2 <= y1) || (@y1 >= y2 )

		if @isrect
			if x1 == x2
				return false if (@y1 != y1) || (@y2 != y2)
			else
				return false if (@x1 != x1) || (@x2 != x2)
			end
		end

		return true
	end

	def area
		(@x2-@x1)*(@y2-@y1)
	end

	def allarea( ar )
		if @isrect
			ar.push(area())
		else
			@div1.allarea(ar)
			@div2.allarea(ar)
		end
	end
end

def splitspaceint(s)
	aaa = s.split(/ /)
	bbb = []
	for i in 0..aaa.length-1
		bbb.push(aaa[i].to_i)
	end
	return bbb
end

w,h,n = splitspaceint(gets)
rootnode = Rectnode.new(true, 0,0,w,h)
divs = []
for i in 1..n
	divs.push( splitspaceint(gets) )
end

while divs.length > 0
	for i in 0..divs.length
		xy = divs[i]
		if rootnode.rdiv(xy[0],xy[1],xy[2],xy[3])
			divs.delete_at(i)
			break
		end
	end
end

ar = []
rootnode.allarea(ar)
ar.sort!
first = true
ar.each{|a|
	print " " if not first
	print a
	first = false
}
puts ""

class Rectnode
	def initialize(isrect, x1,y1,x2,y2)
		@isrect = isrect
		@x1 = x1
		@x2 = x2
		@y1 = y1
		@y2 = y2
		@div1 = nil
		@div2 = nil
	end

	def rdiv(x1,y1,x2,y2)
		if @isrect
			@div1 = Rectnode.new(true, @x1,@y1,x2,y2)
			@div2 = Rectnode.new(true, x1,y1,@x2,@y2)
			@isrect = false
		else
			if @div1.intersects(x1,y1,x2,y2)
				@div1.rdiv(x1,y1,x2,y2)
			else
				@div2.rdiv(x1,y1,x2,y2)
			end
		end
	end

	def intersects(x1,y1,x2,y2)
		return false if (@x2 <= x1) || (@x1 >= x2 )
		return false if (@y2 <= y1) || (@y1 >= y2 )
		return true
	end

	def area
		(@x2-@x1)*(@y2-@y1)
	end

	def allarea( ar )
		if @isrect
			ar.push(area())
		else
			@div1.allarea(ar)
			@div2.allarea(ar)
		end
	end
end

def splitspaceint(s)
	aaa = s.split(/ /)
	bbb = []
	for i in 0..aaa.length-1
		bbb.push(aaa[i].to_i)
	end
	return bbb
end

w,h,n = splitspaceint(gets)
rootnode = Rectnode.new(true, 0,0,w,h)
for i in 1..n
	x1,y1,x2,y2 = splitspaceint(gets)
	rootnode.rdiv(x1,y1,x2,y2)
end
ar = []
rootnode.allarea(ar)
ar.sort!
first = true
ar.each{|a|
	print " " if not first
	print a
	first = false
}
puts ""


You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.You know that you have $$$n$$$ bacteria in the Petri dish and size of the $$$i$$$-th bacteria is $$$a_i$$$. Also you know intergalactic positive integer constant $$$K$$$.The $$$i$$$-th bacteria can swallow the $$$j$$$-th bacteria if and only if $$$a_i > a_j$$$ and $$$a_i \le a_j + K$$$. The $$$j$$$-th bacteria disappear, but the $$$i$$$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $$$i$$$ can swallow any bacteria $$$j$$$ if $$$a_i > a_j$$$ and $$$a_i \le a_j + K$$$. The swallow operations go one after another.For example, the sequence of bacteria sizes $$$a=[101, 53, 42, 102, 101, 55, 54]$$$ and $$$K=1$$$. The one of possible sequences of swallows is: $$$[101, 53, 42, 102, \underline{101}, 55, 54]$$$ $$$\to$$$ $$$[101, \underline{53}, 42, 102, 55, 54]$$$ $$$\to$$$ $$$[\underline{101}, 42, 102, 55, 54]$$$ $$$\to$$$ $$$[42, 102, 55, \underline{54}]$$$ $$$\to$$$ $$$[42, 102, 55]$$$. In total there are $$$3$$$ bacteria remained in the Petri dish.Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.

The first line contains two space separated positive integers $$$n$$$ and $$$K$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le K \le 10^6$$$) — number of bacteria and intergalactic constant $$$K$$$. The second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — sizes of bacteria you have.

Print the only integer — minimal possible number of bacteria can remain.

NoteThe first example is clarified in the problem statement.In the second example an optimal possible sequence of swallows is: $$$[20, 15, 10, 15, \underline{20}, 25]$$$ $$$\to$$$ $$$[20, 15, 10, \underline{15}, 25]$$$ $$$\to$$$ $$$[20, 15, \underline{10}, 25]$$$ $$$\to$$$ $$$[20, \underline{15}, 25]$$$ $$$\to$$$ $$$[\underline{20}, 25]$$$ $$$\to$$$ $$$[25]$$$.In the third example no bacteria can swallow any other bacteria.

n, k = gets.strip.split.map(&:to_i)
ary = gets.strip.split.map(&:to_i)
hsh = {}
ary.each {|x| hsh[x] = (hsh[x] || 0) + 1 }
ary.sort!
ary.uniq!
remaining_ary = []
un = ary.size
0.upto(un-2).each do |j|
  i =  j + 1
  next if ary[j] < ary[i] && ary[i] <= (ary[j]+k)
  remaining_ary << ary[j]
end
remaining_ary << ary.last
puts remaining_ary.map{|x| hsh[x] }.inject(:+)

def read_line
  gets.split.map{|e| e.to_i }
end

n, k = read_line
a = read_line.sort

count = 0

nearest_bigger = []
nearest_bigger[a.count - 1] = a[a.count -1]

(0...n-1).reverse_each do |index|
  cur = a[index]
  next_val = a[index+1]
  if cur == next_val
    nearest_bigger[index] = nearest_bigger[index+1]
  else
    nearest_bigger[index] = next_val
  end
end

a[0...-1].to_enum.with_index.each do |val, index|
  next_val = nearest_bigger[index]
  if val < next_val && (val + k) >= next_val
    count += 1
  end
end

puts n-count

# http://codeforces.com/problemset/problem/990/B

def count
  n, k = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)
  a.sort!
  # puts a.inspect

  return n if a.first == a.last || n == 1

  s = 0
  c = 0
  1.upto(n - 1) do |i|
    next if a[i] - a[i-1] <= k

    c += skip_count(a, i-1, s)
    s = i
  end

  c += skip_count(a, n-1, s)

  return n - c
end

def skip_count(a, startIdx, endIdx)
  c = 0
  startIdx.downto(endIdx) do |i|
    if a[i] == a[startIdx]
      next
    end

    c = (i - endIdx + 1)
    break
  end

  c
end

puts count

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

b.sort!

n = 0
prev = b.first
prev_cnt = 0
b.each do |i|
  if i > prev
    if i > prev + k
      n += prev_cnt
    end
    prev = i
    prev_cnt = 1
  else
    prev_cnt +=1
  end
end
n += prev_cnt
puts n

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

c = 1
s = 1
unique = true
1.upto(n - 1) do |i|
  unique = false if (a[i] != a[i - 1]) && unique
  next if a[i] - a[i-1] <= k

  (i - 1).downto(s) do |j|
    if a[j] == a[i - 1]
      c += 1
      next
    end

    c += 1
    break
  end

  s = i
end

if unique
  puts n
else
  puts c
end


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ of length $$$n$$$ containing each number exactly once. For example, $$$[1]$$$, $$$[4, 3, 5, 1, 2]$$$, $$$[3, 2, 1]$$$ are permutations, and $$$[1, 1]$$$, $$$[0, 1]$$$, $$$[2, 2, 1, 4]$$$ are not.There was a permutation $$$p[1 \dots n]$$$. It was merged with itself. In other words, let's take two instances of $$$p$$$ and insert elements of the second $$$p$$$ into the first maintaining relative order of elements. The result is a sequence of the length $$$2n$$$.For example, if $$$p=[3, 1, 2]$$$ some possible results are: $$$[3, 1, 2, 3, 1, 2]$$$, $$$[3, 3, 1, 1, 2, 2]$$$, $$$[3, 1, 3, 1, 2, 2]$$$. The following sequences are not possible results of a merging: $$$[1, 3, 2, 1, 2, 3$$$], [$$$3, 1, 2, 3, 2, 1]$$$, $$$[3, 3, 1, 2, 2, 1]$$$.For example, if $$$p=[2, 1]$$$ the possible results are: $$$[2, 2, 1, 1]$$$, $$$[2, 1, 2, 1]$$$. The following sequences are not possible results of a merging: $$$[1, 1, 2, 2$$$], [$$$2, 1, 1, 2]$$$, $$$[1, 2, 2, 1]$$$.Your task is to restore the permutation $$$p$$$ by the given resulting sequence $$$a$$$. It is guaranteed that the answer exists and is unique.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 400$$$) — 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 50$$$) — the length of permutation. The second line of the test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the array $$$a$$$ represents the result of merging of some permutation $$$p$$$ with the same permutation $$$p$$$.

For each test case, print the answer: $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$), representing the initial permutation. It is guaranteed that the answer exists and is unique.

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	flag = [false] * (n + 1)
	puts a.reduce([]) { |acc, i|
			if !flag[i]
				acc << i
				flag[i] = true
			end
			acc
	     }.join(' ')
end

# frozen_string_literal: true

lines = gets.to_i
lines.times do
  numbers = gets.to_i
  number_permutation = gets.split(' ').map(&:to_i)
  find_map = {}
  number_permutation.each do |i|
    next if find_map[i]

    find_map[i] = true
  end
  print find_map.keys.join(' '), "\n"
end

n = gets.chomp.to_i
n.times do
    b = gets.chomp.to_i
    atr = gets.chomp.split(" ")
    retsu = []
    until atr == []
        a = atr.shift
       # p retsu
        if !retsu.include?(a)
            retsu << a
        end
    end
    #p retsu
    retsu.delete(" ")
    puts retsu.join(" ")
end

tc = gets.to_i

tc.times do
    n = gets.to_i
    arr = gets.split().map{|i| i.to_i}
    dic = Hash.new(0)
    ans = []
    arr.each do |x|
        if(dic[x] == 0)
            ans << x
        end
        dic[x] += 1
    end
    puts ans.join(" ")
end

gets.to_i.times do
    n = gets.to_i
    a = gets.split.map(&:to_i)
    used = [false] * n
    res = []
    (0...2 * n).each do |i|
        if !used[a[i] - 1]
            used[a[i] - 1] = true
            res << a[i]
        end
    end
    puts res.join ' '
end

def solve
  n = gets.strip.to_i
  a = gets.strip.split(' ').map(&:to_i)
  v = []
  (1..n).each { |e| v[e] = true }
  a.each { |e|
    break if n.zero?
    if v[e] == true
      print "#{e} "
      v[e] = false
    end
  }
  puts
end

gets.strip.to_i.times { solve }

gets.to_i.times do
  gets
  puts gets.split.map(&:to_i).uniq.join(' ')
end

gets.to_i.times do
  gets
  puts gets.split(' ').map(&:to_i).uniq.join(' ')
end

n = gets.chomp.to_i
n.times do
    b = gets.chomp.to_i
    atr = gets.chomp.split("")
    retsu = []
    until atr == []
        a = atr.shift
        if !retsu.include?(a)
            retsu << a
        end
    end
    retsu.delete(" ")
    puts retsu.join(" ")
end


Do you know a story about the three musketeers? Anyway, you will learn about its origins now.Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.

The first line contains two space-separated integers, n and m (3 ≤ n ≤ 4000, 0 ≤ m ≤ 4000) — respectively number of warriors and number of pairs of warriors knowing each other. i-th of the following m lines contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Warriors ai and bi know each other. Each pair of warriors will be listed at most once.

If Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print "-1" (without the quotes).

NoteIn the first sample Richelimakieu should choose a triple 1, 2, 3. The first musketeer doesn't know anyone except other two musketeers so his recognition is 0. The second musketeer has recognition 1 because he knows warrior number 4. The third musketeer also has recognition 1 because he knows warrior 4. Sum of recognitions is 0 + 1 + 1 = 2.The other possible triple is 2, 3, 4 but it has greater sum of recognitions, equal to 1 + 1 + 1 = 3.In the second sample there is no triple of warriors knowing each other.

=begin
      ____________
     /            \
    /  /\      /\  \
   /  /  \    /  \  \
   \                /
    \     \___/    /
     \____________/
=end

class Solve
  def run()
    str = gets.split
    n , m = Integer(str[0]), Integer(str[1])
    graph = Array.new(n) {Array.new(n,false)}
    graph2 = Array.new(n) {Array.new}
    degree = Array.new(n,0)
    for i in 1..m
      str = gets.split
      u , v = Integer(str[0]),Integer(str[1])
      if v < u
        u, v = v , u
      end
      u -= 1
      v -= 1
      graph[u][v] = graph[v][u] = true
      graph2[u].push(v)
      degree[u] += 1
      degree[v] += 1
    end
    mn = 4000 * 4000 * 4000 * 2
    for i in 0..n-1
      for j in 0..graph2[i].length-2
        for k in j+1..graph2[i].length-1
          if graph[graph2[i][j]][graph2[i][k]] == true and degree[i] + degree[graph2[i][j]] + degree[graph2[i][k]] < mn
            mn = degree[i] + degree[graph2[i][j]] + degree[graph2[i][k]]
          end
        end
      end
    end
    if mn == 4000 * 4000 * 4000 * 2
      puts -1
    else
      puts (mn - 6)
    end
  end
end

Solve.new.run

q = Hash.new([])
n, m = gets.split.map(&:to_i)
glory = 0
out = -1

m.times do
  a, b = gets.split.map(&:to_i)
  q[a] += [b]
  q[b] += [a]
end

q.delete_if{ |key, value| value.size < 2 }

q.each do |key, value|

  for i in 0...value.size-1 do
    next unless q.key?(value[i])

    for j in i+1..value.size-1 do
      next unless q.key?(value[j])
      next unless q[value[j]].include?(value[i])

      glory = -6
      glory += q[value[i]].size
      glory += q[value[j]].size
      glory += q[key].size
      out = glory if out > glory || out == -1

    end
  end
end

puts out

require 'set'

n, m = gets.split.map &:to_i
neighbour = (1..n).map{0}
degree = (1..n).map{0}

edges = []
m.times {
	i, j = gets.split.map(&:to_i)
	i -= 1
	j -= 1
	neighbour[i] |= (1 << j)
	neighbour[j] |= (1 << i)
	degree[i] += 1
	degree[j] += 1
	edges << [i, j]
}

min = Float::INFINITY

edges.each{|i, j|
	d0 = degree[i] + degree[j]
	x = neighbour[i] & neighbour[j]
	(0..n-1).each{|k|
		if x[k] == 1
			d = d0 + degree[k]
			min = d if d < min
		end
	}
}

#(0..n-1).sort_by{|i| degree[i]}.each{|i|
#	d1 = degree[i]
#	break if d1 * 3 >= min
#
#	edges.reject!{|j, k|
#		if j == i || k == i
#			true
#		else
#			if neighbour[i].include?(j) && neighbour[i].include?(k)
#				d2, d3 = degree[j], degree[k]
#				d = d1 + d2 + d3
#				min = d if d < min
#			end
#			false
#		end
#	}
#}
#

p min == Float::INFINITY ? -1 : min - 6

n, m = STDIN.gets.split(' ').map{|x| x.to_i}
a = []

m.times do |i|
  a.push(STDIN.gets.split(' ').map{|y| y.to_i - 1});
end

=begin
n, m = 5, 6
a = ['1 2',
'1 3',
'2 3',
'2 4',
'3 4',
'4 5'].map{|x| x.split(' ').map{|y| y.to_i - 1}}
=end
musketeers = Array.new(n){|x| {'known'=>{}, 'knowncount'=> 0}}
a.map do |elem|
  musketeers[elem[0]]['knowncount'] +=1;
  musketeers[elem[0]]['known'][elem[1]]=true;
  musketeers[elem[1]]['knowncount'] +=1;
  musketeers[elem[1]]['known'][elem[0]]=true;
end

# получить тройки знающих
troikas = [];
a.map do |x|
  unite = musketeers[x[0]]['known'].keys & musketeers[x[1]]['known'].keys

  unite.map{|y| troikas.push([y, x[0],x[1] ].sort) }

end

troikas.uniq!

res = troikas.map{|x|  -6 + x.inject(0){|result, y| result+= musketeers[y]['knowncount']}}.min
res = -1 if res == nil
puts res

n, m = gets.chomp.split(' ').map(&:to_i)
as = []
bs = []
m.times do
  a, b = gets.chomp.split(' ').map(&:to_i)
  as << a
  bs << b
end

rs = [[]]
n.times do
  rs << []
end

hs = Hash.new(0)
for i in 0..m-1
  hs[as[i]] += 1
  hs[bs[i]] += 1
  rs[as[i]] << bs[i]
  rs[bs[i]] << as[i]
end

rtn = -1
for m1 in 1..n-2
  r = rs[m1]
  if 1 < r.size
    for j in 0..r.size-2
      m2 = r[j]
      for k in j+1..r.size-1
        m3 = r[k]
        if rs[m2].include?(m3)
          if rtn < 0 || hs[m1] + hs[m2] + hs[m3] - 6 < rtn
            rtn = hs[m1] + hs[m2] + hs[m3] - 6
          end
        end
      end
    end
  end
end

puts rtn

=begin
      ____________
     /            \
    /  /\      /\  \
   /  /  \    /  \  \
   \                /
    \     \___/    /
     \____________/
=end

class Solve
  def run()
    str = gets.split
    n , m = Integer(str[0]), Integer(str[1])
    graph = Array.new(n) {Array.new(n,false)}
    graph2 = Array.new(n) {Array.new}
    degree = Array.new(n,0)
    for i in 1..m
      str = gets.split
      u , v = Integer(str[0]),Integer(str[1])
      if v < u
        u, v = v , u
      end
      u -= 1
      v -= 1
      graph[u][v] = graph[v][u] = true
      graph2[u].push(v)
      degree[u] += 1
      degree[v] += 1
    end
    mn = 4000 * 4000 * 4000 * 2
    for i in 0..n-1
      for j in 0..graph2[i].length-2
        for k in j+1..graph2[i].length-1
          if graph[graph2[i][j]][graph2[i][k]] == true and degree[i] + degree[graph2[i][j]] + degree[graph2[i][k]] < mn
            mn = degree[i] + degree[graph2[i][j]] + degree[graph2[i][k]]
          end
        end
      end
    end
    puts (mn - 6)
  end
end

Solve.new.run

q = Hash.new([])
n, m = gets.split.map(&:to_i)
glory = 0
out = -1

m.times do
  a, b = gets.split.map(&:to_i)
  q[a] += [b]
  q[b] += [a]
end

q.delete_if{ |key, value| value.size < 2 }

q.each do |key, value|
  for i in 0...value.size-1 do
    unless q.key?(value[i])
      glory = 0
      break
    end
    for j in i+1..value.size-1 do
      if q.key?(value[j])

        if q[value[j]].include?(value[i])
          glory += q[value[i]].size
          glory += q[value[j]].size
          glory += q[key].size
          glory -= 6
          out = glory if out > glory || out == -1
        else
          glory = 0
          break
        end
      else
        glory = 0
        break
      end

    end
  end
end

puts out

q = Hash.new([])
n, m = gets.split.map(&:to_i)
glory = 0
out = -1

m.times do
  a, b = gets.split.map(&:to_i)
  q[a] += [b]
  q[b] += [a]
end

q.delete_if{ |key, value| value.size < 2 }

q.each do |key, value|

  for i in 0...value.size-1 do
    break unless q.key?(value[i])

    for j in i+1..value.size-1 do
      break unless q.key?(value[j])
      break unless q[value[j]].include?(value[i])

      glory = -6
      glory += q[value[i]].size
      glory += q[value[j]].size
      glory += q[key].size
      out = glory if out > glory || out == -1

    end
  end
end

puts out


Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human speech more. Help Anfisa.

The first line contains three integers k, a and b (1 ≤ k ≤ 200, 1 ≤ a ≤ b ≤ 200). The second line contains a sequence of lowercase Latin letters — the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.

Print k lines, each of which contains no less than a and no more than b symbols — Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes).

k,a,b = gets.chomp.split(/ /).map!{|x| x.to_i}
s = gets.chomp
if k*a > s.length || k*b < s.length
	puts "No solution"
else
	av = s.length/k
	dd = b - av
	remain = s.length - av*k
	idx = 0
	while idx < s.length
		svidx = idx
		idx += av
		if remain > 0
			wk = [dd, remain].min
			remain -= wk
			idx += wk
		end
		puts s[svidx..idx-1]
	end
end

k,a,b = gets.chomp.split(/ /).map!{|x| x.to_i}
s = gets.chomp
av = s.length/k
if av < a || av*b < s.length
	puts "No solution"
else
	dd = b - av
	remain = s.length - av*k
	idx = 0
	while idx < s.length-1
		svidx = idx
		idx += av
		if remain > 0
			wk = [dd, remain].min
			remain -= wk
			idx += wk
		end
		puts s[svidx..idx-1]
	end
end


You are given an integer $$$n$$$ and an array $$$a_1, a_2, \ldots, a_n$$$. You should reorder the elements of the array $$$a$$$ in such way that the sum of $$$\textbf{MEX}$$$ on prefixes ($$$i$$$-th prefix is $$$a_1, a_2, \ldots, a_i$$$) is maximized.Formally, you should find an array $$$b_1, b_2, \ldots, b_n$$$, such that the sets of elements of arrays $$$a$$$ and $$$b$$$ are equal (it is equivalent to array $$$b$$$ can be found as an array $$$a$$$ with some reordering of its elements) and $$$\sum\limits_{i=1}^{n} \textbf{MEX}(b_1, b_2, \ldots, b_i)$$$ is maximized.$$$\textbf{MEX}$$$ of a set of nonnegative integers is the minimal nonnegative integer such that it is not in the set.For example, $$$\textbf{MEX}(\{1, 2, 3\}) = 0$$$, $$$\textbf{MEX}(\{0, 1, 2, 4, 5\}) = 3$$$.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$  — the number of test cases. The first line of each test case contains a single integer $$$n$$$ $$$(1 \le n \le 100)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(0 \le a_i \le 100)$$$.

For each test case print an array $$$b_1, b_2, \ldots, b_n$$$  — the optimal reordering of $$$a_1, a_2, \ldots, a_n$$$, so the sum of $$$\textbf{MEX}$$$ on its prefixes is maximized. If there exist multiple optimal answers you can find any.

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  a.sort!
  res = []
  (0...n).each do |i|
    res << a[i] if i == 0 || a[i] != a[i - 1]
  end
  (0...n).each do |i|
    res << a[i] if i > 0 && a[i] == a[i - 1]
  end
  puts res.join ' '
end

t = gets.chomp.to_i
for test in (1..t)
  n = gets.chomp.to_i
  a = gets.chomp.split(' ').map { |x| x.to_i }
  c = Array.new(101).fill(0)
  for i in a
    c[i] += 1
  end
  j = 0
  for i in (0..100)
    if c[i] > 0
      c[i] -= 1
      a[j] = i
      j += 1
    end
  end
  for i in (0..100)
    while c[i] > 0
      c[i] -= 1
      a[j] = i
      j += 1
    end
  end
  a.each do |x|
    print x, ' '
  end
  puts
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  i = 0
  (0..100).each do |x|
    if j = a.index(x)
      a[i], a[j] = a[j], a[i]
    else
      break
    end
    i += 1
  end
  puts a.join ' '
end

gets.to_i.times {
  gets
  arr = gets.split(' ').map(&:to_i).sort
  res = []
  res_tail = []
  arr.each { |el|
    if el == res[-1]
      res_tail.push(el)
    else
      res.push(el)
    end
  }
  puts [*res, *res_tail].join(' ')
}

def solve(n, a)
    mex = 0
    b = []
    n.times {
        if (i = a.index(mex))
            b << a.delete_at(i)
            mex += 1
        else
            break
        end
    }
    b += a
    b
end

def main
    t = int
    t.times do
        n = int
        a = ints
        puts solve(n, a) * " "
    end
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(No Yes)
INF = 10**9

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 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 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 * mod_inv(y, mod) % 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
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

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  res = []
  (0...n).each do |i|
    res << a[i] if i == 0 || a[i] != a[i - 1]
  end
  (0...n).each do |i|
    res << a[i] if i > 0 && a[i] == a[i - 1]
  end
  puts res.join ' '
end