Given the integer $$$n$$$ — the number of available blocks. You must use all blocks to build a pedestal. The pedestal consists of $$$3$$$ platforms for $$$2$$$-nd, $$$1$$$-st and $$$3$$$-rd places respectively. The platform for the $$$1$$$-st place must be strictly higher than for the $$$2$$$-nd place, and the platform for the $$$2$$$-nd place must be strictly higher than for the $$$3$$$-rd place. Also, the height of each platform must be greater than zero (that is, each platform must contain at least one block).    Example pedestal of $$$n=11$$$ blocks: second place height equals $$$4$$$ blocks, first place height equals $$$5$$$ blocks, third place height equals $$$2$$$ blocks.Among all possible pedestals of $$$n$$$ blocks, deduce one such that the platform height for the $$$1$$$-st place minimum as possible. If there are several of them, output any of them.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case contains a single integer $$$n$$$ ($$$6 \le n \le 10^5$$$) — the total number of blocks for the pedestal. All $$$n$$$ blocks must be used. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^6$$$.

For each test case, output $$$3$$$ numbers $$$h_2, h_1, h_3$$$ — the platform heights for $$$2$$$-nd, $$$1$$$-st and $$$3$$$-rd places on a pedestal consisting of $$$n$$$ blocks ($$$h_1+h_2+h_3=n$$$, $$$0 < h_3 < h_2 < h_1$$$).  Among all possible pedestals, output the one for which the value of $$$h_1$$$ minimal. If there are several of them, output any of them.

NoteIn the first test case we can not get the height of the platform for the first place less than $$$5$$$, because if the height of the platform for the first place is not more than $$$4$$$, then we can use at most $$$4 + 3 + 2 = 9$$$ blocks. And we should use $$$11 = 4 + 5 + 2$$$ blocks. Therefore, the answer 4 5 2 fits. In the second set, the only suitable answer is: 2 3 1.

#require "prime"
#input of int(split by space)
def get_i()
    return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
    return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
    return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
    return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
    return bool ? y : n
end
#output grid(two dimensional array)
def puts_grid(grid,join_char="")
    grid.each do|line|
        puts line.join(join_char)
    end
end

Dirxy4=[[1,0],[-1,0],[0,1],[0,-1]]
Dirxy8=[[1,0],[1,-1],[1,1],[0,-1],[0,1],[-1,0],[-1,-1],[-1,1]]

INF=Float::INFINITY

#MOD=998_244_353
MOD=10**9+7

T=gets.to_i
T.times do
    n=gets.to_i
    v=n/3
    r=n%3
    case r
    when 0 then
        puts [v,v+1,v-1].join(" ")
    when 1 then
        puts [v,v+2,v-1].join(" ")
    when 2 then
        puts [v+1,v+2,v-1].join(" ")
    end
end

def solution(n)
    fi, se, th = 3, 2, 1
    m = (n - 6) / 3
    r = (n - 6) % 3
    fi += m
    se += m
    th += m
    while r > 0
        if r > 0
            fi += 1
            r -= 1
        end
        if r > 0
            se += 1
            r -= 1
        end
        if r > 0
            th += 1
            r -= 1
        end
    end
    puts se.to_s + " " + fi.to_s + " " + th.to_s
end

n = $stdin.gets.to_i
(0...n).each do |i|
  n = $stdin.gets.to_i
  solution(n)
end

t = gets.to_i

t.times do
  n = gets.to_i
  h1 = h2 = h3 = n / 3
  m = n % 3
  if m == 1
    h1 += 1
  elsif m == 2
    h1 += 1
    h2 += 1
  end

  until h3 < h2 && h2 < h1 && h1+h2+h3 == n
    h1 += 1
    h3 -= 1
  end
  puts [h2, h1, h3].join(" ")
end

#require "prime"
#input of int(split by space)
def get_i()
    return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
    return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
    return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
    return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
    return bool ? y : n
end
#output grid(two dimensional array)
def puts_grid(grid,join_char="")
    grid.each do|line|
        puts line.join(join_char)
    end
end

Dirxy4=[[1,0],[-1,0],[0,1],[0,-1]]
Dirxy8=[[1,0],[1,-1],[1,1],[0,-1],[0,1],[-1,0],[-1,-1],[-1,1]]

INF=Float::INFINITY

#MOD=998_244_353
MOD=10**9+7

T=gets.to_i
T.times do
    n=gets.to_i
    puts [2,n-3,1].join(" ")
end


You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.The following definition of a regular bracket sequence is well-known, so you can be familiar with it.Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.Determine the least number of replaces to make the string s RBS.

The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.

If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s.

s = gets.strip.split ''

brk = Array.new
right = {'>' => '<', '}' => '{', ']' => '[', ')' => '('}

res = 0

s.each do |e|
	if right.include? e
		if brk.size == 0
			res = -1
			break
		end

		if brk[-1]  == right[e]
			brk.pop
		else
			res += 1
			brk.pop
		end
	else
		brk.push e
	end
end

if res == -1 or brk.any?{|e| e != 0}
	puts 'Impossible'
else
	puts res
end

str = gets.chomp

stack = []
res = 0
hash = {
  ')' => '(',
  '>' => '<',
  ']' => '[',
  '}' => '{'
}

str.each_char do |c|
  case c
  when '(', '{', '<', '[' then stack.push c
  when ')'
    res = 'Impossible' and break if (stack.length==0)
    res += 1 if stack[-1]!='('
    stack.pop
  when '}'
    res = 'Impossible' and break if (stack.length==0)
    res += 1 if stack[-1]!='{'
    stack.pop
  when '>'
    res = 'Impossible' and break if (stack.length==0)
    res += 1 if stack[-1]!='<'
    stack.pop
  when ']'
    res = 'Impossible' and break if (stack.length==0)
    res += 1 if stack[-1]!='['
    stack.pop
  end
end

if stack.length==0
  puts res
else
  puts 'Impossible'
end

s = gets.chomp

RBS = Array.new		# regular bracket sequance
change = 0

for i in 0...s.length
	case s[i]
		when '(', '[', '{', '<' then
			RBS.push s[i]

		when ')', ']', '}', '>' then
			if RBS.empty?
				puts "Impossible"
				exit true
			end

			ch = RBS.pop
			if not ((ch == '(' and s[i] == ')') or (ch == '[' and s[i] == ']') or (ch == '{' and s[i] == '}') or (ch == '<' and s[i] == '>'))
				change = change + 1
			end
	end

end

if not RBS.empty?
	puts "Impossible"
else
	puts change
end

ans=0
s=[]
def type_of b
	case b
	when ?<,?{,?[,?(
		:opening
	when ?>,?},?],?)
		:closing
	end
end

def is_paired?(o,c)
	case o
	when ?<
		c==?>
	when ?{
		c==?}
	when ?[
		c==?]
	when ?(
		c==?)
	end
end

while c=STDIN.getc
	if type_of(c)==:opening
		s.push c
	elsif type_of(c)==:closing
		o=s.pop
		unless o
			puts "Impossible"
			exit
		end
		ans+=1 unless is_paired?(o,c)
	end
end

puts s.empty? ? ans : "Impossible"

s = gets.strip.split ''

brk =Array.new(4, 0)
right = {'>' => 0, '}' => 1, ']' => 2, ')' => 3}
left = {'<' => 0, '{' => 1, '[' => 2, '(' => 3}
res = 0

s.each do |e|
	if right.include? e
		if brk.none?{|i| i > 0}
			res = -1
			break
		end

		if brk[right[e]] != 0
			brk[right[e]] -= 1
		else
			res += 1
			brk[brk.find_index{|e| e != 0}] -= 1
		end
	else left.include? e
			brk[left[e]] += 1
	end
end

if res == -1 or brk.any?{|e| e != 0}
	puts 'Impossible'
else
	puts res
end

ans=0
s=[]
def type_of b
	case b
	when ?<,?{,?[,?(
		:opening
	when :>,?},?],?)
		:closing
	end
end

def is_paired?(o,c)
	case o
	when ?<
		c==?>
	when ?{
		c==?}
	when ?[
		c==?]
	when ?(
		c==?)
	end
end

