Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!This contest consists of n problems, and Pasha solves ith problem in ai time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. Pasha can send any number of solutions at the same moment.Unfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during m time periods, jth period is represented by its starting moment lj and ending moment rj. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment T iff there exists a period x such that lx ≤ T ≤ rx.Pasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have solutions to all problems submitted, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems.

The first line contains one integer n (1 ≤ n ≤ 1000) — the number of problems. The second line contains n integers ai (1 ≤ ai ≤ 105) — the time Pasha needs to solve ith problem. The third line contains one integer m (0 ≤ m ≤ 1000) — the number of periods of time when the website is working. Next m lines represent these periods. jth line contains two numbers lj and rj (1 ≤ lj < rj ≤ 105) — the starting and the ending moment of jth period. It is guaranteed that the periods are not intersecting and are given in chronological order, so for every j > 1 the condition lj > rj - 1 is met.

If Pasha can solve and submit all the problems before the end of the contest, print the minimal moment of time by which he can have all the solutions submitted. Otherwise print "-1" (without brackets).

NoteIn the first example Pasha can act like this: he solves the second problem in 4 units of time and sends it immediately. Then he spends 3 time units to solve the first problem and sends it 7 time units after the contest starts, because at this moment the website starts working again.In the second example Pasha invents the solution only after the website stops working for the last time.In the third example Pasha sends the solution exactly at the end of the first period.

gets
s=gets.split.map(&:to_i).reduce(:+)
gets.to_i.times{
	l,r=gets.split.map(&:to_i)
	s<=r&&(p [l,s].max;exit)
}
p -1

n = Integer(gets.chomp)
solve = Array.new(n)
solve = gets.chomp.split.map &:to_i
m = Integer(gets.chomp)
period = Array.new(m)
for i in 0...m
    period[i] = gets.chomp.split.map &:to_i
end

time_solve = 0
for i in 0...n
    time_solve += solve[i]
end
output = -1
for i in 0..m-1
    if time_solve <= period[i][1] && time_solve >= period[i][0]
        output = time_solve
        break
    elsif  i != m - 1 && time_solve < period[i + 1][0] && time_solve > period[i][1]
        output = period[i + 1][0]
        break
    end
end

for i in 0...m
    if time_solve <= period[i][0]
        output = period[i][0]
        break
    elsif time_solve <= period[i][1]
        output = time_solve
        break
    end
end

puts output

n = Integer(gets.chomp)
solve = Array.new(n)
solve = gets.chomp.split.map &:to_i
m = Integer(gets.chomp)
period = Array.new(m)
for i in 0...m
    period[i] = gets.chomp.split.map &:to_i
end

time_solve = 0
for i in 0...n
    time_solve += solve[i]
end
output = -1
for i in 0...m
    if period[i][1] >= time_solve && time_solve >= period[i][0]
        output = time_solve
    break
        end
end

puts output

n = Integer(gets.chomp)
solve = Array.new(n)
solve = gets.chomp.split.map &:to_i
m = Integer(gets.chomp)
period = Array.new(m)
for i in 0...m
    period[i] = gets.chomp.split.map &:to_i
end

time_solve = 0
for i in 0...n
    time_solve += solve[i]
end
output = -1
for i in 0...m
    for j in 0..1
        if period[i][j] >= time_solve
            output = period[i][j]
            break
        end
    end
end

puts output

n = Integer(gets.chomp)
solve = Array.new(n)
solve = gets.chomp.split.map &:to_i
m = Integer(gets.chomp)
period = Array.new(m)
for i in 0...m
    period[i] = gets.chomp.split.map &:to_i
end

time_solve = 0
for i in 0...n
    time_solve += solve[i]
end
output = -1
for i in 0..m-1
    if time_solve <= period[i][1] && time_solve >= period[i][0]
        output = time_solve
        break
    elsif  i != m - 1 && time_solve < period[i + 1][0] && time_solve > period[i][1]
        output = period[i + 1][0]
        break
    end
end

for i in 0...m
    if time_solve <= period[i][0]
        output = period[i][1]
        break
    elsif time_solve <= period[i][1]
        output = time_solve
        break
    end
end

puts output

n = Integer(gets.chomp)
solve = Array.new(n)
solve = gets.chomp.split.map &:to_i
m = Integer(gets.chomp)
period = Array.new(m)
for i in 0...m
    period[i] = gets.chomp.split.map &:to_i
end

time_solve = 0
for i in 0...n
    time_solve += solve[i]
end
output = -1
for i in 0...m
    for j in 0..1
        if period[i][j] >= time_solve
            output = time_solve
            break
        end
    end
end

puts output

n = Integer(gets.chomp)
solve = Array.new(n)
solve = gets.chomp.split.map &:to_i
m = Integer(gets.chomp)
period = Array.new(m)
for i in 0...m
    period[i] = gets.chomp.split.map &:to_i
end

time_solve = 0
for i in 0...n
    time_solve += solve[i]
end
output = -1
for i in 0..m-1
    if time_solve <= period[i][1] && time_solve >= period[i][0]
        output = time_solve
        break
    elsif  i != m - 1 && time_solve < period[i + 1][0] && time_solve > period[i][1]
        output = period[i + 1][0]
        break
    end
end

puts output

n = Integer(gets.chomp)
solve = Array.new(n)
solve = gets.chomp.split.map &:to_i
m = Integer(gets.chomp)
period = Array.new(m)
for i in 0...m
    period[i] = gets.chomp.split.map &:to_i
end

time_solve = 0
for i in 0...n
    time_solve += solve[i]
end
output = -1
for i in 0...m-1
    if period[i][1] >= time_solve && time_solve >= period[i][0]
        output = time_solve
        break
    elsif time_solve < period[i + 1][0] && time_solve > period[i][1]
        output = period[i + 1][0]
        break
    end
end

puts output

n = Integer(gets.chomp)
solve = Array.new(n)
solve = gets.chomp.split.map &:to_i
m = Integer(gets.chomp)
period = Array.new(m)
for i in 0...m
    period[i] = gets.chomp.split.map &:to_i
end

time_solve = 0
for i in 0...n
    time_solve += solve[i]
end
output = -1
for i in 1...m
    if period[i][1] >= time_solve && time_solve >= period[i][0]
        output = time_solve
        break
    elsif time_solve > period[i - 1][1] && time_solve < period[i][0]
        output = period[i][0]
        break
    end
end

puts output


You are given a positive decimal number x.Your task is to convert it to the "simple exponential notation".Let x = a·10b, where 1 ≤ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b.

The only line contains the positive decimal number x. The length of the line will not exceed 106. Note that you are given too large number, so you can't use standard built-in data types "float", "double" and other.

Print the only line — the "simple exponential notation" of the given number x.

require'bigdecimal';x=BigDecimal(gets).split;s=x[1][0];s<<'.'+x[1][1..-1] if x[1].size>1;s<<'E%d'%[x[3]-1] if x[3]!=1;puts s


A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.

The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai < bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.

If the required division into teams doesn't exist, print number -1. Otherwise, print  lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team.  If there are multiple answers, you are allowed to print any of them.

n, m=gets.split.map(&:to_i)
c=n/3
s=[nil]*(n+1)
t=1
m.times do
  a, b=gets.split.map(&:to_i)
  if s[a].nil?&&s[b].nil?
    if t > c
      puts '-1'
      exit
    end
    s[a]=s[b]=t
    t+=1
  elsif s[a].nil?
    s[a]=s[b]
  elsif s[b].nil?
    s[b]=s[a]
  elsif s[a]!=s[b]
    puts '-1'
    exit
  end
end
h=Hash.new { |h, k| h[k]=[] }
s.each_with_index { |a, t| h[a]<<t if a }
if h.find {|k,v| v.size>3}
  puts '-1'
  exit
end
f=s.each_index.select { |i| !s[i] }
f.shift
for t in 1..c do
  r=h[t]
  n=r.size
  puts (r | f.pop(3-n)).join ' '
end

def dfs(now, parent, group)
    group.push now
    $vis[now] = true
    $path[now].each do |to|
        next if to == parent or $vis[to]
        dfs(to, now, group)
    end
    return group
end
n, m = gets.split(' ').map { |i|  i.to_i }
$vis = Array.new(50, false)
$path = Array.new(50){Array.new}
groups = []
can = true
m.times do
    x, y = gets.split(' ').map { |i| i.to_i}
    $path[x].push y
    $path[y].push x
end
n.times do |i|
    next if $vis[i+1]
    group = dfs(i+1, -1, [])
    can = false if group.size > 3
    $vis[i+1] = false if group.size == 1
    groups.push group unless group.size == 1
end
if can
    groups.each do |g|
        next if g.size >= 3
        while g.size != 3
            find = false
            for i in 1..n
                next if $vis[i]
                g.push i
                $vis[i] = true
                find = true
                break
            end
            if not find
                can = false
                break
            end
        end
    end
    group = []
    for i in 1..n
        next if $vis[i]
        group.push i
        if group.size == 3
            groups.push group
            group = []
        end
    end
end
if can
    groups.each do |g|
        puts g.join(' ')
    end
else
    puts -1
end

def dfs(now, parent, group)
    group.push now
    $vis[now] = true
    $path[now].each do |to|
        next if to == parent or $vis[to]
        dfs(to, now, group)
    end
    return group
end
n, m = gets.split(' ').map { |i|  i.to_i }
$vis = Array.new(50, false)
$path = Array.new(50){Array.new}
groups = []
can = true
m.times do
    x, y = gets.split(' ').map { |i| i.to_i}
    $path[x].push y
    $path[y].push x
end
n.times do |i|
    next if $vis[i+1]
    group = dfs(i+1, -1, [])
    can = false if group.size > 3
    while group.size < 3
        find = false
        for i in 1..n
            next if $vis[i]
            if $path[i].size == 0
                group.push i
                $vis[i] = true
                find = true
                break
            end
        end
        if not find
            can = false
            break
        end
    end
    groups.push group
end
if can
    groups.each do |g|
        puts g.join(' ')
    end
else
    puts -1
end

def dfs(now, parent, group)
    group.push now
    $vis[now] = true
    $path[now].each do |to|
        next if to == parent or $vis[to]
        dfs(to, now, group)
    end
    return group
end
n, m = gets.split(' ').map { |i|  i.to_i }
$vis = Array.new(50, false)
$path = Array.new(50){Array.new}
groups = []
can = true
m.times do
    x, y = gets.split(' ').map { |i| i.to_i}
    $path[x].push y
    $path[y].push x
end
n.times do |i|
    next if $vis[i+1]
    group = dfs(i+1, -1, [])
    can = false if group.size > 3
    while group.size < 3
        find = false
        for i in 1..n
            next if $vis[i]
            if $path[i].size == 0
                group.push i
                $vis[i] = true
                find = true
                break
            end
        end
        break unless find
    end
    groups.push group