while c=STDIN.getc
	if type_of(c)==:opening
		s.push c
	elsif type_of(c)==:closing
		o=s.pop
		unless o
			puts "Impossible"
			exit
		end
		ans+=1 unless is_paired?(o,c)
	end
end

puts s.empty? ? ans : "Impossible"

ans=0
s=[]
def type_of b
	case b
	when ?<,?{,?[,?(
		:opening
	when ?>,?},?],?)
		:closing
	end
end

def is_paired?(o,c)
	case o
	when ?<
		c==?>
	when ?{
		c==?}
	when ?[
		c==?]
	when ?(
		c==?)
	end
end

while c=STDIN.getc
	p type_of(c)
	if type_of(c)==:opening
		s.push c
	elsif type_of(c)==:closing
		o=s.pop
		unless o
			puts "Impossible"
			exit
		end
		ans+=1 unless is_paired?(o,c)
	end
end

puts s.empty? ? ans : "Impossible"


A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.

The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). All the numbers in the lines are separated by single spaces.

On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.

NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.

a,k={},gets.split.map(&:to_i)[1]
gets.split.map(&:to_i).sort.each{|i|a[i]=1 if i%k>0||!a[i/k]}
p a.size

k=gets.split.map(&:to_i)[1]
a,ans={},0
gets.split.map(&:to_i).sort.each{|i|a[i]=1}
a.each do |key,v|
  next if v==0
  ans+=1
  a[key*k]-=1 if a[k*key]
end
p ans

n,k=gets.chomp.split.collect{|a| a.to_i}
arr=gets.chomp.split.collect{|a| a.to_i}.sort
set={}
arr.each{|a| if a%k!=0 || set[a/k]== nil then set[a]=true end }
puts set.size

#!/usr/bin/ruby1.9

n, k = STDIN.readline.split.collect {|s| s.to_i }
a = STDIN.readline.split.collect {|s| s.to_i }

a.sort!
index = {}
a.length.times {|i| index[a[i]] = i }

count = 0
a.length.times do |i|
	next if a[i] < 0
	count += 1
	j = index[k*a[i]]
	a[i] *= -1
	if j != nil
		a[j] *= -1
	end
end

puts count

require 'set'
nk = gets.split(' ').collect!{|i| i.to_i}
n = nk[0]
k = nk[1]

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

# ak = []
# size = 0
# a.each do |i|
# 	if !ak.include?(i)
# 		ak << i*k
# 		size += 1
# 	end
# end

# puts size
s = Set.new
a.each do |i|
	s << i*k if !s.include?(i)
end

p s.size

# require 'set'
nk = gets.split(' ').collect!{|i| i.to_i}
n = nk[0]
k = nk[1]

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

# s = Set.new
s = {}
b = 0
a.each do |i|
	if !s.include?(i)
		s[i*k] = b
		b += 1
	end
end

p b

def binary_search(ary, x)

  n = ary.size
  left  = 0
  right = n - 1

  while left <= right
    mid = (left + right) / 2

    case ary[mid] <=> x
    when 0
      return mid
    when 1
      right = mid - 1
    when -1
      left  = mid + 1
    end
  end

  return -1
end

n, k = gets.split.map &:to_i
ary  = gets.split.map(&:to_i).sort
aryc = Array.new(n, 0)
ans  = 0

for i in 0 .. n - 1 do

  if aryc[i] == 1 then next end
  aryc[i] = 1

  tmp = ary[i]
  cnt = 1

  while tmp <= ary[n - 1]
    if k == 1 then break end
    tmp *= k
    check = binary_search(ary, tmp)
    if check > -1
      aryc[check] = 1
      cnt += 1
    else
      break
    end
  end

  ans += (cnt + 1) / 2
end

puts ans

nk = gets.split(' ').collect!{|i| i.to_i}
n = nk[0]
k = nk[1]

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

# ak = []
# size = 0
# a.each do |i|
# 	if !ak.include?(i)
# 		ak << i*k
# 		size += 1
# 	end
# end

# puts size
s = []
a.each do |i|
	s << i if !s.include?(i/k)
end

p s.size

def binary_search(ary, x)

  n = ary.size
  left  = 0
  right = n - 1

  while left <= right
    mid = (left + right) / 2

    case ary[mid] <=> x
    when 0
      return mid
    when 1
      right = mid - 1
    when -1
      left  = mid + 1
    end
  end

  return -1
end

n, k = gets.split.map &:to_i
ary  = gets.split.map(&:to_i).sort
aryc = Array.new(n, 0)
ans  = 0

for i in 0 .. n - 1 do

  if k == 1 then break end

  if aryc[i] == 1 then next end
  aryc[i] = 1

  tmp = ary[i]
  cnt = 1

  while tmp <= ary[n - 1]
    tmp *= k
    check = binary_search(ary, tmp)
    if check > -1
      aryc[check] = 1
      cnt += 1
    else
      break
    end
  end

  ans += (cnt + 1) / 2
end

puts ans

def binary_search(ary, x)
n = ary.size
left = 0
right = n - 1
while left < right
mid = (left + right) / 2
case ary[mid] <=> x
when 0
return mid
when 1
right = mid
when -1
left  = mid + 1
end
end
return -1
end

n, k = gets.split.map &:to_i
ary = gets.split.map(&:to_i).sort
aryc = Array.new(n, 0)
ans = 0

for i in 0 .. n - 1 do
if aryc[i] == 1 then next end
aryc[i]= 1
tmp = ary[i]
cnt = 1
while tmp <= ary[n - 1]
tmp *= k
check = binary_search(ary, tmp)
if check > -1
break
else
aryc[check] = 1
cnt += 1
end
end
ans += cnt/2
end

puts ans


You have a string $$$s$$$ consisting of digits from $$$0$$$ to $$$9$$$ inclusive. You can perform the following operation any (possibly zero) number of times:   You can choose a position $$$i$$$ and delete a digit $$$d$$$ on the $$$i$$$-th position. Then insert the digit $$$\min{(d + 1, 9)}$$$ on any position (at the beginning, at the end or in between any two adjacent digits). What is the lexicographically smallest string you can get by performing these operations?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ of the same length if and only if the following holds:   in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a smaller digit than the corresponding digit in $$$b$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then the test cases follow. Each test case consists of a single line that contains one string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$) — the string consisting of digits. Please note that $$$s$$$ is just a string consisting of digits, so leading zeros are allowed. It is guaranteed that the sum of lengths of $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print a single string — the minimum string that is possible to obtain.

NoteIn the first test case:   Delete $$$8$$$ and insert $$$9$$$ at the end of the notation. The resulting notation is $$$04299$$$.  Delete $$$4$$$ and insert $$$5$$$ in the $$$3$$$-rd position of the notation. The resulting notation is $$$02599$$$. Nothing needs to be done in the second and third test cases.

gets.to_i.times do
  m = 9
  puts (gets.chomp!.chars.map!(&:to_i).reverse_each.map do |c|
    if m >= c
      m = c
      c
    elsif c == 9
      c
    else
      c + 1
    end
  end.sort!.join)
end

gets.to_i.times do
  a = []
  b = []
  m = 9
  puts (gets.chomp!.chars.map!(&:to_i).reverse_each.map do |c|
    if m >= c
      m = c
      c
    elsif c == 9
      c
    else
      c + 1
    end
  end.sort!.join)
end

gets.to_i.times do
  a = []
  b = []
  m = 9
  gets.chomp!.chars.map!(&:to_i).reverse_each do |c|
    if m >= c
      m = c
      a << c
    else
      b << c
    end
  end
  a += b.map! { |e| e == 9 ? 9 : e + 1 }
  puts a.sort!.join
end

gets.to_i.times do
  a = []
  b = []
  m = 9
  gets.chomp!.chars.map!(&:to_i).reverse_each do |c|
    m = c if m > c
    if m == c
      a << c
    else
      b << c
    end
  end
  a += b.map! { |e| e == 9 ? 9 : e + 1 }
  puts a.sort!.join
end