end
if can
    groups.each do |g|
        puts g.join(' ')
    end
else
    puts -1
end

n,m=gets.split.map(&:to_i)
s=[nil]*(n+1)
t=1
m.times do
  a,b=gets.split.map(&:to_i)
  if s[a].nil?&&s[b].nil?
    s[a]=s[b]=t
    t+=1
  elsif s[a].nil?
    s[a]=s[b]
  elsif s[b].nil?
    s[b]=s[a]
  elsif s[a]!=s[b]
    puts'-1'
    exit
  end
end
h=Hash.new{|h,k|h[k]=[]}
s.each_with_index{|a,t|h[a]<<t if a}
f=s.each_index.select{|i|!s[i]}
f.shift
for t in 1..n/3 do
  r=h[t]
  n=r.size
  if n>3
    puts'-1'
    exit
  else
    puts (r | f.pop(3-n)).join' '
  end
end

n,m=gets.split.map(&:to_i)
s=[nil]*(n+1)
t=1
m.times do
  a,b=gets.split.map(&:to_i)
  if s[a]==nil&&s[b]==nil
    s[a]=s[b]=t
    t+=1
  elsif s[a]==nil
    s[a]=s[b]
  else
    s[b]=s[a]
  end
end
h=Hash.new{|h,k|h[k]=[]}
s.each_with_index{|a,t|h[a]<<t if a}
f=s.each_index.select{|i|!s[i]}
f.shift
for t in 1..n/3 do
  r=h[t]
  n=r.size
  if n>3
    puts'-1'
    exit
  else
    puts (r | f.pop(3-n)).join' '
  end
end

n, m=gets.split.map(&:to_i)
c=n/3
s=[nil]*(n+1)
t=1
m.times do
  a, b=gets.split.map(&:to_i)
  if s[a].nil?&&s[b].nil?
    if t > c
      puts '-1'
      exit
    end
    s[a]=s[b]=t
    t+=1
  elsif s[a].nil?
    s[a]=s[b]
  elsif s[b].nil?
    s[b]=s[a]
  elsif s[a]!=s[b]
    puts '-1'
    exit
  end
end
h=Hash.new { |h, k| h[k]=[] }
s.each_with_index { |a, t| h[a]<<t if a }
f=s.each_index.select { |i| !s[i] }
f.shift
for t in 1..c do
  r=h[t]
  n=r.size
  if n>3
    puts '-1'
    exit
  else
    puts (r | f.pop(3-n)).join ' '
  end
end

n,m=gets.split.map(&:to_i)
s=[nil]*(n+1)
t=1
m.times do
  a,b=gets.split.map(&:to_i)
  if s[a]==nil&&s[b]==nil
    s[a]=s[b]=t
    t+=1
  elsif s[a]==nil
    s[a]=s[b]
  else
    s[b]=s[a]
  end
end
h=Hash.new([])
s.each_with_index{|a,t|h[a]<<t if a}
f=s.each_index.select{|i|!s[i]}
f.shift
for t in 1..n/3 do
  r=h[t]
  n=r.size
  if n>3
    puts'-1'
    exit
  else
    puts (r | f.pop(3-n)).join' '
  end
end

n, m=gets.split.map(&:to_i)
s=[nil]*(n+1)
t=1
m.times do
  a, b=gets.split.map(&:to_i)
  if s[a].nil?&&s[b].nil?
    if t > n/3
      puts '-1'
      exit
    end
    s[a]=s[b]=t
    t+=1
  elsif s[a].nil?
    s[a]=s[b]
  elsif s[b].nil?
    s[b]=s[a]
  elsif s[a]!=s[b]
    puts '-1'
    exit
  end
end
h=Hash.new { |h, k| h[k]=[] }
s.each_with_index { |a, t| h[a]<<t if a }
f=s.each_index.select { |i| !s[i] }
f.shift
for t in 1..n/3 do
  r=h[t]
  n=r.size
  if n>3
    puts '-1'
    exit
  else
    puts (r | f.pop(3-n)).join ' '
  end
end

n,m=gets.split.map(&:to_i)
s=[nil]*(n+1)
t=1
m.times do
  a,b=gets.split.map(&:to_i)
  if s[a].nil?&&s[b].nil?
    s[a]=s[b]=t
    t+=1
  elsif s[a].nil?
    s[a]=s[b]
  elsif s[b].nil?
    s[b]=s[a]
  else
    puts'-1'
    exit
  end
end
h=Hash.new{|h,k|h[k]=[]}
s.each_with_index{|a,t|h[a]<<t if a}
f=s.each_index.select{|i|!s[i]}
f.shift
for t in 1..n/3 do
  r=h[t]
  n=r.size
  if n>3
    puts'-1'
    exit
  else
    puts (r | f.pop(3-n)).join' '
  end
end


Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.

The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.

The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.

NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.

#!/usr/bin/ruby
require 'prime'
n=gets.to_i
p n<3?1:2
puts (2..n+1).map{|e|e.prime? ? 1 : 2}*' '

def is_prime(n=2)
	if n < 2
	       	return 0
	elsif n==2
	       	return 1
	elsif n%2==0
	       	return 0
	else
		j=3
		while j*j<=n
			if n % j == 0
				return 0
			end
			j+=2;
		end
		return 1
	end
end
n=gets.chomp.to_i
#puts n
color=Array.new(n+2,1)
#puts color.join(' ')
number=1
i=2
max=1
while i<=n+1
	if is_prime(i)
		j=2
		while i*j <= n+1
			color[i*j]=2
			max=color[i*j] if color[i*j] > max
			j+=1
		end
	end
	i+=1
end
#puts color.join(' ')
puts max
i=2
while i<=n+1
	print " #{color[i]}"
	i+=1
end
puts

n = gets.to_i + 1
colors = Array.new(n + 1)
2.upto(n) do |i|
  next if colors[i]
  colors[i] = 1
  (2 * i).step(n, i){|j| colors[j] = 2}
end
colors.shift(2)
p colors.max
puts colors.join(' ')

n = gets.to_i

a = Array.new
max = 1
(2..n+1).each do |i|
  (1..n+1).each do |j|
    break if i * j > n+1
    next if a[j].to_i > 1
    next if a[i * j] == 2
    a[i * j] = a[j].to_i == 1 ? 2 : 1
    max = [a[i * j], max].max
  end
end

puts max
puts a[2, a.length].join(' ')

#!/usr/bin/ruby
require 'prime'
n=gets.to_i
p n<2?1:2
puts (1..n).map{|e|e.prime? ? 1 : 2}*' '

n=gets.chomp.to_i
#puts n
color=Array.new(n+2,1)
#puts color.join(' ')
number=1
i=2
max=1
while i<=n+1
	j=2
	while i*j <= n+1
		color[i*j]+=1
		max=color[i*j] if color[i*j] > max
		j+=1
	end
	i+=1
end
#puts color.join(' ')
puts max
i=2
while i<=n+1
	print " #{color[i]}"
	i+=1
end
puts

n=gets.chomp.to_i
#puts n
color=Array.new(n+2,0)
#puts color.join(' ')
number=1
i=2
max=0
while i<=n+1
	if color[i]==0
		color[i]=number
		j=2
		while i*j <= n+1
			if color[i*j]==0
				color[i*j]=number+1
				max=number+1 if number + 1 > max
			else
				color[i*j]=number+2
				max=number+2 if number + 1 > max
				number+=1;
			end
			j+=1
		end
	end
	i+=1
end
#puts color.join(' ')
puts max
i=2
while i<=n+1
	print " #{color[i]}"
	i+=1
end
puts

n = gets.to_i + 1
colors = Array.new(n)
2.upto(n) do |i|
  i.step(n, i).with_index{|j, c| colors[j] ||= c + 1}
end
colors.compact!
p colors.uniq.size
puts colors.join(' ')

n = gets.to_i + 1
colors = Array.new(n + 1, 1)
2.upto(n) do |i|
  c = colors[i] + 1
  (2 * i).step(n, i) do |j|
    colors[j] = [colors[j], c].max
  end
end
colors.shift(2)
p colors.max
puts colors.join(' ')

n = gets.to_i

a = Array.new
max = 1
(2..n+1).each do |i|
  (1..n+1).each do |j|
    break if i * j > n+1
    next if a[i * j].to_i > a[j].to_i
    a[i * j] = [a[j].to_i, a[i * j].to_i].max + 1
    max = [a[i * j], max].max
  end
end

puts max
puts a[2, a.length].join(' ')


Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$.    The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.

In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.

N,K = gets.split.map &:to_i
es = Hash[(1..N).map{ |n| [n,{}] }]
(1..N-1).each{ |i|
  a,b = gets.split.map &:to_i
  es[a][b] = es[b][a] = i-1
}
R = (1..N).map{ |n| es[n].size }.sort[-K-1]
colors = Array.new(N-1,nil)

queue = [[nil,1]]

while cn = queue.pop do
  c,n = cn
  c = 0 if !c
  es[n].each{  |m,i|
    next if colors[i]
    c = (c + 1) % R
    colors[i] = c
    queue << [c,m]
  }
end

p R
puts colors.map{ |c| c + 1 } * " "


Mihai has an $$$8 \times 8$$$ chessboard whose rows are numbered from $$$1$$$ to $$$8$$$ from top to bottom and whose columns are numbered from $$$1$$$ to $$$8$$$ from left to right.Mihai has placed exactly one bishop on the chessboard. The bishop is not placed on the edges of the board. (In other words, the row and column of the bishop are between $$$2$$$ and $$$7$$$, inclusive.)The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked.     An example of a bishop on a chessboard. The squares it attacks are marked in red. Mihai has marked all squares the bishop attacks, but forgot where the bishop was! Help Mihai find the position of the bishop.

The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 36$$$) — the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either '#' or '.', denoting a square under attack and a square not under attack, respectively.

For each test case, output two integers $$$r$$$ and $$$c$$$ ($$$2 \leq r, c \leq 7$$$) — the row and column of the bishop.  The input is generated in such a way that there is always exactly one possible location of the bishop that is not on the edge of the board.

NoteThe first test case is pictured in the statement. Since the bishop lies in the intersection row $$$4$$$ and column $$$3$$$, the correct output is 4 3.

gets.to_i.times do
  gets
  xxs = 8.times.map { gets.chomp.chars }
  r, c = (1..6).flat_map do |i|
    (1..6).filter_map do |j|
      if xxs[i - 1][j - 1] == "#" && xxs[i - 1][j + 1] == "#" && xxs[i + 1][j - 1] == "#" && xxs[i + 1][j + 1] == "#"
        [i + 1, j + 1]
      end
    end
  end.first
  puts "#{r} #{c}"