gets.to_i.times do
  s = gets.chomp!.chars.map!(&:to_i).reverse!
  a = []
  b = []
  m = 9
  s.each do |c|
    m = c if m > c
    if m == c
      a << c
    else
      b << c
    end
  end
  a += b.map! { |e| e == 9 ? 9 : e + 1 }
  puts a.sort!.join
end

gets.to_i.times do
  a = []
  b = []
  m = 9
  gets.chomp!.chars.map!(&:to_i).reverse_each do |c|
    if m >= c
      c = m
      a << c
    else
      b << c
    end
  end
  a += b.map! { |e| e == 9 ? 9 : e + 1 }
  puts a.sort!.join
end

gets.to_i.times do
  s = gets.chomp!.chars.map!(&:to_i)
  a = []
  (0..9).each do |i|
    break if s.empty?
    c = s.count(i)
    if c != 0
      j = s.rindex(i)
      s = s[(j + 1)..-1] + s[0...j].map! do |e|
        if e == i || e == 9
          e
        else
          e + 1
        end
      end.tap { |s| s.delete(i) }.sort!
      a += [i] * c
    end
  end
  puts a.join
end


The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it.However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to figure out whether the document has malfunctioned. Specifically, he is given a string of length $$$n$$$ whose characters are all either T or M, and he wants to figure out if it is possible to partition it into some number of disjoint subsequences, all of which are equal to TMT. That is, each character of the string should belong to exactly one of the subsequences.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) characters.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$)  — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$3 \le n < 10^5$$$), the number of characters in the string entered in the document. It is guaranteed that $$$n$$$ is divisible by $$$3$$$. The second line of each test case contains a string of length $$$n$$$ consisting of only the characters T and M. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single line containing YES if the described partition exists, and a single line containing NO otherwise.

5
3
TMT
3
MTT
6
TMTMTT
6
TMTTTT
6
TTMMTT

NoteIn the first test case, the string itself is already a sequence equal to TMT.In the third test case, we may partition the string into the subsequences TMTMTT. Both the bolded and the non-bolded subsequences are equal to TMT.

t = gets.to_s.to_i

def check(a)
  cnt_t = 0
  cnt_m = 0
  a.each do |c|
    cnt_t += 1 if c == "T"
    cnt_m += 1 if c == "M"
  end
  return false if cnt_m * 2 != cnt_t

  cnt = 0
  a.each do |c|
    cnt += 1 if c == "T"
    cnt -= 1 if c == "M"
    return false if cnt < 0
  end

  cnt = 0
  a.reverse.each do |c|
    cnt += 1 if c == "T"
    cnt -= 1 if c == "M"
    return false if cnt < 0
  end

  return true
end

1.upto(t) do |casenum|
  n = gets.to_s.split.map {|x| x.to_i }
  ar = gets.to_s.strip.split("")

  if check(ar)
    printf("YES\n")
  else
    printf("NO\n")
  end
end


Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers.Subarray a[i... j] (1 ≤ i ≤ j ≤ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj).

The first line contains two space-separated integers n, k (1 ≤ k ≤ n ≤ 4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly.  The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — elements of the array.

Print the single number — the number of such subarrays of array a, that they have at least k equal integers. Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2).In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1).In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).

n,m=gets.split.map &:to_i;a=gets.split.map &:to_i;h=Hash.new 0;j,z=-1,0;n.times{|i|h[a[j+=1]]+=1 until h[a[j]]>=m||j==n;z+=n-j;h[a[i]]-=1;};p z

n,m = gets.split.map(&:to_i)
ans = 0

hs = Hash.new(0)

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

i = 0
j = 0
ok = false
while i < a.size
    if i - 1 >= 0
        ok = false if hs[a[i-1]] == m
        hs[a[i-1]] -= 1
    end

    until ok or j == a.size
        ok = true if (hs[a[j]] += 1) == m
        j += 1
    end
    ans += a.size - j + 1 if ok
#p [i,j,ans]
#    p hs
    i += 1
end

puts ans

n,m=gets.split.map &:to_i;a=gets.split.map &:to_i;h=Hash.new 0;j,z=-1,0;n.times{|i|h[i]-=1;h[a[j+=1]]+=1 until h[a[j]]>=m||j==n;z+=n-j};p z


You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad.A substring s[l...r] (1 ≤ l ≤ r ≤ |s|) of string s  =  s1s2...s|s| (where |s| is the length of string s) is string  slsl + 1...sr.The substring s[l...r] is good, if among the letters  sl, sl + 1, ..., sr there are at most k bad ones (look at the sample's explanation to understand it more clear).Your task is to find the number of distinct good substrings of the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their content is different, i.e. s[x...y] ≠ s[p...q].

The first line of the input is the non-empty string s, consisting of small English letters, the string's length is at most 1500 characters. The second line of the input is the string of characters "0" and "1", the length is exactly 26 characters. If the i-th character of this string equals "1", then the i-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on. The third line of the input consists a single integer k (0 ≤ k ≤ |s|) — the maximum acceptable number of bad characters in a good substring.

Print a single integer — the number of distinct good substrings of string s.

NoteIn the first example there are following good substrings: "a", "ab", "b", "ba", "bab".In the second example there are following good substrings: "a", "aa", "ac", "b", "ba", "c", "ca", "cb".

s = gets.chomp.chars.map &:ord
t = gets.chomp
bads = [0]*97 + t.chars.map{ |i| i == ?0 }
k = gets.to_i

ans = 0
pre = []

for x in (0...s.length).map{ |i| s[i..-1] }.sort
    h = pre.zip(x).take_while{ |i, j| i == j }.length
    p = 0
    x.each_with_index do |c, i|
		p += 1 if bads[c]
        next if i < h
		break if p > k
		ans += 1
    end
	pre = x
end

puts ans

s = gets.chomp.chars.map{ |i| i.ord - 97 }
bads = gets.chomp.chars.map{ |i| i == ?0 }
k = gets.to_i

ans = 0
pre = []

for x in (0...s.length).map{ |i| s[i..-1] }.sort
    h = pre.zip(x).take_while{ |i, j| i == j }.length
    p = 0
    x.each_with_index do |c, i|
		break if k < p += 1 if bads[c]
        ans += 1 unless i < h
    end
	pre = x
end

puts ans

require "Set"

string = gets.chomp.chars.map &:ord
bads = [0]*97 + gets.chomp.chars.map{ |i| 1 - i.to_i }
limit = gets.to_i

zo = string.map{ |i| bads[i] }

left = 0
right = -1
n = 0

h = Set.new

loop do
    for i in left+1..right
        h.add string[i..right]
    end
    break if string.length == right += 1
    if limit < n += bads[string[right]]
        n = limit
        left += zo[left..right].index(1) + 1
    end
    h.add string[left..right]
end

puts h.size


The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dn - 1 is the distance between the n - 1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.

The first line contains integer n (3 ≤ n ≤ 100) — the number of stations on the circle line. The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 100) — the distances between pairs of neighboring stations. The third line contains two integers s and t (1 ≤ s, t ≤ n) — the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces.

Print a single number — the length of the shortest path between stations number s and t.

NoteIn the first sample the length of path 1 → 2 → 3 equals 5, the length of path 1 → 4 → 3 equals 13.In the second sample the length of path 4 → 1 is 100, the length of path 4 → 3 → 2 → 1 is 15.In the third sample the length of path 3 → 1 is 1, the length of path 3 → 2 → 1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0.

def run
  n = ARGF.readline.to_i
  d = ARGF.readline.split.map(&:to_i)
  t, s = ARGF.readline.split.map(&:to_i)

  positive = 0
  cur = t - 1
  while cur != (s - 1)
    positive += d[cur]
    cur = (cur + 1) % n
  end

  negative = 0
  cur = t - 1
  while cur != (s - 1)
    cur = (cur + n - 1) % n
    negative += d[cur]
  end

  puts [positive, negative].min
end

run if $0 == __FILE__

def run
  n = ARGF.readline.to_i
  d = ARGF.readline.split.map(&:to_i)
  t, s = ARGF.readline.split.map(&:to_i)

  sum = 0
  cur = t - 1
  while cur != (s - 1)
    sum += d[cur]
    cur = (cur + 1) % n
  end

  puts [sum, d.reduce(:+) - sum].min
end

run if $0 == __FILE__

a=gets.chomp.to_i
b=gets.chomp.split(" ")
0.upto(a-1) {|i| b[i]=b[i].to_i}
d=gets.chomp.split(" ")
0.upto(1) {|i| d[i]=d[i].to_i}
d.sort!
ans1=0
ans2=0

(d[0]-1).upto(d[1]-2) {|i| ans1+=b[i]}
if d[0]!=1
0.upto(d[0]-2) {|i| ans2+=b[i]}
end
(a-1).downto(d[1]-1 ){|i| ans2+=b[i]}
if ans1<ans2
puts "#{ans1}"
else
puts "#{ans2}"
end

n=gets.to_i
xs=gets.split.map{|e| e.to_i}
a,b=gets.split.map{|e| e.to_i}
c=[a,b].min
d=[a,b].max

sum=0
xs.each{|e| sum+=e}

sum2=0
((c-1)..(d-2)).each{|i|
	sum2+=xs[i]
}
puts [sum2,sum-sum2].min

require 'set'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i
stops = gets.split.map(&:to_i)
a, b = gets.split.map(&:to_i)
from, to = [a, b].min - 1, [a, b].max - 1

total_weight = stops.inject(0, :+)
from_a_to_b = stops[from...to].inject(0, :+)

print [total_weight - from_a_to_b, from_a_to_b].min

n=gets.to_i
a=gets.split.map(&:to_i)
s,t=gets.split.map(&:to_i)
s-=1
t-=1
i,k=s,0
while i!=t do
    k+=a[i]
    i=(i+1)%n
end
res=k
i,k=s,0
while i!=t do
    k+=a[(i-1+n)%n]
    i=(i-1+n)%n
end
puts [res, k].min

n = Integer(gets)
input = gets.chomp
nums = input.split
d = Array.new
for i in 0...n
    d[i] = Integer(nums[i])
end
input2 = gets.chomp
num = input2.split
s = Integer(num[0])
t = Integer(num[1])
sum = 0
for i in 0...n
    sum = sum + d[i]
end
sov = 0
if s <= t
    for i in s-1...t-1
        sov = sov + d[i]
    end
else
    for i in t-1...s-1
        sov = sov + d[i]
    end
end
sov2 = sum - sov
if sov >= sov2
    puts sov2
else
    puts sov
end

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

s, t = gets.split(' ').collect!{|i| i.to_i - 1}.sort

sum = 0
sum1 = 0
d.each_index do |i|
	sum += d[i]
	sum1 += d[i] if i >= s && i < t
end
sum2 = sum - sum1

p [sum1, sum2].min

gets
ds = gets.split.map(&:to_i)
s, t = gets.split.map(&:to_i)

s, t = [s, t].sort

first = ds[(s-1)..(t-2)].reduce(:+) || 0
second = ds.reduce(:+) - first
p [first, second].min

n = gets.chomp.to_i
arr = gets.split(" ").collect! {|x| x.to_i}
s1,t1 = gets.split(" ").collect! {|x| x.to_i}
sum = 0
arr.each {|v|
	sum += v
}

f = 0
s = [s1,t1].min
t = [s1,t1].max
arr[(s-1)...(t-1)].each {|w|
	f += w
}

puts [f,sum-f].min

n = gets.to_i;
a = gets.split.map(&:to_i);
sum = a.inject(:+);
acc = 0;
d = [0].concat(a.map {|x| acc += x})
s, t = gets.split.map(&:to_i);
s, t = t, s if t < s
p ([d[t-1]-d[s-1], sum - d[t-1] + d[s-1]].min)

n = Integer(gets.chomp)
d = gets.chomp.split.map { |x| x.to_i }
s, t = gets.chomp.split.map { |x| x.to_i }.sort
puts(s == t ? 0 : [d[s - 1...t - 1], d[t - 1...n] + d[0...s - 1]].map { |a| a.inject(:+) }.min)

gets
ds = gets.split.map(&:to_i)
ps = gets.split.map(&:to_i).map(&:pred)
p [ds.slice!(ps.min, ps.reduce(&:-).abs), ds].map { |i|
  (i || []).reduce(&:+).to_i
}.min

n = gets.to_i
ds = gets.split.map(&:to_i)
s, t = gets.split.map(&:to_i).sort
if s == t
  puts 0
  exit
end
sum = ds.inject{|m,i|m+i}
dis = ds[s-1,t-s].inject{|m,i|m+i}
puts [dis, sum - dis].min

n = gets.to_i
ar = [0] + gets.split(' ').map(&:to_i)
s, t = gets.split(' ').map(&:to_i).minmax
v1 = ar.inject(:+)
v2 = ar[s...t].inject(0,:+)
puts [v1-v2, v2].min

n = gets.to_i
d = gets.split.map{|i| i.to_i}
s,t = gets.split.map{|i| i = i.to_i - 1}
res1 = 0
res2 = 0

if s > t then
    k = t
    while k < s do
        res1 += d[k]
        k += 1
    end
    while k < n do
        res2 += d[k]
        k += 1
    end
    k = 0
    while k < t do
        res2 += d[k]
        k += 1
    end
else
    k = s
    res1 = 0
    while k < t do
        res1 += d[k]
        k += 1
    end
    while k < n do
        res2 += d[k]
        k += 1
    end
    k = 0
    while k < s do
        res2 += d[k]
        k += 1
    end
end

puts [res1, res2].min

class Array
  def sum
    self.inject{|sum, x| sum + x}
  end
end
num = gets.chomp.to_i
dis = gets.chomp.split(" ").map {|x| x.to_i}
tmp = gets.chomp.split(" ")
a = tmp[0].to_i
b = tmp[1].to_i
if a > b
  a,b = b,a
end
r1 = 0
for i in a-1..b-2
  r1 += dis[i]
end

if r1 < dis.sum-r1
  puts r1
else
  puts dis.sum-r1
end

n = gets.to_i
d = gets.split(' ').map(&:to_i)
s, t = gets.split(' ').map(&:to_i)
if t < s
  s , t = t, s
end
l1 , l2 = 0, 0

for i in 0..d.size - 1 do
  if (i < s - 1) || (i > t - 2)
    l1 += d[i]
  else
    l2 += d[i]
  end
end

puts (if l1 < l2 then l1 else l2 end)

n = gets.chomp.to_i
d = gets.chomp.split(" ").map{|x| x.to_i}
s,j = gets.chomp.split(" ").map{|x| x.to_i}.sort

sum1 = 0
(s-1..j-2).each do |i|
  sum1 += d[i]
end

sum2 = 0
(0..s-2).each do |i|
  sum2 += d[i]
end

(j-1..n-1).each do |i|
  sum2 += d[i]
end

puts [sum1,sum2 ].min

num_stations = gets.to_i
stations = gets.split.collect {|i| i.to_i}
req_stations = gets.split.collect {|i| i.to_i}
total_distance = stations.inject(:+)
distance = 0
first = req_stations.min
last = req_stations.max
for i in first-1...last-1
	distance = distance + stations[i]
end
puts [distance,total_distance-distance].min

n = gets.to_i
dis = Array.new(n+1, 0)
d = gets.split.map(&:to_i)
for i in 1..n
  dis[i] = dis[i-1]+d[i-1]
end
a = gets.split.map(&:to_i)
A = (a.min) -1
B = (a.max) -1
puts [dis[B] - dis[A], (dis[n]-dis[B]) + dis[A]].min

#!/usr/bin/ruby

n = STDIN.readline.to_i

distances = STDIN.readline.split.collect {|s| s.to_i}
total = distances.inject {|sum, x| sum += x }

limits = STDIN.readline.split.collect {|s| s.to_i}
limits.sort!

sum = 0
((limits[0]-1)..(limits[1]-2)).each do |i|
	sum += distances[i]
end
puts [sum, total-sum].min

l = gets.chomp.to_i
arr = gets.chomp.split(' ').map(&:to_i)
s, t = gets.chomp.split(' ').map(&:to_i).sort

s -= 1
t -= 1

l1 = l2 = 0

s.upto(t-1).each do |ind|
  l1 += arr[ind]
end