end

n = gets.to_i

n.times do
  gets

  r = -1

  m = Array.new(8)

  8.times do |i|
    line = gets

    m[i] = line.chars
  end

  8.times do |i|
    8.times do |j|
      next unless m[i][j] == "#"
      next unless i - 1 > -1 && j - 1 > -1 && m[i - 1][j - 1] == "#"
      next unless i + 1 < 8 && j + 1 < 8 && m[i + 1][j + 1] == "#"
      next unless i - 1 > -1 && j + 1 < 8 && m[i - 1][j + 1] == "#"
      next unless i + 1 > -1 && j - 1 > -1 && m[i + 1][j - 1] == "#"

      puts [i, j].map(&:succ).map(&:to_s).join(" ")
    end
  end
end

$cnt = []

def solve
    v = Array.new(8){Array.new(8)}
    t = gets.split
    i = 0
    while i < 8
        s = gets.split('')
        j = 0
        s.each do |x|
            v[i][j] = x
            j = j + 1
        end
        i = i + 1
    end
    i = 1
    while i < 7
        j = 1
        while j < 7
            if v[i - 1][j - 1] == '#' and v[i - 1][j + 1] == '#' and v[i + 1][j - 1] == '#' and v[i + 1][j + 1] == '#'
                ans = []
                ans.append(i + 1)
                ans.append(j + 1)
                puts ans * " "
            end
            j = j + 1
        end
        i = i + 1
    end
end

maxn = 10005
maxn.times do
    $cnt.append(0)
end
gets.to_i.times do
    solve
end

gets.to_i.times do
  gets
  s = Array.new(8){gets.chomp.chars}
  gx, gy = 0, 0
  dx = [-1, -1, 1, 1]
  dy = [-1, 1, -1, 1]
  8.times do |i|
    8.times do |j|
      cnt = 0
      4.times do |k|
        x = j+dx[k]
        y = i+dy[k]
        if 0 <= x && x < 8 && 0 <= y && y < 8
          cnt += 1 if s[y][x] == '#'
        end
      end
      if cnt == 4
        gx = j+1
        gy = i+1
      end
    end
  end
  puts "#{gy} #{gx}"
end

main = -> {
  t = int
  t.times do
    string
    grid = rep(8) { string }
    (2 .. 7).any? do |i|
        (2 .. 7).any? do |j|
            if grid[i - 2][j - 2] == ?# && grid[i - 2][j] == ?# && grid[i][j - 2] == ?# && grid[i][j] == ?#
                puts "#{i} #{j}"
                true
            else
                false
            end
        end
    end
  end
}

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

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]

gets.to_i.times do
  gets
  xxs = 8.times.map { gets.chomp.chars }
  r, c = (0..7).flat_map do |i|
    (0..7).filter_map do |j|
      [i + 1, j + 1] if xxs[i][j] == "#" && xxs[i].count("#") == 1 && xxs.map { |xs| xs[j] }.count("#") == 1
    end
  end.first
  puts "#{r} #{c}"
end


An integer array $$$a_1, a_2, \ldots, a_n$$$ is being transformed into an array of lowercase English letters using the following prodecure:While there is at least one number in the array:   Choose any number $$$x$$$ from the array $$$a$$$, and any letter of the English alphabet $$$y$$$.  Replace all occurrences of number $$$x$$$ with the letter $$$y$$$. For example, if we initially had an array $$$a = [2, 3, 2, 4, 1]$$$, then we could transform it the following way:  Choose the number $$$2$$$ and the letter c. After that $$$a = [c, 3, c, 4, 1]$$$.  Choose the number $$$3$$$ and the letter a. After that $$$a = [c, a, c, 4, 1]$$$.  Choose the number $$$4$$$ and the letter t. After that $$$a = [c, a, c, t, 1]$$$.  Choose the number $$$1$$$ and the letter a. After that $$$a = [c, a, c, t, a]$$$. After the transformation all letters are united into a string, in our example we get the string "cacta".Having the array $$$a$$$ and the string $$$s$$$ determine if the string $$$s$$$ could be got from the array $$$a$$$ after the described transformation?

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^3$$$) — the number of test cases. Then the description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the array $$$a$$$ and the string $$$s$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 50$$$) — the elements of the array $$$a$$$. The third line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of lowercase English letters.

For each test case, output "YES", if we can get the string $$$s$$$ from the array $$$a$$$, and "NO" otherwise. You can output each letter in any case.

NoteThe first test case corresponds to the sample described in the statement.In the second test case we can choose the number $$$50$$$ and the letter a.In the third test case we can choose the number $$$11$$$ and the letter a, after that $$$a = [a, 22]$$$. Then we choose the number $$$22$$$ and the letter b and get $$$a = [a, b]$$$.In the fifth test case we can change all numbers one by one to the letter a.

# ○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．
def int(b = 0); gets.to_i + b end
def ints(b = 0); gets.split.map{ |x| x.to_i + b } end
def str; gets.chomp end
OO = (1<<62)-(1<<31)
# ○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．

def solve
  n = int
  a = ints
  s = str

  b = [-1] * n
  t = "?" * n
  n.times do |i|
    unless a[i] == nil
      # a[i] -> s[i]
      n.times do |j|
        if a[j] == a[i]
          return false if t[j] != '?' && t[j] != s[i]
          t[j] = s[i]
        end
      end
    end
  end

  s == t
end

t = int
t.times do
  ans = solve
  puts ans ? "YES" : "NO"
end


Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types:  Application x generates a notification (this new notification is unread).  Thor reads all notifications generated so far by application x (he may re-read some notifications).  Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.

The first line of input contains two integers n and q (1 ≤ n, q ≤ 300 000) — the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typei — type of the i-th event. If typei = 1 or typei = 2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1 ≤ typei ≤ 3, 1 ≤ xi ≤ n, 1 ≤ ti ≤ q).

Print the number of unread notifications after each event.

NoteIn the first sample:  Application 3 generates a notification (there is 1 unread notification).  Application 1 generates a notification (there are 2 unread notifications).  Application 2 generates a notification (there are 3 unread notifications).  Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test:  Application 2 generates a notification (there is 1 unread notification).  Application 4 generates a notification (there are 2 unread notifications).  Application 2 generates a notification (there are 3 unread notifications).  Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left.  Application 3 generates a notification (there is 1 unread notification).  Application 3 generates a notification (there are 2 unread notifications).

input = gets.chomp.split
n = Integer(input[0])
q = Integer(input[1])
event = []
for i in 0...q
    event[i] = []
    input1 = gets.chomp.split
    event[i][0] = Integer(input1[0])
    event[i][1] = Integer(input1[1])
end

unread = 0
notification = []
result = []
record = []
for i in 0...n
    record[i] = []
end
x = 0
for i in 0...q
    if event[i][0] == 1
        notification.push([event[i][1], 0])
        unread += 1
        record[event[i][1] - 1].push(notification.length - 1)
    elsif event[i][0] == 2
        for j in record[event[i][1] - 1]
            if j >= x && notification[j][1] == 0
                notification[j][1] = 1
                unread -= 1
            end
        end
        record[event[i][1] - 1] = []
    else
        if event[i][1] > x
            for j in x...event[i][1]
                if notification[j][1] == 0
                    notification[j][1] = 1
                    unread -= 1
                end
            end
            x = event[i][1]
        end
    end
    result.push(unread)
end

puts result

#$stdin=File.open "input.txt","r"
#$stdout=File.open "output.txt","w"

notifications=Array.new
d=0
a=0

n,q=gets.split.map{|x|x.to_i}
unread=Array.new(n+1,0)
read=Array.new(n+1,0)

q.times do

	t,x=gets.split.map{|y|y.to_i}

	if t==1 then notifications.push x; a+=1; unread[x]+=1
	elsif t==2 then
		a-=unread[x];read[x]+=unread[x];unread[x]=0
	elsif t==3
		notifications[0...x-d].each do |i|
			if read[i]>0 then read[i]-=1
			elsif unread[i]>0 and a>0 then unread[i]-=1;a-=1
			end
			notifications.shift;d+=1
		end if x-d>0
	end

	puts a
end

@n, @q = STDIN.gets.split(' ').collect{|x| x.to_i}
@record = Hash.new{|hash,key| hash[key] = Array.new}
@g, @decnt, @maxt, @count = Array.new, 0, 0, 0
@q.times do
	opt, x = STDIN.gets.split(' ').collect{|x| x.to_i}
	case opt
		when 1 then
			@g.push true
			@record[x].push(@count)
			@count += 1
		when 2 then
			@record[x].each do |v|
				if @g[v] then
					@g[v] = false
					@decnt += 1
				end
			end
			@record[x].clear
		when 3 then
			for i in @maxt...[x, @count].min do
				if @g[i] then
					@g[i] = false
					@decnt += 1
				end
			end
			@maxt = [[x, @count].min, @maxt].max
	end
	puts @count-@decnt
end

input = gets.chomp.split
n = Integer(input[0])
q = Integer(input[1])
event = []
for i in 0...q
    event[i] = []
    input1 = gets.chomp.split
    event[i][0] = Integer(input1[0])
    event[i][1] = Integer(input1[1])
end

=begin
def unread_count(a)
    unread_count = 0
    for i in 0...a.length
        if a[i][1] == 0
            unread_count += 1
        end
    end
    return unread_count
end
=end

unread = 0
notification = []
result = []
record = []
for i in 0...n
    record[i] = []
end
x = 0
for i in 0...q
    if event[i][0] == 1
        notification.push([event[i][1], 0])
        unread += 1
        record[event[i][1] - 1].push(notification.length - 1)
    elsif event[i][0] == 2
        for j in record[event[i][1] - 1]
            if j > x && notification[j][1] == 0
                notification[j][1] = 1
                unread -= 1
            end
        end
    else
        if event[i][1] > x
            for j in x...event[i][1]
                if notification[j][1] == 0
                    notification[j][1] = 1
                    unread -= 1
                end
            end
            x = event[i][1]
        end
    end
    result.push(unread)
end

puts result

#$stdin=File.open "input.txt","r"
n,q=gets.split.map{|x|x.to_i}
notifications=Array.new
count=Array.new
c=0
q.times do
	a,b=gets.split.map{|x|x.to_i}

	if a==1
		notifications[b]=0 if notifications[b]==nil
		notifications[b]+=1
		count[c]=b;
		c+=1
	elsif a==2
		notifications[b]=0
	else
		count[0..b].each {|x| notifications[x]-=1 if notifications[x]>0}
	end
	sum=0
	notifications.each {|x| sum+=x if x!=nil}
	puts sum
end

#$stdin=File.open "input.txt","r"
n,q=gets.split.map{|x|x.to_i}
notifications=Array.new
count=Array.new
c=0
q.times do
	a,b=gets.split.map{|x|x.to_i}

	if a==1
		notifications[b]=0 if notifications[b]==nil
		notifications[b]+=1
		count[c]=b;
		c+=1
	elsif a==2
		notifications[b]=0
	else
		count[0...b].each {|x| notifications[x]-=1 if notifications[x]>0}
	end
	sum=0
	notifications.each {|x| sum+=x if x!=nil}
	puts sum
end

#$stdin=File.open "input.txt","r"

notifications=Array.new
a=0

n,q=gets.split.map{|x|x.to_i}
unread=Array.new(n+1,0)
read=Array.new(n+1,0)

q.times do

	t,x=gets.split.map{|y|y.to_i}

	if t==1 then notifications.push x; a+=1; unread[x]+=1
	elsif t==2 then
		a-=unread[x];read[x]+=unread[x];unread[x]=0
	elsif t==3
		notifications[0...x].each do |i|
			if read[i]!=0 then read[i]-=1
			else unread[i]-=1;a-=1
			end
#print notifications, "\n"
#print read,"\n"
#print unread, "\n"
		end
	end
#	print read,"\n"
#	print unread,"\n"
	puts a
end

#$stdin=File.open "input.txt","r"

notifications=Array.new
read=Array.new

n,q=gets.split.map{|x|x.to_i}

q.times do

	t,x=gets.split.map{|y|y.to_i}

	notifications.push x if t==1
	if t==2
		notifications.each do |y|
			ind=notifications.index y
			read[ind]=y if y==x
		end
	elsif t==3
		notifications[0...x].each do |y|
			ind = notifications.index y
			read[ind]=y
		end
	end
	puts (notifications-read).length
end

#$stdin=File.open "input.txt","r"

notifications=Array.new
a=0

n,q=gets.split.map{|x|x.to_i}
unread=Array.new(n+1,0)
read=Array.new(n+1,0)

q.times do

	t,x=gets.split.map{|y|y.to_i}

	if t==1 then notifications.push x; a+=1; unread[x]+=1
	elsif t==2 then
		a-=unread[x];read[x]+=unread[x];unread[x]=0
	elsif t==3
		notifications[0...x].each do |i|
			if read[i]!=0 then read[i]-=1
			elsif unread[i]>0 and a>0 then unread[i]-=1;a-=1
			end
#print notifications, "\n"
#print read,"\n"
#print unread, "\n"
		end
	end
#	print read,"\n"
#	print unread,"\n"
	puts a
end

#$stdin=File.open "input.txt","r"
#$stdout=File.open "output.txt","w"

notifications=Array.new
d=0
a=0

n,q=gets.split.map{|x|x.to_i}
unread=Array.new(n+1,0)
read=Array.new(n+1,0)

q.times do

	t,x=gets.split.map{|y|y.to_i}

	if t==1 then notifications.push x; a+=1; unread[x]+=1
	elsif t==2 then
		a-=unread[x];read[x]+=unread[x];unread[x]=0
	elsif t==3
#	cur_read=read.clone
		notifications[0...x-d].each do |i|
#			if cur_read[i]>0 then cur_read[i]-=1
			if read[i]>0 then read[i]-=1;notifications.shift;d+=1
			elsif unread[i]>0 and a>0 then unread[i]-=1;a-=1
			end
		end
	end

	puts a
end

#$stdin=File.open "input.txt","r"
#$stdout=File.open "output.txt","w"

notifications=Array.new
d=0
a=0

n,q=gets.split.map{|x|x.to_i}
unread=Array.new(n+1,0)
read=Array.new(n+1,0)

q.times do

	t,x=gets.split.map{|y|y.to_i}

	if t==1 then notifications.push x; a+=1; unread[x]+=1
	elsif t==2 then
		a-=unread[x];read[x]+=unread[x];unread[x]=0
	elsif t==3
		notifications[0...x-d].each do |i|
			if read[i]>0 then read[i]-=1;d+=1
			elsif unread[i]>0 and a>0 then unread[i]-=1;a-=1
			end
			notifications.shift
		end if x-d>0
	end

	puts a
end

#$stdin=File.open "input.txt","r"
n,q=gets.split.map{|x|x.to_i}
notifications=Array.new
count=Array.new
c=0
q.times do
	a,b=gets.split.map{|x|x.to_i}

	if a==1
		notifications[b]=0 if notifications[b]==nil
		notifications[b]+=1
#print -1,notifications,-1,"\n"
		count[c]=b;
		c+=1
#		print -3,count,-3,"\n"
	elsif a==2
		notifications[b]=0
	else
		count.each do |x|
			notifications[x]-=1
#			print -2,notifications,-2,"\n"
		end
	end
	sum=0
	notifications.each {|x| sum+=x if x!=nil}
	puts sum
end

#$stdin=File.open "input.txt","r"

notifications=Array.new
a=0

n,q=gets.split.map{|x|x.to_i}
unread=Array.new(n+1,0)
read=Array.new(n+1,0)

q.times do

	t,x=gets.split.map{|y|y.to_i}

	if t==1 then notifications.push x; a+=1; unread[x]+=1
	elsif t==2 then
		a-=unread[x];read[x]+=unread[x];unread[x]=0
	elsif t==3
		notifications[0...x].each do |i|
			if read[i]!=0 then read[i]-=1
			elsif unread[i]>0 and a>0 then unread[i]-=1;a-=1
			end
		end
	end

	puts a
end

#$stdin=File.open "input.txt","r"
#$stdout=File.open "output.txt","w"

notifications=Array.new
a=0

n,q=gets.split.map{|x|x.to_i}
unread=Array.new(n+1,0)
read=Array.new(n+1,0)

q.times do

	t,x=gets.split.map{|y|y.to_i}

	if t==1 then notifications.push x; a+=1; unread[x]+=1
	elsif t==2 then
		a-=unread[x];read[x]+=unread[x];unread[x]=0
	elsif t==3
		cread=read.clone
		notifications[0...x].each do |i|
			if cread[i]!=0 then cread[i]-=1
			elsif unread[i]>0 and a>0 then unread[i]-=1;a-=1
			end
		end
	end

#	print read,"\n"
#	print unread,"\n"
	puts a
end

#$stdin=File.open "input.txt","r"

notifications=Array.new
a=0

n,q=gets.split.map{|x|x.to_i}
unread=Array.new(n+1,0)
read=Array.new(n+1,0)

q.times do

	t,x=gets.split.map{|y|y.to_i}

	if t==1 then notifications.push x; a+=1; unread[x]+=1
	elsif t==2 then
		a-=unread[x];read[x]+=unread[x];unread[x]=0
	elsif t==3
		notifications[0...x].each do |i|
			if read[i] then read[i]-=1
			else unread[x]-=1;a-=1
			end
		end
	end

	puts a
end

#$stdin=File.open "input.txt","r"
n,q=gets.split.map{|x|x.to_i}
notifications=Array.new
count=Array.new
c=0
q.times do
	a,b=gets.split.map{|x|x.to_i}

	if a==1
		notifications[b]=0 if notifications[b]==nil
		notifications[b]+=1
		count[c]=b;
		c+=1
	elsif a==2
		notifications[b]=0
	else
		count.each {|x| notifications[x]-=1 if notifications[x]>0}
	end
	sum=0
	notifications.each {|x| sum+=x if x!=nil}
	puts sum
end


Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to n.Let us remind you the definition of the greatest common divisor: GCD(a1, ..., ak) = d, where d represents such a maximal positive number that each ai (1 ≤ i ≤ k) is evenly divisible by d. At that, we assume that all ai's are greater than zero.Knowing that Petya is keen on programming, his friends has agreed beforehand that the 1-st friend gives a1 sweets, the 2-nd one gives a2 sweets, ..., the n-th one gives an sweets. At the same time, for any i and j (1 ≤ i, j ≤ n) they want the GCD(ai, aj) not to be equal to 1. However, they also want the following condition to be satisfied: GCD(a1, a2, ..., an) = 1. One more: all the ai should be distinct.Help the friends to choose the suitable numbers a1, ..., an.

The first line contains an integer n (2 ≤ n ≤ 50).

If there is no answer, print "-1" without quotes. Otherwise print a set of n distinct positive numbers a1, a2, ..., an. Each line must contain one number. Each number must consist of not more than 100 digits, and must not contain any leading zeros. If there are several solutions to that problem, print any of them. Do not forget, please, that all of the following conditions must be true:  For every i and j (1 ≤ i, j ≤ n): GCD(ai, aj) ≠ 1 GCD(a1, a2, ..., an) = 1 For every i and j (1 ≤ i, j ≤ n, i ≠ j): ai ≠ aj  Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).

require 'mathn'

n = gets.to_i

if n == 2 then puts "-1"
else

primes = []
p = Prime.new
n.times do
  primes << p.next()
end

product = primes.inject do |p, x|
  p * x
end
a = primes.map do |x|
  product / x
end

puts a.join("\n")

end

require 'prime'

n = gets.to_i
if n == 2
	p -1
	exit
end

a = []
Prime.each do |prime|
	a << prime
	break if a.size == n
end
s = a.inject(&:*)
a = a.map{|_| s / _}
puts a * "\n"
__END__
n.times do |i|
	p a[i] if a[i].to_s.size > 100
	i.times do |j|
		p "#{a[i]} #{a[j]}" if a[i].gcd(a[j]) == 1
	end
end
p "555" if a.inject(&:gcd) > 1

#!/usr/bin/ruby

require 'prime'

n = gets.to_i
if n == 2
	p -1
	exit
end

arr = Prime.take(n)

n.times { |i|
	tmp = arr.dup
	tmp.delete_at(i)
	p tmp.inject(:*)
}

n = STDIN.gets.chomp.to_i
if n == 1
  puts 2
  exit 0
end
if n == 2
  puts -1
  exit 0
end
primes = []
# get primes
x = 2
while primes.size < n+1
  ok = true
  primes.each { |t|
    if (x % t == 0)
      ok = false
      break;
    end
  }
  if ok
    primes.push(x)
  end
  x = x + 1
end

ans = []
(n-1).times { |i|
  ans.push(primes[0])
}
ans.push(1)

(n-1).times { |i|
  ans[i] *= primes[i+1]
  ans[n-1] *= primes[i+1]
}

n.times { |i|
  puts ans[i]
}

require 'prime'
n = gets
n = n.to_i
i = 0
num = 2
primes = Array.new()
while i<n
    if num.prime? then
        primes.push num
        i+=1
    end
    num+=1
end
if n==2 then
    puts "-1"
else
for i in 0..n-1
    num = 1
    for j in 0..n-1
        if i!=j then
            num*=primes[j]
        end
    end
    puts num