(s-1).downto(0).each do |ind|
  l2 += arr[ind]
end

t.upto(l-1).each do |ind|
  l2 += arr[ind]
end

#puts l1, l2, s ,t
puts l1 > l2 ? l2 : l1

n = Integer(gets)
input = gets.chomp
nums = input.split
d = Array.new
for i in 0...n
	d[i] = Integer(nums[i])
end
input2 = gets.chomp
num = input2.split
s = Integer(num[0])
t = Integer(num[1])
sum = 0
for i in 0...n
	sum = sum + d[i]
end
sov = 0
for i in s-1...t-1
	sov = sov + d[i]
end
sov2 = sum - sov
if sov >= sov2
	puts sov2
else
	puts sov
end

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

s, t = gets.split(' ').collect!{|i| i.to_i}.sort

rast1 = 0
(s..(t-1)).each do |x|
	rast1 += d[x-1]
end

rast2 = 0
if s > 1
	(0..(s-1)).each do |x|
		rast2 += d[x-1]
	end
end

(t..n).each do |x|
	rast2 += d[x-1]
end

if rast1 < rast2
	p rast1
else
	p rast2
end

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

s, t = gets.split(' ').collect!{|i| i.to_i}.sort

if t > s
	rast1 = 0

	(s..(t-1)).each do |x|
		rast1 += d[x-1]
	end

	rast2 = 0
	if s > 1
		(0..(s-1)).each do |x|
			rast2 += d[x-1]
		end
	end

	(t..n).each do |x|
		rast2 += d[x-1]
	end

	if rast1 < rast2
		p rast1
	else
		p rast2
	end
else
	p 0
end

gets
ds = gets.split.map(&:to_i)
s, t = gets.split.map(&:to_i)

first = ds[(s-1)..(t-2)].reduce(:+) || 0
second = ds.reduce(:+) - first
p [first, second].min

gets
ds = gets.split.map(&:to_i)
ps = gets.split.map(&:to_i).map(&:pred)
puts [ds.rotate!(-ds[0]).slice!(0, ps.reduce(&:-).abs), ds].map { |i|
  (i || []).reduce(&:+)
}.min

l = gets.chomp.to_i
arr = gets.chomp.split(' ').map(&:to_i)
s, t = gets.chomp.split(' ').map(&:to_i).sort

s -= 1
t -= 1

l1 = l2 = 0

s.upto(t-1).each do |ind|
  l1 += arr[ind]
end

s.downto(0).each do |ind|
  l2 += arr[ind]
end

t.upto(l-1).each do |ind|
  l2 += arr[ind]
end

puts l1 > l2 ? l2 : l1


A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show.The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions:  Is it true that y is strictly larger than number x?  Is it true that y is strictly smaller than number x?  Is it true that y is larger than or equal to number x?  Is it true that y is smaller than or equal to number x? On each question the host answers truthfully, "yes" or "no".Given the sequence of questions and answers, find any integer value of y that meets the criteria of all answers. If there isn't such value, print "Impossible".

The first line of the input contains a single integer n (1 ≤ n ≤ 10000) — the number of questions (and answers). Next n lines each contain one question and one answer to it. The format of each line is like that: "sign x answer", where the sign is:   ">" (for the first type queries),  "<" (for the second type queries),  ">=" (for the third type queries),  "<=" (for the fourth type queries).  All values of x are integer and meet the inequation  - 109 ≤ x ≤ 109. The answer is an English letter "Y" (for "yes") or "N" (for "no"). Consequtive elements in lines are separated by a single space.

Print any of such integers y, that the answers to all the queries are correct. The printed number y must meet the inequation  - 2·109 ≤ y ≤ 2·109. If there are many answers, print any of them. If such value doesn't exist, print word "Impossible" (without the quotes).

#!/usr/bin/ruby
A=['>','<','<=','>=']
min=-10**9-1
max=10**9+1
gets.to_i.times{
line=gets.chomp.split
line[0]=A.index(line[0])
line[0]^=2 if line[2]=='N'
line[1]=line[1].to_i
if line[0]==0
	min=[line[1]+1,min].max
elsif line[0]==1
	max=[line[1]-1,max].min
elsif line[0]==2
	max=[line[1],max].min
else
	min=[line[1],min].max
end
}
puts min<=max ? min : 'Impossible'

min = 10 ** 9 * (-2)
max = 10 ** 9 * 2

increase_min = proc { |num| min = (min >= num) ? min : num }
decrease_max = proc { |num| max = (max <= num) ? max : num }

n = gets.chomp.to_i
n.times do
    sign, num, answer = gets.chomp.split
    num = num.to_i

    case sign
    when ">"
        increase_min[num + 1] if answer == "Y"
        decrease_max[num] if answer == "N"
    when ">="
        increase_min[num] if answer == "Y"
        decrease_max[num - 1] if answer == "N"
    when "<"
        decrease_max[num - 1] if answer == "Y"
        increase_min[num] if answer == "N"
    when "<="
        decrease_max[num] if answer == "Y"
        increase_min[num + 1] if answer == "N"
    end
end

if min > max
    print "Impossible"
else
    print min
end

class ProblemA
  INF = 2e9.to_i

  def initialize
    @dats = STDIN.read.split("\n")
    @min, @max = -INF, INF
    @qnum = @dats[0].to_i
  end

  def solve
    possible = true
    (1..@qnum).each do |row|
      question = @dats[row]
      operator, num, ans = question.split(" ").map {|s| s = s.gsub(" ", "")}
      num = num.to_i

      ret = case operator
            when ">="
              ans == "Y" ? update(operator, num) : update("<", num)
            when "<="
              ans == "Y" ? update(operator, num) : update(">", num)
            when ">"
              ans == "Y" ? update(operator, num) : update("<=", num)
            when "<"
              ans == "Y" ? update(operator, num) : update(">=", num)
            end
      (possible = false and break) unless ret
    end
    if possible
      print @min
    else
      print "Impossible"
    end
  end

  def update(operator, num)
    case operator
    when ">="
      @min = num if @min < num
    when "<="
      @max = num if @max > num
    when ">"
      @min = num+1 if @min < num+1
    when "<"
      @max = num-1 if @max > num-1
    end
    @min > @max ? false : true
  end
end

solver = ProblemA.new
solver.solve

n = gets.chomp.to_i
max = (10 ** 9) * 2
min = -max
n.times do
    sign, x, ans = gets.chomp.split(/ /)
    x = x.to_i
    if ans == "N"
        case sign
        when '>'
            sign = '<='
        when '>='
            sign = '<'
        when '<'
            sign = '>='
        when '<='
            sign = '>'
        end
    end
    case sign
    when '>='
        min = [min, x].max
    when '>'
        min = [min, x + 1].max
    when '<'
        max = [max, x - 1].min
    when '<='
        max = [max, x].min
    end
end
if min <= max
    puts min
else
    puts "Impossible"
end

n = gets.chomp.to_i

a = 2*-10e8
b = 2* 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b >= md[2].to_i
			b = md[2].to_i - 1

			b += 1 if token.length > 1
		end
	end

	if token[0] == ('>')
		if a <= md[2].to_i
			a = md[2].to_i + 1

			a -= 1 if token.length > 1
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

def reverse_signs(s)
	case s
	when ">="
		return "<"
	when ">"
		return "<="
	when "<"
		return ">="
	when "<="
		return ">"
	end

end

def calc(s,no,start,finish)
	case s
	when ">="
		start = no if no > start
	when ">"
		start = no + 1 if no + 1 > start
	when "<"
		finish = no - 1 if no - 1 < finish
	when "<="
		finish = no	if no < finish
	end
	return start,finish
end

n = gets.to_i
start = -(10 ** 9) * 2
finish = (10 ** 9) * 2

n.times do
	s,no,ans = gets.split(" ")
	no = no.to_i
	# puts "#{s},#{no},#{ans}"
	if ans == "Y"
		# puts "here"
		start,finish =  calc(s,no,start,finish)
		# puts "#{start},#{finish}"
	else
		start,finish =  calc(reverse_signs(s),no,start,finish)
	end
end
# puts start
# puts finish
if start <= finish
	puts "#{start}"