end
end

def prime?(num)
  2.upto(num-1){|i|
    if num % i == 0
      return false
    end
  }
  return true
end
p = Array.new
i = 2
while p.length < 50
  if prime?(i)
    p << i
  end
  i += 1
end
n = gets.to_i
if n!=2
  for i in 0...n
    ans = 1
    for j in 0...n-1
      ans *= p[(i+j)%n]
    end
    puts ans
  end
else
  puts -1
end

def prime x

  m = Math.sqrt x
  for i in 2..m
    if x % i == 0
      return false
    end
  end

  return true

end

n = gets.to_i

if n == 2
  puts -1
else

  primes = []

  cur = 2
  while primes.size < n
    if prime cur
      primes.push cur
    end
    cur += 1
  end

  product = 1
  for prime in primes
    product *= prime
  end

  for i in 0...n
    puts product / primes[i]
  end
end

N = gets.to_i

if N == 2
  puts -1
else
  puts 21
  puts 14
  1.upto(N - 2) { |i|
    puts 3 * (2 ** i)
  }
end

n = STDIN.gets.chomp.to_i
if n == 2
  puts -1
  exit 0
end

values = [99, 55, 11115]
product = values.reduce(&:*)
multiplier = 1
4.upto(n) do
  values.push(product * multiplier)
  multiplier += 1
end
values.each do |value|
  puts value
end

def gcd(a, b)
    return a if b.eql? 0
    gcd(b, a % b)
end

n = gets.to_i

if (n == 2)
  puts -1
  exit
end

mas = [20,18,15]
for i in 3..n-1
  mas[i] = mas[i-1]*3;
end

puts mas

def is_prime(n)
    i = 2
    while i * i <= n
        return false if n % i == 0
        i += 1
    end
    true
end

n = gets.to_i

if n == 2
    puts -1
else
    i = 2
    primes = []
    while primes.size < n
        primes << i if is_prime(i)
        i += 1
    end

    product = primes.inject(1) { |p, i| p * i }
    puts primes.map { |p| product / p }
end

require 'mathn'

n = gets.to_i

primes = []
p = Prime.new
n.times do
  primes << p.next()
end

product = primes.inject do |p, x|
  p * x
end
a = primes.map do |x|
  product / x
end

puts a.join(" ")

require 'mathn'

n = gets.to_i

primes = []
p = Prime.new
n.times do
  primes << p.next()
end

product = primes.inject do |p, x|
  p * x
end
a = primes.map do |x|
  product / x
end

puts a.join("\n")

#!/usr/bin/ruby

require 'prime'

n = gets.to_i
if n == 2
	p -1
	exit
end

arr = Prime.take(50)

n.times { |i|
	tmp = arr.dup
	tmp.delete_at(i)
	p tmp.inject(:*)
}

#!/usr/bin/ruby

require 'mathn'

n = gets.to_i
if n == 2
	p -1
	exit
end

arr = []
Prime.each(1000) { |pr|
	arr << pr
	break if arr.size == n
}

n.times { |i|
	tmp = arr.dup
	tmp.delete_at(i)
	p tmp.inject(:*)
	p tmp.inject(:*).to_s.size
}

#!/usr/bin/ruby

require 'mathn'

n = gets.to_i
if n == 2
	p -1
	exit
end

arr = []
Prime.each(100) { |pr|
	arr << pr
	break if arr.size == n
}

n.times { |i|
	tmp = arr.dup
	tmp.delete_at(i)
	p tmp.inject(:*)
}

n = STDIN.gets.chomp.to_i
primes = []
# get primes
x = 2
while primes.size < n+1
  ok = true
  primes.each { |t|
    if (x % t == 0)
      ok = false
      break;
    end
  }
  if ok
    primes.push(x)
  end
  x = x + 1
end

ans = []
(n-1).times { |i|
  ans.push(primes[0])
}
ans.push(1)

(n-1).times { |i|
  ans[i] *= primes[i+1]
  ans[n-1] *= primes[i+1]
}

n.times { |i|
  puts ans[i]
}

def prime x

  m = Math.sqrt x
  for i in 2..m
    if x % i == 0
      return false
    end
  end

  return true

end

n = gets.to_i

primes = []

cur = 2
while primes.size < n
  if prime cur
    primes.push cur
  end
  cur += 1
end

product = 1
for prime in primes
  product *= prime
end

for i in 0...n
  puts product / primes[i]
end

n = STDIN.gets.chomp.to_i
if n == 2
  puts -1
  exit 0
end

factorial = {}
f = 1
1.upto(n + 5) do |i|
  f *= i
  factorial[i] = f
end

values = []
1.upto(n - 2) do |i|
  values.push(factorial[i+1])
end

values.each { |x| puts x }
puts values.last * 97
puts values.last * 97 * 2

def is_prime(n)
    i = 2
    while i * i <= n
        return false if n % i == 0
        i += 1
    end
    true
end

n = gets.to_i

i = 2
primes = []
while primes.size < n
    primes << i if is_prime(i)
    i += 1
end

product = primes.inject(1) { |p, i| p * i }
puts primes.map { |p| product / p }


Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 106. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.

#!/usr/bin/ruby
h={}
cap=cur=0
gets.to_i.times{
	x,y=gets.split
	y=y.to_i
	if x=='+' && !h[y]
		cur+=1
		h[y]=1
	elsif x=='-' && h[y]
		cur-=1
		h[y]=nil
	elsif x=='-' && !h[y]
		cap+=1
	end
	cap=[cap,cur].max
}
p cap

#!/usr/bin/ruby

def solution(n, records)
  set = {}
  mx = 0
  records.each do |rec|
    mx+=1 if rec[0] == '-' && ! set[rec[1]]
    set.delete rec[1] if rec[0] == '-'
    set[rec[1]] = rec  if rec[0] == '+'
    mx = [mx, set.size].max
  end
  puts mx
end

n = gets.to_i
records = []
n.times { records.push(gets.split(' ')) }
solution n, records

# http://codeforces.com/contest/567/problem/B

require 'set'
n = gets.chomp.to_i
counter = Hash.new { |h, k| h[k] = Set.new }
memo = Hash.new(0)
n.times do |idx|
  op, num = gets.chomp.split
  counter[idx] = counter[idx - 1].clone

  case op
  when '+'
    memo[num] += 1
    counter[idx] << num
  else
    if memo[num] == 1
      memo[num] -= 1
    else
      (- 1...idx).each { |idx2| counter[idx2] << num  }
    end
    counter[idx] -= [num]
  end
end

puts counter.values.map(&:length).max

# require 'pry'
def read_ints; gets.chomp.split.map(&:to_i) end
n = read_ints[0]
current = 0
max = 0
current_stack = []
n.times do
	line = gets.chomp.split
	if(line[0]=='+')
		#new man come
		current+=1
		current_stack<<line[1].to_i
		max = current if current>max
	else
		#man come out
		man_id = line[1].to_i
		if(current_stack.include? man_id)
			current_stack.delete(man_id)
			current-=1
		else #was there from begging
			max+=1
		end
	end
end
puts max

n = gets.chomp.to_i
rs = []
n.times{
  rs << gets.chomp.split(' ')
}

cnt = 0
hs = Hash.new
rs.each do |r|
  if r[0] == '-' && hs[r[1]] != '+'
    cnt += 1
  end
  hs[r[1]] = r[0]
end

rtn = cnt
rs.each do |r|
  if r[0] == '-'
    cnt -= 1
  else
    cnt += 1
  end
  rtn = cnt if rtn < cnt
end

puts rtn

n = gets.to_i
ans = 0
q = []
n.times do
  a, b = gets.split
  b = b.to_i
  if a == '-'
    ans += 1 if q.delete(b).nil?
  else
    q << b
  end
  ans = [ans, q.size].max
end
puts ans

require 'set'

n=gets.chomp.to_i
sign=Array.new(1000001){0}
line=[]
room=Set.new
for i in 0...n
  line.push(gets.chomp)
  s=line[i].split(" ")
  num=s[1].to_i
  if s[0]=="-"
    if sign[num]==0
      room.add(num)
    end
  else
    sign[num]=1
  end
end
ans=room.size
for i in 0...n
  s=line[i].split(" ")
  if s[0]=="+"
    room.add(s[1].to_i)
  else
    room.delete(s[1].to_i)
  end
  if room.size>ans
    ans=room.size
  end
end
puts ans

list_length = gets.chomp.gsub(/ /,'').to_i
numbers = []

list_length.times do |i|
  numbers << gets.chomp.gsub(/ /,'').to_i
end

current_number_in_room = 0
max = 0
current_users_in_room = []

numbers.each do |number|
  number = number.to_i

  if number > 0
    current_number_in_room += 1
    current_users_in_room << number.abs

    max <= current_number_in_room ? (max = current_number_in_room) : max
  else
    if current_users_in_room.include?(number.abs)
      current_users_in_room.delete(number.abs)

      current_number_in_room -= 1
    else
      maybe_max = max + 1

      max <= maybe_max ? max = maybe_max : max
    end
  end
end

puts max

logNum = gets.chomp.to_i

data = []
room = 0
startRoom = 0
result = -1
peopleExit = false
inPeople = 0
initialPeople = []
logs = []

(0...logNum).each do |iter|
	log = gets.chomp.split(' ')
	logs << log

	if log[0] == "+"
		data << log[1]
	else
		if !data.include?(log[1])
			startRoom += 1
		end
	end
end

data = data.clear
room = startRoom
result = startRoom

#puts "middle room : #{room}"

logs.each do |log|

	if log[0] == "+"
		data << log[1]
		room += 1
	else
		if data.include?(log[1])
			data.delete(log[1])
		end

		room -= 1
	end

	result = room if result < room
end

puts result

#!/usr/bin/ruby

def solution(n, records)
  set = {}
  mx = 0
  records.reverse.each do |rec|
    set.delete rec[1] if rec[0] == '+'
    set[rec[1]] = rec  if rec[0] == '-'
    mx = [mx, set.size].max
  end
  puts mx
end

n = gets.to_i
records = []
n.times { records.push(gets.split(' ')) }
solution n, records

# solution 6, [%w(+ 12001),%w(- 12001),%w(- 1),%w(- 1200),%w(+ 1),%w(+ 7)]
# solution 4, 4, '.cc.', [1, 2, 1, 0], %w(. . a a)
# solution 4,3
# solution 3,2
# solution 3,1
# solution 3,3
# solution 2,1
# solution 2,2
#
# #
# # solution 4, [75, 150, 75, 50]
# # solution 3, [100, 150, 250]

# http://codeforces.com/contest/567/problem/B

require 'set'
n = gets.chomp.to_i
counter = Hash.new { |h, k| h[k] = Set.new }
memo = Hash.new(0)
n.times do |idx|
  op, num = gets.chomp.split
  counter[idx] = counter[idx - 1].clone

  case op
  when '+'
    memo[num] += 1
    counter[idx] << num
  else
    if memo[num] == 1
      memo[num] -= 1
      counter[idx] -= [num]
    else
      (0..idx).each { |idx2| counter[idx2] << num  }
    end
  end
end

puts counter.values.map(&:length).max

logNum = gets.chomp.to_i

data = []
room = 0
startRoom = 0
result = -1
peopleExit = false
inPeople = 0

(0...logNum).each do |iter|
	log = gets.chomp.split(' ')

	if log[0] == "+"
		data << log[1]
		room += 1

		inPeople += 1 if !peopleExit
	else
		peopleExit = true
		if data.include?(log[1])
			data.delete(log[1])
			room -= 1
		else
			startRoom += 1
		end
	end

	result = room if result < room
end

result = inPeople + startRoom if result < inPeople + startRoom

puts result


There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≤ i ≤ n) and replace element ai with ai & x, where & denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.

The first line contains integers n and x (2 ≤ n ≤ 100 000, 1 ≤ x ≤ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≤ ai ≤ 100 000), the elements of the array.

Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.

NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.

N, X = gets.split.map(&:to_i)
as = gets.split.map(&:to_i)
ah = {}
xh = {}
ans = 10
N.times do |i|
    ax = as[i] & X
    if ah[as[i]]
        ans = 0 if ans > 0
    elsif xh[as[i]] || ah[ax]
        ans = 1 if ans > 1
    elsif xh[ax]
        ans = 2 if ans > 2
    end
    ah[as[i]] = true
    xh[ax] = true
end
puts ans == 10 ? -1 : ans


There is the following puzzle popular among nuclear physicists.A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements.You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times.The aim is getting a new pregiven set of k atoms.The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 17). The second line contains space-separated symbols of elements of n atoms, which are available from the start. The third line contains space-separated symbols of elements of k atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized.

If it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line «YES», and on the next k lines print the way of synthesizing each of k atoms as equations. Each equation has the following form: "x1+x2+...+xt->yi", where xj is the symbol of the element of some atom from the original set, and yi is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples.

YES
Mn+C+K->Sn
Co+Zn+Sc->Pt
Li+Mg+P+F->Y

NoteThe reactions from the first example possess the following form (the atomic number is written below and to the left of the element):To find a periodic table of the chemical elements, you may use your favorite search engine.The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints.

class E
    ATOMS = "Hoge H  He  Li  Be      B   C   N   O   F   Ne Na  Mg      Al  Si  P   S   Cl  Ar K   Ca      Sc  Ti  V   Cr  Mn  Fe  Co  Ni  Cu  Zn  Ga  Ge  As  Se  Br  Kr Rb  Sr      Y   Zr  Nb  Mo  Tc  Ru  Rh  Pd  Ag  Cd  In  Sn  Sb  Te  I   Xe Cs  Ba      La  Ce  Pr  Nd  Pm  Sm  Eu  Gd  Tb  Dy  Ho  Er  Tm  Yb    Lu  Hf  Ta  W   Re  Os  Ir  Pt  Au  Hg  Tl  Pb  Bi  Po  At  Rn Fr  Ra Ac  Th  Pa  U   Np  Pu  Am  Cm  Bk  Cf  Es  Fm  Md  No".split

    def initialize
        @atom_num = {}
        ATOMS.each_with_index { |v, i| @atom_num[v] = i }
    end

    def dfs(sp, dp, sum, using)
        if dp == @dests.size
            puts "YES"
            arr = Array.new(@dests.size){Array.new}
            using.each_with_index do |v, idx|
                arr[v] << @srcs[idx]
            end
            arr.each_with_index do |v, idx|
                puts "#{v.map{|a| ATOMS[a]}.join('+')}->#{ATOMS[@dests[idx]]}"
            end
            exit
        end

        prev = -1
        sp.upto(@srcs.size-1) do |i|
            next if @srcs[i] == prev
            next if using[i] != -1

            tot = sum + @srcs[i]
            next if tot > @dests[dp]

            using[i] = dp
            if tot == @dests[dp]
                dfs(0, dp+1, 0, using)
            else
                dfs(i+1, dp, tot, using)
            end
            using[i] = -1

            prev = @srcs[i]
        end
    end

    def solve
        n,k = gets.split.map(&:to_i)
        @srcs = gets.split.map { |v| @atom_num[v] }.sort
        @dests = gets.split.map { |v| @atom_num[v] }

        dfs(0, 0, 0, [-1]*@srcs.size)
        puts "NO"
    end
end

e = E.new
e.solve


An array is sorted if it has no inversionsA Young BoyYou are given an array of $$$n$$$ positive integers $$$a_1,a_2,\ldots,a_n$$$. In one operation you do the following:   Choose any integer $$$x$$$.  For all $$$i$$$ such that $$$a_i = x$$$, do $$$a_i := 0$$$ (assign $$$0$$$ to $$$a_i$$$). Find the minimum number of operations required to sort the array in non-decreasing order.

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

For each test case print one integer — the minimum number of operations required to sort the array in non-decreasing order.

NoteIn the first test case, you can choose $$$x = 3$$$ for the operation, the resulting array is $$$[0, 0, 2]$$$.In the second test case, you can choose $$$x = 1$$$ for the first operation and $$$x = 3$$$ for the second operation, the resulting array is $$$[0, 0, 0, 0]$$$.

require "set"

gets.to_i.times do
  n = gets.to_i
  xs = gets.split.map(&:to_i)
  replaced = Set.new
  last = 0
  xs.each_cons(2).each.with_index do |(a, b), i|
    a = replaced.include?(a) ? 0 : a
    b = replaced.include?(b) ? 0 : b
    if a <= b
    else
      (last..i).each do |i|
        replaced << xs[i]
      end
      last = i
    end
  end
  p replaced.count
end

require 'set'
gets.to_i.times do
  n=gets.to_i
  # aを広義単調増加にする手数のmin
  a=gets.split.map(&:to_i)
  t=-1
  (n-1).times do |i|
    t=i if a[i]>a[i+1]
  end
  s=Set.new
  (t+1).times {|i| s << a[i]}
  lim=t
  (n-1).downto(t+1) do |i|
    if s.include? a[i] then
      lim=i
      break
    end
  end
  p lim==-1 ? 0 : a[0..lim].uniq.size
end


Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one Morty. They're gathering in m groups. Each person can be in many groups and a group can contain an arbitrary number of members.Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility).  Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world). Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all 2n possible scenarios, 2 possible scenarios for who a traitor in each universe) such that in that scenario the world will end.

The first line of input contains two integers n and m (1 ≤ n, m ≤ 104) — number of universes and number of groups respectively. The next m lines contain the information about the groups. i-th of them first contains an integer k (number of times someone joined i-th group, k > 0) followed by k integers vi, 1, vi, 2, ..., vi, k. If vi, j is negative, it means that Rick from universe number  - vi, j has joined this group and otherwise it means that Morty from universe number vi, j has joined it. Sum of k for all groups does not exceed 104.

In a single line print the answer to Summer's question. Print "YES" if she should cancel the event and "NO" otherwise.

NoteIn the first sample testcase, 1st group only contains the Rick from universe number 3, so in case he's a traitor, then all members of this group are traitors and so Summer should cancel the event.

STDIN.readline
while !STDIN.eof? && signups = STDIN.readline.strip.split(" ").map(&:to_i)
  valid = false
  group_signups = {}
  signups.each.with_index do |signup, index|
    if(index > 0)
      if(group_signups[-signup])
        valid = true
        break
      else
        group_signups[signup] = signup
      end
    end
  end

  if(!valid)
    puts "YES"
    exit
  end
end

puts "NO"

n, m = gets.split.map(&:to_i)
a = m.times.map{gets.split.map(&:to_i)[1..-1].uniq.map(&:abs)}
puts a.any?{|x| x.size == 1 || x.uniq.size == x.size} ? 'YES' : 'NO'


You want to perform the combo on your opponent in one popular fighting game. The combo is the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in $$$s$$$. I.e. if $$$s=$$$"abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend $$$m$$$ wrong tries to perform the combo and during the $$$i$$$-th try you will make a mistake right after $$$p_i$$$-th button ($$$1 \le p_i < n$$$) (i.e. you will press first $$$p_i$$$ buttons right and start performing the combo from the beginning). It is guaranteed that during the $$$m+1$$$-th try you press all buttons right and finally perform the combo.I.e. if $$$s=$$$"abca", $$$m=2$$$ and $$$p = [1, 3]$$$ then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 2 \cdot 10^5$$$) — the length of $$$s$$$ and the number of tries correspondingly. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of each test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i < n$$$) — the number of characters pressed right during the $$$i$$$-th try. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ both does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$). It is guaranteed that the answer for each letter does not exceed $$$2 \cdot 10^9$$$.

For each test case, print the answer — $$$26$$$ integers: the number of times you press the button 'a', the number of times you press the button 'b', $$$\dots$$$, the number of times you press the button 'z'.

3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4

NoteThe first test case is described in the problem statement. Wrong tries are "a", "abc" and the final try is "abca". The number of times you press 'a' is $$$4$$$, 'b' is $$$2$$$ and 'c' is $$$2$$$.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is $$$9$$$, 'd' is $$$4$$$, 'e' is $$$5$$$, 'f' is $$$3$$$, 'o' is $$$9$$$, 'r' is $$$3$$$ and 's' is $$$1$$$.

def read_array(to)
  gets.strip.split(' ').map(&to)
end

MAPPING = ('a'..'z').to_a.zip((0..26)).inject({}) { |m, h| m[h[0]] = h[1]; m }

gets.strip.to_i.times do
  _, _ = read_array(:to_i)
  s    = gets.strip
  p    = read_array(:to_i)
  sums = []
  s.split('').inject(Array.new(26, 0)) do |m, c|
    m[MAPPING[c]] += 1
    sums << m.dup
    m
  end
  res = Array.new(26, 0)
  (p + [s.size]).each_with_index do |t, i|
    res = sums[t-1].zip(res).map { |x| x[0] + x[1] }
  end
  puts res.join(' ')
end

n=gets.to_i
(1..n).each do |x|
  array = []
  a,b=gets.chomp.split(" ").map(&:to_i)
  str=gets.chomp.split("")
  array=gets.chomp.split(" ").map(&:to_i)
  array.push(a)
  temp = Array.new(a, 0)
  array.each do |arr|
    temp[arr-1] += 1
  end
  a -= 1
  while a > 0
    a -= 1
    temp[a] += temp[a+1]
  end
  result = Array.new(26, 0)
  k = 0
  temp.each do |arr|
    result[str[k].ord - 97] += arr
    k += 1
  end
  print("#{result.join(" ")}\n")