else
	puts "Impossible"
end

a = 2 * -10 ** 9
b = 2 * 10 ** 9
n = gets.to_i
t = { ">=" => "<", "<=" => ">", ">" => "<=", "<" => ">=" }
n.times do
	s, c, an = gets.split
	s = t[s] if an.chomp == "N"
	c = c.to_i
	case s
		when ">="
			a = c if c > a
		when ">"
			a = c + 1 if c + 1 > a
		when "<="
			b = c if c < b
		when "<"
			b = c - 1 if c - 1 < b
	end
end

puts a if (a..b).size.nonzero?
puts "Impossible" if (a..b).size.zero?

#f = File.open('test1.txt', 'r')
f = STDIN

n = f.gets.chomp.to_i
left, right = -2_000_000_000, 2_000_000_000
op = {
  ">" => "<=",
  "<" => ">=",
  ">=" => "<",
  "<=" => ">"
}
n.times do
  sign, x, answer = f.gets.chomp.split
  sign = op[sign] if answer == 'N'
  case sign
    when '<' #
      right = [right, x.to_i - 1].min
    when '>' #
      left = [left, x.to_i + 1].max
    when '<=' #
      right = [right, x.to_i].min
    when '>=' #
      left = [left, x.to_i].max
  end
end

puts (left <= right ? left : 'Impossible')

mn = -0x3f3f3f3f
mx = -mn
gets.to_i.times do
	op, x, ans = gets.split
	x = x.to_i
	(op = "<") && (x = x + 1) if op == "<="
	(op = ">=") && (x = x + 1) if op == ">"
	if op == ">=" && ans == "Y" || op == "<" && ans == "N"
		mn = [mn, x].max
	else
		mx = [mx, x-1].min
	end
end
puts mn <= mx ? mn : "Impossible"

#!/usr/bin/ruby
A=['>','<','<=','>=']
min=-10**9
max=10**9
gets.to_i.times{
line=gets.chomp.split
line[0]=A.index(line[0])
line[0]^=2 if line[2]=='N'
line[1]=line[1].to_i
if line[0]==0
	min=line[1]+1
elsif line[0]==1
	max=line[1]-1
elsif line[0]==2
	max=line[1]
else
	min=line[1]
end
}
puts min<=max ? min : 'Impossible'

#!/usr/bin/ruby
A=['>','<','<=','>=']
min=-10**9
max=10**9
gets.to_i.times{
line=gets.chomp.split
line[0]=A.index(line[0])
line[0]^=2 if line[2]=='N'
line[1]=line[1].to_i
if line[0]==0
	min=[line[1]+1,min].max
elsif line[0]==1
	max=[line[1]-1,max].min
elsif line[0]==2
	max=[line[1],max].min
else
	min=[line[1],min].max
end
}
puts min<=max ? min : 'Impossible'

min = 10 ** 9 * (-1)
max = 10 ** 9

n = gets.chomp.to_i
n.times do
    sign, num, answer = gets.chomp.split
    next if answer == "N"

    num = num.to_i
    case sign
    when ">"
        min = (min > num) ? min : num + 1
    when "<"
        max = (max < num) ? max : num - 1
    when ">="
        min = (min >= num) ? min : num
    when "<="
        max = (max <= num) ? max : num
    end
end

if min > max
    print "Impossible"
else
    print min
end

min = 10 ** 9 * (-1)
max = 10 ** 9

increase_min = proc { |num| min = (min >= num) ? min : num }
decrease_max = proc { |num| max = (max <= num) ? max : num }

n = gets.chomp.to_i
n.times do
    sign, num, answer = gets.chomp.split
    num = num.to_i

    case sign
    when ">"
        increase_min[num + 1] if answer == "Y"
        decrease_max[num] if answer == "N"
    when ">="
        increase_min[num] if answer == "Y"
        decrease_max[num - 1] if answer == "N"
    when "<"
        decrease_max[num - 1] if answer == "Y"
        increase_min[num] if answer == "N"
    when "<="
        decrease_max[num] if answer == "Y"
        increase_min[num + 1] if answer == "N"
    end
end

if min > max
    print "Impossible"
else
    print min
end

class ProblemA
  INF = 2e10
  def initialize
    @dats = STDIN.read.split("\n")
    @min, @max = -INF, INF
    @qnum = @dats[0].to_i
  end

  def solve
    possible = true
    (1..@qnum).each do |row|
      question = @dats[row]
      operator, num, ans = question.split(" ").map {|s| s = s.gsub(" ", "")}
      num = num.to_i

      ret = case operator
            when ">="
              ans == "Y" ? update(operator, num) : update("<", num)
            when "<="
              ans == "Y" ? update(operator, num) : update(">", num)
            when ">"
              ans == "Y" ? update(operator, num) : update("<=", num)
            when "<"
              ans == "Y" ? update(operator, num) : update(">=", num)
            end
      (possible = false and break) unless ret
    end
    if possible
      print @min
    else
      print "Impossible"
    end
  end

  def update(operator, num)
    print "#{operator} #{num}\n"
    case operator
    when ">="
      @min = num if @min < num
    when "<="
      @max = num if @max > num
    when ">"
      @min = num+1 if @min < num+1
    when "<"
      @max = num-1 if @max > num-1
    end
    @min > @max ? false : true
  end
end

solver = ProblemA.new
solver.solve

class ProblemA
  INF = 2e10.to_i

  def initialize
    @dats = STDIN.read.split("\n")
    @min, @max = -INF, INF
    @qnum = @dats[0].to_i
  end

  def solve
    possible = true
    (1..@qnum).each do |row|
      question = @dats[row]
      operator, num, ans = question.split(" ").map {|s| s = s.gsub(" ", "")}
      num = num.to_i

      ret = case operator
            when ">="
              ans == "Y" ? update(operator, num) : update("<", num)
            when "<="
              ans == "Y" ? update(operator, num) : update(">", num)
            when ">"
              ans == "Y" ? update(operator, num) : update("<=", num)
            when "<"
              ans == "Y" ? update(operator, num) : update(">=", num)
            end
      (possible = false and break) unless ret
    end
    if possible
      print @min
    else
      print "Impossible"
    end
  end

  def update(operator, num)
    case operator
    when ">="
      @min = num if @min < num
    when "<="
      @max = num if @max > num
    when ">"
      @min = num+1 if @min < num+1
    when "<"
      @max = num-1 if @max > num-1
    end
    @min > @max ? false : true
  end
end

solver = ProblemA.new
solver.solve

class ProblemA
  INF = 2e10
  def initialize
    @dats = STDIN.read.split("\n")
    @min, @max = -INF, INF
    @qnum = @dats[0].to_i
  end

  def solve
    possible = true
    (1..@qnum).each do |row|
      question = @dats[row]
      operator, num, ans = question.split(" ").map {|s| s = s.gsub(" ", "")}
      num = num.to_i

      ret = case operator
            when ">="
              ans == "Y" ? update(operator, num) : update("<", num)
            when "<="
              ans == "Y" ? update(operator, num) : update(">", num)
            when ">"
              ans == "Y" ? update(operator, num) : update("<=", num)
            when "<"
              ans == "Y" ? update(operator, num) : update(">=", num)
            end
      (possible = false and break) unless ret
    end
    if possible
      print @min
    else
      print "Impossible"
    end
  end

  def update(operator, num)
    case operator
    when ">="
      @min = num if @min < num
    when "<="
      @max = num if @max > num
    when ">"
      @min = num+1 if @min < num+1
    when "<"
      @max = num-1 if @max > num-1
    end
    @min > @max ? false : true
  end
end

solver = ProblemA.new
solver.solve

n = gets.chomp.to_i
max = (10 ** 9) * 2
min = -max
n.times do
    sign, x, ans = gets.chomp.split(/ /)
    x = x.to_i
    if ans == "N"
        case sign
        when '>'
            sign = '<='
        when '>='
            sign = '<'
        when '<'
            sign = '>='
        when '<='
            sign = '>'
        end
    end
    case sign
    when '>='
        min = [min, x].max
    when '>'
        min = [min, x + 1].max
    when '<'
        max = [max, x - 1].min
    when '<='
        max = [max, x].min
    end