end


Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index bi from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index bi, then this person acted like that:  he pointed at the person with index (bi + 1) mod n either with an elbow or with a nod (x mod y is the remainder after dividing x by y);  if j ≥ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player bi on the current turn, then he had drunk a glass of juice;  the turn went to person number (bi + 1) mod n. The person who was pointed on the last turn did not make any actions.The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.You can assume that in any scenario, there is enough juice for everybody.

The first line contains a single integer n (4 ≤ n ≤ 2000) — the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns.

Print a single integer — the number of glasses of juice Vasya could have drunk if he had played optimally well.

NoteIn both samples Vasya has got two turns — 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like "abbbb". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different.

n=gets.to_i
s=gets.chomp
l=s.size
c=0
p
for i in (n..l-1).step(n) do
  c+=1 if s[i-1]==s[i-2] and s[i-1]==s[i-3]
end
p c

n = gets.to_i
s = gets.chomp
c=0;
for i in (n..s.length-1).step(n)
	if(s[i-1]==s[i-2] && s[i-3]==s[i-1])
		c+=1;
	end
end
p c

n = gets.to_i
ar = gets.chomp
c = 0;
for i in (n..ar.length-1).step(n)
	if(ar[i-1]==ar[i-2] && ar[i-1]==ar[i-3])
		c+=1
	end
end
p c;

n = gets.to_i
s = gets.chomp
i = n
c = 0
while i < s.size
  c += 1 if s[i - 1] == s[i - 2] && s[i - 2] == s[i - 3]
  i += n
end
puts c

n = gets.to_i
puts gets.chomp.slice(1,2000).chars.each_slice(n).select{|x|
  x.length == n && x[-4] == x[-3] && x[-3] == x[-2]
}.length

n = gets.to_i
seq = gets.chomp!
ret = 0
for i in 0...seq.size
  if i >= 4 && i % n == 0
    if seq[i-1] == seq[i-2] && seq[i-2] == seq[i-3]
      ret += 1
    end
  end
end
puts ret

n = STDIN.readline.to_i
s = STDIN.readline.strip
pos = n
count = 0
while pos < s.length
	count += 1 if s[pos-1] == s[pos-2] and s[pos-2] == s[pos-3]
	pos += n
end
puts count

def run
  n = $stdin.gets.to_i
  a = $stdin.gets.chomp.split(//)

  cnt = 0
  cur = 0
  while cur < a.length
    cnt += 1 if cur >= 3 and a[cur - 1] == a[cur - 2] and a[cur - 1] == a[cur - 3]
    cur += n
  end

  puts cnt
end

run if $0 == __FILE__

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

i = 0
c = 0
while i * n < str.length do
  i+=1
  next if i*n < 3 || i*n >= str.length
  if str[i*n - 1] == str[i*n - 2] &&
    str[i*n - 1] == str[i*n - 3]
    c += 1
  end
end
puts c

n = gets.to_i
s = gets.chomp
ans = 0
(n...s.size).step(n).each{|i| ans += 1 if s[i-3]==s[i-2] and s[i-2]==s[i-1]}
puts ans

n = gets.to_i
s = gets.chomp
r = 0
i = n
while i < s.length
  if (s[i-3,3] == 'aaa') or (s[i-3,3] == 'bbb')
    r += 1
  end
  i += n
end
puts "#{r}"

n = gets.to_i
s = gets.chomp
c=0;
for i in (n..s.length).step(n)
	if(s[i-1]==s[i-2] && s[i-3]==s[i-1])
		c+=1;
	end
end
p c

def run
  n = $stdin.gets.to_i
  a = $stdin.gets.split(//)

  cnt = 0
  cur = 0
  while cur < a.length
    cnt += 1 if cur >= 3 and a[cur - 1] == a[cur - 2] and a[cur - 1] == a[cur - 3]
    cur += n
  end

  puts cnt
end

run if $0 == __FILE__

n=gets.to_i
s=gets.chomp
l=s.size
c=0
for i in (n..l-1).step(n) do
  c+=1 if s[i-1]==s[i-2] and s[i-1]==s[i-2]
end
p c

n=gets.to_i
s=gets.chomp
l=s.size
c=0
for i in (n..l).step(n) do
  c+=1 if s[i-1]==s[i-2] and s[i-1]==s[i-2]
end
p c


There is a binary string $$$a$$$ of length $$$n$$$. In one operation, you can select any prefix of $$$a$$$ with an equal number of $$$0$$$ and $$$1$$$ symbols. Then all symbols in the prefix are inverted: each $$$0$$$ becomes $$$1$$$ and each $$$1$$$ becomes $$$0$$$.For example, suppose $$$a=0111010000$$$.   In the first operation, we can select the prefix of length $$$8$$$ since it has four $$$0$$$'s and four $$$1$$$'s: $$$[01110100]00\to [10001011]00$$$.  In the second operation, we can select the prefix of length $$$2$$$ since it has one $$$0$$$ and one $$$1$$$: $$$[10]00101100\to [01]00101100$$$.  It is illegal to select the prefix of length $$$4$$$ for the third operation, because it has three $$$0$$$'s and one $$$1$$$. Can you transform the string $$$a$$$ into the string $$$b$$$ using some finite number of operations (possibly, none)?

The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 3\cdot 10^5$$$) — the length of the strings $$$a$$$ and $$$b$$$. The following two lines contain strings $$$a$$$ and $$$b$$$ of length $$$n$$$, consisting of symbols $$$0$$$ and $$$1$$$. The sum of $$$n$$$ across all test cases does not exceed $$$3\cdot 10^5$$$.

For each test case, output "YES" if it is possible to transform $$$a$$$ into $$$b$$$, or "NO" if it is impossible. You can print each letter in any case (upper or lower).

NoteThe first test case is shown in the statement.In the second test case, we transform $$$a$$$ into $$$b$$$ by using zero operations.In the third test case, there is no legal operation, so it is impossible to transform $$$a$$$ into $$$b$$$.In the fourth test case, here is one such transformation:   Select the length $$$2$$$ prefix to get $$$100101010101$$$.  Select the length $$$12$$$ prefix to get $$$011010101010$$$.  Select the length $$$8$$$ prefix to get $$$100101011010$$$.  Select the length $$$4$$$ prefix to get $$$011001011010$$$.  Select the length $$$6$$$ prefix to get $$$100110011010$$$. In the fifth test case, the only legal operation is to transform $$$a$$$ into $$$111000$$$. From there, the only legal operation is to return to the string we started with, so we cannot transform $$$a$$$ into $$$b$$$.

gets.to_i.times do
  n=gets.to_i
  a=gets.chomp.chars
  b=gets.chomp.chars
  i=0
  f=true
  c=0
  j=0
  while i<n
    if a[i]=="0"
      c-=1
    else
      c+=1
    end
    if j==0
      if a[i]==b[i]
        j=1
      else
        j=-1
      end
    elsif j==1
      if a[i]!=b[i]
        f=false
        break
      end
    else
      if a[i]==b[i]
        f=false
        break
      end
    end
    if c==0
      j=0
    end
    i+=1
  end
  if j==-1
    f=false
  end
  if f
    puts "YES"
  else
    puts "NO"
  end
end

gets.to_i.times do
  n=gets.to_i
  a=gets.chomp.chars
  b=gets.chomp.chars
  i=0
  f=true
  c=0
  j=0
  while i<n
    if a[i]=="0"
      c-=1
    else
      c+=1
    end
    if j==0
      if a[i]==b[i]
        j=1
      else
        j=-1
      end
    elsif j==1
      if a[i]!=b[i]
        f=false
        break
      end
    else
      if a[i]==b[i]
        f=false
        break
      end
    end
    if c==0
      j=0
    end
    i+=1
  end
  if f
    puts "YES"
  else
    puts "NO"
  end
end


Ashish has a string $$$s$$$ of length $$$n$$$ containing only characters 'a', 'b' and 'c'.He wants to find the length of the smallest substring, which satisfies the following conditions:   Length of the substring is at least $$$2$$$  'a' occurs strictly more times in this substring than 'b'  'a' occurs strictly more times in this substring than 'c'  Ashish is busy planning his next Codeforces round. Help him solve the problem.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^{5})$$$  — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2 \le n \le 10^{6})$$$  — the length of the string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting only of characters 'a', 'b' and 'c'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^{6}$$$.

For each test case, output the length of the smallest substring which satisfies the given conditions or print $$$-1$$$ if there is no such substring.

NoteConsider the first test case. In the substring "aa", 'a' occurs twice, while 'b' and 'c' occur zero times. Since 'a' occurs strictly more times than 'b' and 'c', the substring "aa" satisfies the condition and the answer is $$$2$$$. The substring "a" also satisfies this condition, however its length is not at least $$$2$$$.In the second test case, it can be shown that in none of the substrings of "cbabb" does 'a' occur strictly more times than 'b' and 'c' each.In the third test case, "cacabccc", the length of the smallest substring that satisfies the conditions is $$$3$$$.

gets.to_i.times do

n = gets.to_i
s = gets.chomp

substrs = s.scan(/a(?:|b|c|bc|cb)(?=a)/)
m = substrs.map!(&:length).map!(&:succ).min
if m
  puts m
  next
end

substrs = s.scan(/abbacca|accabba/)
m = substrs.map!(&:length).min
if m
  puts m
  next
end

puts -1

end

gets.to_i.times do

n = gets.to_i
s = gets.chomp

substrs = s.scan(/a(?:|b|c|bc|cb)(?=a)/)
puts substrs.map!(&:length).map!(&:succ).min || -1

end


Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).Inserting an element in the same position he was erased from is also considered moving.Can Vasya divide the array after choosing the right element to move and its new position?

The first line contains single integer n (1 ≤ n ≤ 100000) — the size of the array. The second line contains n integers a1, a2... an (1 ≤ ai ≤ 109) — the elements of the array.

Print YES if Vasya can divide the array after moving one element. Otherwise print NO.

NoteIn the first example Vasya can move the second element to the end of the array.In the second example no move can make the division possible.In the third example Vasya can move the fourth element by one position to the left.

require 'set'
n = gets.to_i
array = gets.split(" ").map{|i| i.to_i}
rsum = []
totalSum = array.inject(0){|sum,x| sum + x }
sum = 0
0.upto(n-1) do |i|
  sum += array[i]
  rsum << sum
end

possible = false
possibles = {}
firstPossibles = {}
0.upto(n-1) do |i|
  left = 2*rsum[i] - totalSum
  possibles[left] = i
  if not firstPossibles.include?(left)
    firstPossibles[left] = i
  end
  if left == 0
    possible = true
  end
end