end
puts "#{min} #{max}"
if min <= max
    puts min
else
    puts "Impossible"
end

n = gets.chomp.to_i
min = -1000000000
max = -min
n.times do
    sign, x, ans = gets.chomp.split(/ /)
    x = x.to_i
    if ans == "N"
        case sign
        when '>'
            sign = '<='
        when '>='
            sign = '<'
        when '<'
            sign = '>='
        when '<='
            sign = '>'
        end
    end
    case sign
    when '>='
        min = [min, x].max
    when '>'
        min = [min, x + 1].max
    when '<'
        max = [max, x - 1].min
    when '<='
        max = [max, x].min
    end
end
if min <= max
    puts min
else
    puts "Impossible"
end

n = gets.chomp.to_i
min = -1000000000
max = -min
n.times do
    sign, x, ans = gets.chomp.split(/ /)
    x = x.to_i
    if ans == "N"
        case sign
        when '>'
            sign = '<='
        when '>='
            sign = '<'
        when '<'
            sign = '>='
        when '<='
            sign = '>'
        end
    end
    case sign
    when '>', '>='
        min = [min, x].max
    when '<', '<='
        max = [max, x].min
    end
end
if min <= max
    puts min
else
    puts "Impossible"
end

n = gets.chomp.to_i

a = -10e8
b = 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b > md[2].to_i
			b = md[2].to_i - 1
		end

		if token.length > 1
			b += 1
		end
	end

	if token[0].eql?('>')
		if a < md[2].to_i
			a = md[2].to_i + 1
		end

		if token.length > 1
			a -= 1
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = 2*-10e8
b = 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b > md[2].to_i
			b = md[2].to_i - 1

			b += 1 if token.length > 1
		end
	end

	if token[0].eql?('>')
		if a < md[2].to_i
			a = md[2].to_i + 1

			a -= 1 if token.length > 1
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = -10e9
b = 10e9
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)
	if md[3] =~ /^Y/
		if md[1][0] == '<'
			if b > md[2].to_i
				b = md[2].to_i - 1
			end

			if md[1].length > 1
				b += 1
			end
		end

		if md[1][0].eql?('>')
			if a < md[2].to_i
				a = md[2].to_i + 1
			end

			if md[1].length > 1
				a -= 1
			end
		end
	end
end

# puts a
# puts b
if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = 2*-10e8
b = 2* 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b > md[2].to_i
			b = md[2].to_i - 1

			b += 1 if token.length > 1
		end
	end

	if token[0].eql?('>')
		if a < md[2].to_i
			a = md[2].to_i + 1

			a -= 1 if token.length > 1
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = -10e8
b = 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b > md[2].to_i
			b = md[2].to_i - 1

			b += 1 if token.length > 1
		end
	end

	if token[0].eql?('>')
		if a < md[2].to_i
			a = md[2].to_i + 1

			a -= 1 if token.length > 1
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = 2*-10e8
b = 2* 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b > md[2].to_i
			b = md[2].to_i - 1

			b += 1 if token.length > 1
		end
	end

	if token[0].eql?('>')
		if a < md[2].to_i
			a = md[2].to_i + 1

			a -= 1 if token.length > 1
		end
	end
end

if a >= b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = -10e9
b = 10e9
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)
	if md[3] =~ /^Y/
		if md[1][0] == '<'
			if b > md[2].to_i
				b = md[2].to_i - 1
			end

			if md[1].length > 1
				b += 1
			end
		end

		if md[1][0].eql?('>')
			if a < md[2].to_i
				a = md[2].to_i + 1
			end

			if md[1].length > 1
				a -= 1
			end
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = -10e8
b = 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)
	if md[3] =~ /^Y/
		if md[1][0] == '<'
			if b > md[2].to_i
				b = md[2].to_i - 1
			end

			if md[1].length > 1
				b += 1
			end
		end

		if md[1][0].eql?('>')
			if a < md[2].to_i
				a = md[2].to_i + 1
			end

			if md[1].length > 1
				a -= 1
			end
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

def reverse_signs(s)
	case s
	when ">="
		return "<"
	when ">"
		return "<="
	when "<"
		return ">="
	when "<="
		return ">"
	end

end

def calc(s,no,start,finish)
	case s
	when ">="
		start = no if no > start
	when ">"
		start = no + 1 if no + 1 > start
	when "<"
		finish = no - 1 if no - 1 < finish
	when "<="
		finish = no	if no < finish
	end
	return start,finish
end

n = gets.to_i
start = -10 ** 9
finish = 10 ** 9
n.times do
	s,no,ans = gets.split(" ")
	no = no.to_i
	# puts "#{s},#{no},#{ans}"
	if ans == "Y"
		puts "here"
		start,finish =  calc(s,no,start,finish)
		# puts "#{start},#{finish}"
	else
		start,finish =  calc(reverse_signs(s),no,start,finish)
	end
end
if start <= finish
	puts "#{start}"
else
	puts "Impossible"
end

def reverse_signs(s)
	case s
	when ">="
		return "<"
	when ">"
		return "<="
	when "<"
		return ">="
	when "<="
		return ">"
	end

end

def calc(s,no,start,finish)
	case s
	when ">="
		start = no if no > start
	when ">"
		start = no + 1 if no + 1 > start
	when "<"
		finish = no - 1 if no - 1 < finish
	when "<="
		finish = no	if no < finish
	end
	return start,finish
end

n = gets.to_i
start = -10 ** 9
finish = 10 ** 9
n.times do
	s,no,ans = gets.split(" ")
	no = no.to_i
	# puts "#{s},#{no},#{ans}"
	if ans == "Y"
		# puts "here"
		start,finish =  calc(s,no,start,finish)
		# puts "#{start},#{finish}"
	else
		start,finish =  calc(reverse_signs(s),no,start,finish)
	end
end
if start <= finish
	puts "#{start}"
else
	puts "Impossible"
end

a = -10 ** 9
b = 10 ** 9
n = gets.to_i
t = { ">=" => "<", "<=" => ">", ">" => "<=", "<" => ">=" }
n.times do
	s, c, an = gets.split
	s = t[s] if an.chomp == "N"
	c = c.to_i
	case s
		when ">="
			a = c
		when ">"
			a = c + 1
		when "<="
			b = c
		when "<"
			b = c - 1
	end
end

puts a if (a..b).size.nonzero?
puts "Impossible" if (a..b).size.zero?

a = -10 ** 9
b = 10 ** 9
n = gets.to_i
t = { ">=" => "<", "<=" => ">", ">" => "<=", "<" => ">=" }
n.times do
	s, c, an = gets.split
	s = t[s] if an.chomp == "N"
	c = c.to_i
	case s
		when ">="
			a = c if c > a
		when ">"
			a = c + 1 if c + 1 > a
		when "<="
			b = c if c < b
		when "<"
			b = c - 1 if c - 1 < b
	end
end

puts a if (a..b).size.nonzero? and b >= -10 ** 9 and a <= 10 ** 9
puts "Impossible" unless (a..b).size.nonzero? and b >= -10 ** 9 and a <= 10 ** 9

a = -10 ** 9
b = 10 ** 9
n = gets.to_i
t = { ">=" => "<", "<=" => ">", ">" => "<=", "<" => ">=" }
n.times do
	s, c, an = gets.split
	s = t[s] if an.chomp == "N"
	c = c.to_i
	case s
		when ">="
			a = c if c > a
		when ">"
			a = c + 1 if c + 1 > a
		when "<="
			b = c if c < b
		when "<"
			b = c - 1 if c - 1 < b
	end
end

puts a if (a..b).size.nonzero?
puts "Impossible" if (a..b).size.zero?

a = -10 ** 9 - 1
b = 10 ** 9 + 1
n = gets.to_i
t = { ">=" => "<", "<=" => ">", ">" => "<=", "<" => ">=" }
n.times do
	s, c, an = gets.split
	s = t[s] if an.chomp == "N"
	c = c.to_i
	case s
		when ">="
			a = c if c > a
		when ">"
			a = c + 1 if c + 1 > a
		when "<="
			b = c if c < b
		when "<"
			b = c - 1 if c - 1 < b
	end