0.upto(n-1) do |i|
  if possibles.include?(2*array[i]) && possibles[2*array[i]] > i
    possible = true
  elsif firstPossibles.include?(-2*array[i]) && firstPossibles[-2*array[i]] < i
    possible = true
  end
end

if possible
  print("YES")
else
  print("NO")
end

require 'set'
n = gets.to_i
array = gets.split(" ").map{|i| i.to_i}
rsum = []
totalSum = array.inject(0){|sum,x| sum + x }
sum = 0
0.upto(n-1) do |i|
  sum += array[i]
  rsum << sum
end

possible = false
possibles = {}
0.upto(n-1) do |i|
  left = 2*rsum[i] - totalSum
  possibles[left] = i
  if left == 0
    possible = true
  end
end

0.upto(n-1) do |i|
  if possibles.include?(2*array[i]) && possibles[2*array[i]] >= i
    possible = true
  elsif possibles.include?(-2*array[i]) && possibles[-2*array[i]] <= i
    possible = true
  end
end

if possible
  print("YES")
else
  print("NO")
end

require 'set'
n = gets.to_i
array = gets.split(" ").map{|i| i.to_i}
rsum = []
totalSum = array.inject(0){|sum,x| sum + x }
sum = 0
0.upto(n-1) do |i|
  sum += array[i]
  rsum << sum
end

possible = false
possibles = Set.new
0.upto(n-1) do |i|
  left = 2*rsum[i] - totalSum
  possibles.add(left)
  if left == 0
    possible = true
  end
end

0.upto(n-1) do |i|
  if possibles.include? 2*array[i]
    possible = true
  end
end

if possible
  print("YES")
else
  print("NO")
end

require 'set'
n = gets.to_i
array = gets.split(" ").map{|i| i.to_i}
rsum = []
totalSum = array.inject(0){|sum,x| sum + x }
sum = 0
0.upto(n-1) do |i|
  sum += array[i]
  rsum << sum
end

possible = false
possibles = {}
0.upto(n-1) do |i|
  left = 2*rsum[i] - totalSum
  possibles[left] = i
  if left == 0
    possible = true
  end
end

0.upto(n-1) do |i|
  if possibles.include?(2*array[i]) && possibles[2*array[i]] >= i
    possible = true
  end
end

if possible
  print("YES")
else
  print("NO")
end


You are playing a variation of game 2048. Initially you have a multiset $$$s$$$ of $$$n$$$ integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset.During each operation you choose two equal integers from $$$s$$$, remove them from $$$s$$$ and insert the number equal to their sum into $$$s$$$.For example, if $$$s = \{1, 2, 1, 1, 4, 2, 2\}$$$ and you choose integers $$$2$$$ and $$$2$$$, then the multiset becomes $$$\{1, 1, 1, 4, 4, 2\}$$$.You win if the number $$$2048$$$ belongs to your multiset. For example, if $$$s = \{1024, 512, 512, 4\}$$$ you can win as follows: choose $$$512$$$ and $$$512$$$, your multiset turns into $$$\{1024, 1024, 4\}$$$. Then choose $$$1024$$$ and $$$1024$$$, your multiset turns into $$$\{2048, 4\}$$$ and you win.You have to determine if you can win this game.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) – the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in multiset. The second line of each query contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 2^{29}$$$) — the description of the multiset. It is guaranteed that all elements of the multiset are powers of two.

For each query print YES if it is possible to obtain the number $$$2048$$$ in your multiset, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first query you can win as follows: choose $$$512$$$ and $$$512$$$, and $$$s$$$ turns into $$$\{1024, 64, 1024\}$$$. Then choose $$$1024$$$ and $$$1024$$$, and $$$s$$$ turns into $$$\{2048, 64\}$$$ and you win.In the second query $$$s$$$ contains $$$2048$$$ initially.

include Math
gets.to_i.times do
  n = gets.to_i
  ary = gets.split.map(&:to_i)
  a2  = Array.new(12, 0)
  ary.each {|a| if a <= 2048 then a2[log(a, 2).to_i]+=1 end}
  for i in 0..10 do a2[i+1] += a2[i]/2 end
  puts a2[11] > 0 ? :YES: :NO
end


The store sells $$$n$$$ beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them.A necklace is a set of beads connected in a circle.For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemble the following necklaces (these are not all possible options):  And the following necklaces cannot be assembled from beads sold in the store:  The first necklace cannot be assembled because it has three beads "a" (of the two available). The second necklace cannot be assembled because it contains a bead "d", which is not sold in the store. We call a necklace $$$k$$$-beautiful if, when it is turned clockwise by $$$k$$$ beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace.    As you can see, this necklace is, for example, $$$3$$$-beautiful, $$$6$$$-beautiful, $$$9$$$-beautiful, and so on, but it is not $$$1$$$-beautiful or $$$2$$$-beautiful.In particular, a necklace of length $$$1$$$ is $$$k$$$-beautiful for any integer $$$k$$$. A necklace that consists of beads of the same color is also beautiful for any $$$k$$$.You are given the integers $$$n$$$ and $$$k$$$, and also the string $$$s$$$ containing $$$n$$$ lowercase letters of the English alphabet — each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a $$$k$$$-beautiful necklace you can assemble.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 2000$$$). The second line of each test case contains the string $$$s$$$ containing $$$n$$$ lowercase English letters — the beads in the store. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2000$$$.

Output $$$t$$$ answers to the test cases. Each answer is a positive integer — the maximum length of the $$$k$$$-beautiful necklace you can assemble.

6
6 3
abcbac
3 6
aaa
7 1000
abczgyo
5 4
ababa
20 10
aaebdbabdbbddaadaadc
20 5
ecbedececacbcbccbdec

NoteThe first test case is explained in the statement.In the second test case, a $$$6$$$-beautiful necklace can be assembled from all the letters.In the third test case, a $$$1000$$$-beautiful necklace can be assembled, for example, from beads "abzyo".

require 'prime'
class Integer
	def divisors
		self.prime_division.reduce([1]) do |acc, (p, e)|
			(0..e).map { p**_1 }.product(acc).map { _1 * _2 }
		end.sort
	end
end

gets.to_i.times do
	n, k = gets.split.map(&:to_i)
	s = gets.chomp
	cnt = s.chars.tally
	rindex = (1..n).reverse_each.to_a
	puts k.divisors.map { |d|
			(rindex.bsearch { |i| cnt.sum { |val, cnt| cnt / i } >= d } || 0) *
				d
	     }.max
end

require 'prime'
class Integer
	def divisors
		self.prime_division.reduce([1]) do |acc, (p, e)|
			(0..e).map { p**_1 }.product(acc).map { _1 * _2 }
		end.sort
	end
end

gets.to_i.times do
	n, k = gets.split.map(&:to_i)
	s = gets.chomp
	cnt = s.chars.tally
	puts k.divisors.map { |d|
			(
				(1..10).reverse_each.to_a.bsearch { |i|
					cnt.sum { |val, cnt| cnt / i } >= d
				} || 0
			) * d
	     }.max
end


A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Let $$$p$$$ be any permutation of length $$$n$$$. We define the fingerprint $$$F(p)$$$ of $$$p$$$ as the sorted array of sums of adjacent elements in $$$p$$$. More formally,$$$$$$F(p)=\mathrm{sort}([p_1+p_2,p_2+p_3,\ldots,p_{n-1}+p_n]).$$$$$$For example, if $$$n=4$$$ and $$$p=[1,4,2,3],$$$ then the fingerprint is given by $$$F(p)=\mathrm{sort}([1+4,4+2,2+3])=\mathrm{sort}([5,6,5])=[5,5,6]$$$.You are given a permutation $$$p$$$ of length $$$n$$$. Your task is to find a different permutation $$$p'$$$ with the same fingerprint. Two permutations $$$p$$$ and $$$p'$$$ are considered different if there is some index $$$i$$$ such that $$$p_i \ne p'_i$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 668$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2\le n\le 100$$$)  — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1,\ldots,p_n$$$ ($$$1\le p_i\le n$$$). It is guaranteed that $$$p$$$ is a permutation.

For each test case, output $$$n$$$ integers $$$p'_1,\ldots, p'_n$$$ — a permutation such that $$$p'\ne p$$$ and $$$F(p')=F(p)$$$. We can prove that for every permutation satisfying the input constraints, a solution exists. If there are multiple solutions, you may output any.

gets.to_i.times do
  n=gets.to_i
  a=gets.split(" ").map(&:to_i)
  a.reverse!
  puts a.join(" ")
end

t = gets.to_i
t.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    puts a.reverse.join(" ")
end

times = gets.to_i

(1..times).each do |i|
  array_size = gets.to_i

  a = Array.new(array_size)
  a = gets.split(/\s+/).reverse.join(" ")
  puts a
end

gets.to_i.times{gets
puts gets.split.reverse.join ' '}

T = gets.to_i

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

  puts a.reverse.join(' ')
end


Vasya bought the collected works of a well-known Berland poet Petya in n volumes. The volumes are numbered from 1 to n. He thinks that it does not do to arrange the book simply according to their order. Vasya wants to minimize the number of the disposition’s divisors — the positive integers i such that for at least one j (1 ≤ j ≤ n) is true both: j mod i = 0 and at the same time p(j) mod i = 0, where p(j) is the number of the tome that stands on the j-th place and mod is the operation of taking the division remainder. Naturally, one volume can occupy exactly one place and in one place can stand exactly one volume.Help Vasya — find the volume disposition with the minimum number of divisors.

The first line contains number n (1 ≤ n ≤ 100000) which represents the number of volumes and free places.

Print n numbers — the sought disposition with the minimum divisor number. The j-th number (1 ≤ j ≤ n) should be equal to p(j) — the number of tome that stands on the j-th place. If there are several solutions, print any of them.


Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.

NoteIn the first test case, you can add roads   from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$,  from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$,  from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$,  from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$,  from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$.  The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.

def I()gets.split.map &:to_i end
I()[0].times{n,=I();a=I().sort;x=s=i=0;(x+=s-a[i]*i;s+=a[i];i+=1)while i<n;p x+a[-1]}

def I
gets.split.map &:to_i
end
I()[0].times{n,=I();a=I().sort;x=s=i=0;(x+=s-a[i]*i;s+=a[i];i+=1)while i<n;p x+a[-1]}

gets.to_i.times{n=gets.to_i;a=(gets.split.map &:to_i).sort;x=s=i=0;(x+=s-a[i]*i;s+=a[i];i+=1)while i<n;p x+a[-1]}

gets.to_i.times{gets;a=gets.split.map &:to_i;r=i=0;for(x,y)in a.zip(a[1..])
(i+=1;r-=(y-x)*(i*(a.length-i)-1))if y
end;p r}