end

puts a if (a..b).size.nonzero? and a != -10 ** 9 - 1 and b != 10 ** 9 + 1
puts "Impossible" unless (a..b).size.nonzero? and a != -10 ** 9 - 1 and b != 10 ** 9 + 1

#f = File.open('test1.txt', 'r')
f = STDIN

n = f.gets.chomp.to_i
left, right = -2_000_000_000, 2_000_000_000
op = {
  ">" => "<",
  "<" => ">",
  ">=" => "<=",
  "<=" => ">="
}
n.times do
  sign, x, answer = f.gets.chomp.split
  sign = op[sign] if answer == 'N'
  case sign
    when '<' #
      right = [right, x.to_i - 1].min
    when '>' #
      left = [left, x.to_i + 1].max
    when '<=' #
      right = [right, x.to_i].min
    when '>=' #
      left = [left, x.to_i].max
  end
end

puts (left <= right ? left : 'Impossible')


Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.

The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.

Print a single number — the number of distinct letters in Anton's set.

#puts "Enter the string\n"
s = gets.chomp.to_s
l = s.length
#puts l
a = [l]
j = 0
for i in 0...l-1 do
    if s[i].ord >= 97 && s[i].ord <= 122
        a[j] = s[i]
        j += 1
        #puts a[j-1]
    end
end

#puts j (size of array a)
if j == 0
    puts 0
elsif j == 1
    puts 1
else
    a =  a.sort
    c = 0
    for k in 0..j do
        if a[k] != a[k+1]
            c += 1
        end
    end
    puts c
end

set = gets.chomp
puts set.tr('{},','').split(' ').uniq.length

require 'set'
puts gets.chomp.gsub(/[{} ]/,"").split(",").to_set.count

#!/usr/bin/env ruby

require 'set'

s = Set.new STDIN.gets.strip[1...-1].split(',').map(&:strip)

puts s.size

a = gets.chomp.chars
a[-1] = a[0] = ""
p a.join("").split(", ").uniq.size

a=gets.chomp.split("")
a.delete("{")
a.delete("}")
a.delete(" ")
a.delete(",")
a.uniq!
puts "#{a.length}"

ar = gets.chomp.split(/[^[:lower:]]/).select{|x| x.length>0}
hs = Hash.new 0
ar.each{|x| hs[x]+=1}
puts hs.length

letters = gets
letters = letters.slice(1, letters.length - 3).split(', ')

puts letters.uniq.length

#!/usr/bin/ruby
p gets.chomp[1...-1].split(', ').uniq.size

require 'set'

set = Set.new
s = gets.chomp
s.gsub!(/{|}| /, "")

s.split(",").each { |c| set << c }
puts set.length

s = gets.chomp
l = s.length
c={}
for i in 0...l
if s[i]=="{" || s[i]=="}"||s[i]==","||s[i]==" " then next
elsif c["#{s[i]}"]==nil then
    c["#{s[i]}"]=1
end
end
puts c.length

array = gets.delete('{}').chomp.split(", ")
puts array.uniq.count

s = gets.chomp
s =  s.delete!  "{, } "
s =  s.chars.uniq
puts s.size

numbers = gets.strip[1..-2].split(', ')

set = Hash.new(0)
numbers.each do |num|
  set[num] += 1
end

puts set.size

input = gets.chomp
letter = input.gsub(/[^a-zA-Z ]/," ").split(" ")
counter = {}
for i in 0...letter.length
	counter[letter[i]] = 1
end
sum = 0
counter.each do |key, value|
	sum += value
end
puts sum

s = $stdin.readline

b = s.scan(/[a-z]/)

puts b.uniq.count

def run
  h = Hash.new(0)
  $stdin.gets.gsub(/[{}]/, "").split(",").map(&:strip).each do |c|
    h[c] += 1 if c != ""
  end
  puts h.size
end

run if $0 == __FILE__

s = gets.chomp()
c = 0
('a'..'z').each do |char|
    if s.include? char
        c += 1
    end
end
puts(c)

puts gets.chomp.gsub(/{|}/, '').split(', ').uniq.count

s = gets.chomp
puts s.gsub("{", "").gsub("}", "").split(",").map(&:strip).uniq.count

line = gets.chomp
letters = line[1..(line.length - 2)].split(/, /)
letters.uniq!
puts letters.length

require 'set'
s=gets.chomp
s=s.slice(1,s.size-2).split(", ")
puts Set.new(s).count

s=gets.chomp
s.gsub!('{','').gsub!('}','')
arr = s.split(',').map(&:strip)
co = {}
arr.each do |a|
  if co[a].nil?
    co[a] = 1
  else
  co[a] +=1
  end
end

puts co.keys.length

a=gets.chomp
if a.length==2
	puts "0"
elsif a.length==3
	puts "1"
else
	puts a[1..(a.length-2)].split(",").map{|s| s.lstrip.rstrip}.uniq.length
end

hash = Hash.new(0)
gets.chomp.slice(1...-1).split(/,\s*/).each {|e| hash[e] +=1}
puts hash.length

require 'set'
s=gets
s=s.slice(1,s.size-2).split(", ")
puts Set.new(s).count


Ivan is collecting coins. There are only $$$N$$$ different collectible coins, Ivan has $$$K$$$ of them. He will be celebrating his birthday soon, so all his $$$M$$$ freinds decided to gift him coins. They all agreed to three terms:  Everyone must gift as many coins as others. All coins given to Ivan must be different. Not less than $$$L$$$ coins from gifts altogether, must be new in Ivan's collection.But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms.

The only line of input contains 4 integers $$$N$$$, $$$M$$$, $$$K$$$, $$$L$$$ ($$$1 \le K \le N \le 10^{18}$$$; $$$1 \le M, \,\, L \le 10^{18}$$$) — quantity of different coins, number of Ivan's friends, size of Ivan's collection and quantity of coins, that must be new in Ivan's collection.

Print one number — minimal number of coins one friend can gift to satisfy all the conditions. If it is impossible to satisfy all three conditions print "-1" (without quotes).

NoteIn the first test, one coin from each friend is enough, as he will be presented with 15 different coins and 13 of them will definitely be new.In the second test, Ivan has 11 friends, but there are only 10 different coins. So all friends can't present him different coins.

n,m,k,l=gets.split.map &:to_i
x=(k+l+m-1)/m
p m*x>n ? -1 : x

N,M,K,L=gets.split.map &:to_i
if M>N
    puts -1
    exit
end
d=N/M
x=N-K
if d*M-K<L
    puts -1
    exit
end
puts (L+K+M-1)/M

#N different collectible coins,
#Ivan has K of them
#M freinds
#L coins from gifts altogether, must be new in Ivan's collection

N, M, K, L = gets.split(" ").map(&:to_i)

#example 1
# N, M, K, L = "20 15 2 3".split(" ").map(&:to_i)
#assert 1

#example 2
# N, M, K, L = "10 11 2 4".split(" ").map(&:to_i)
#assert -1

def condition_all_coins_different( friends, coins_per_friend, total_collectable_coins )
	return false if friends * coins_per_friend > total_collectable_coins
	true
end

def condition_minimum_amount_of_new_coins( minimum_new_coins, total_coins_gifted, total_collectable_coins, already_present_coins )
	#possible_new_coins = total_collectable_coins - already_present_coins
	total_coins_gifted >= minimum_new_coins + already_present_coins
end

coins_per_friend = ( K + L ) / M
until condition_minimum_amount_of_new_coins( L, M * coins_per_friend, N, K )
 #condition_all_coins_different( M, coins_per_friend, N ) and
	coins_per_friend += 1
end

# puts coins_per_friend

if condition_all_coins_different( M, coins_per_friend, N)
	puts coins_per_friend
else
	puts -1
end

n,m,k,l=gets.split.map &:to_i
x=(k+l)/m
p m*x>n ? x : -1

n,m,k,l=gets.split.map &:to_i
x=(k+l)/m
p m*x>n ? -1 : x

n,m,k,l=gets.split.map &:to_i
x=(k+l+m-1)/m
p m*x>n ? x : -1


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