name = gets.chomp
numb = gets.to_i

s_hash = Hash.new
arr = []
numb.times do |j|
	l = ""
	t = ""
	s = gets.chomp
	n = s.size - 1
	cnt = 0
	for i in 1..n
		if s[i] == ' '
			l = s[0,i]
			break
		end
	end
	m = l.size
	if s[m + 1,6] == "posted"
		for i in (m + 11)..n
			if s[i] == ' '
				t = s[m + 11,i - m - 13]
				break
			end
		end
		puts t
		if t == name or l == name
			cnt = 15
		end
		if s_hash["#{l}"] == nil and l != name
			arr << l
		end

		if s_hash["#{t}"] == nil and t != name
			arr << t
		end

		s_hash["#{l}"] = s_hash["#{l}"].to_i + cnt
		s_hash["#{t}"] = s_hash["#{t}"].to_i + cnt
	end

	if s[m + 1,9] == "commented"
		for i in (m + 14)..n
			if s[i] == ' '
				t = s[m + 14,i - m - 16]
				break
			end
		end

		if t == name or l == name
			cnt = 10
		end
		if s_hash["#{l}"] == nil and l != name
			arr << l
		end

		if s_hash["#{t}"] == nil and t != name
			arr << t
		end

		s_hash["#{l}"] = s_hash["#{l}"].to_i + cnt
		s_hash["#{t}"] = s_hash["#{t}"].to_i + cnt
	end

		if s[m + 1,5] == "likes"
		for i in (m + 7)..n
			if s[i] == ' '
				t = s[m + 7,i - m - 9]
				break
			end
		end
		if t == name or l == name
			cnt = 5
		end
		if s_hash["#{l}"] == nil and l != name
			arr << l
		end

		if s_hash["#{t}"] == nil and t != name
			arr << t
		end

		s_hash["#{l}"] = s_hash["#{l}"].to_i + cnt
		s_hash["#{t}"] = s_hash["#{t}"].to_i + cnt
	end

end

arr.sort!

arr.sort_by! {|element| [-s_hash["#{element}"].to_i, -element] }

c = arr.size

c.times do |i|
	puts  arr[i]
end

Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described).This priority factor will be affected by three types of actions:   1. "X posted on Y's wall" (15 points),  2. "X commented on Y's post" (10 points),  3. "X likes Y's post" (5 points). X and Y will be two distinct names. And each action will increase the priority factor between X and Y (and vice versa) by the above value of points (the priority factor between X and Y is the same as the priority factor between Y and X).You will be given n actions with the above format (without the action number and the number of points), and you have to print all the distinct names in these actions sorted according to the priority factor with you.

The first line contains your name. The second line contains an integer n, which is the number of actions (1≤n≤100). Then n lines follow, it is guaranteed that each one contains exactly 1 action in the format given above. There is exactly one space between each two words in a line, and there are no extra spaces. All the letters are lowercase. All names in the input will consist of at least 1 letter and at most 10 small Latin letters.

Print m lines, where m is the number of distinct names in the input (excluding yourself). Each line should contain just 1 name. The names should be sorted according to the priority factor with you in the descending order (the highest priority factor should come first). If two or more names have the same priority factor, print them in the alphabetical (lexicographical) order.
Note, that you should output all the names that are present in the input data (excluding yourself), even if that person has a zero priority factor.
The lexicographical comparison is performed by the standard "<" operator in modern programming languages. The line a is lexicographically smaller than the line b, if either a is the prefix of b, or if exists such an i (1≤i≤min(|a|,|b|)), that ai<bi, and for any j (1≤j<i) aj=bj, where |a| and |b| stand for the lengths of strings a and b correspondently.

ahmed
3
ahmed posted on fatma's wall
fatma commented on ahmed's post
mona likes ahmed's post

name = gets.chomp
numb = gets.to_i

s_hash = Hash.new
arr = []
numb.times do |j|
	l = ""
	t = ""
	s = gets.chomp
	n = s.size - 1
	cnt = 0
	for i in 1..n
		if s[i] == ' '
			l = s[0,i]
			break
		end
	end
	m = l.size
	if s[m + 1,6] == "posted"
		for i in (m + 11)..n
			if s[i] == ' '
				t = s[m + 11,i - m - 13]
				break
			end
		end
		if t == name or l == name
			cnt = 15
		end
		if s_hash["#{l}"] == nil and l != name
			arr << l
		end

		if s_hash["#{t}"] == nil and t != name
			arr << t
		end

		s_hash["#{l}"] = s_hash["#{l}"].to_i + cnt
		s_hash["#{t}"] = s_hash["#{t}"].to_i + cnt
	end

	if s[m + 1,9] == "commented"
		for i in (m + 14)..n
			if s[i] == ' '
				t = s[m + 14,i - m - 16]
				break
			end
		end

		if t == name or l == name
			cnt = 10
		end
		if s_hash["#{l}"] == nil and l != name
			arr << l
		end

		if s_hash["#{t}"] == nil and t != name
			arr << t
		end

		s_hash["#{l}"] = s_hash["#{l}"].to_i + cnt
		s_hash["#{t}"] = s_hash["#{t}"].to_i + cnt
	end

		if s[m + 1,5] == "likes"
		for i in (m + 7)..n
			if s[i] == ' '
				t = s[m + 7,i - m - 9]
				break
			end
		end
		if t == name or l == name
			cnt = 5
		end
		if s_hash["#{l}"] == nil and l != name
			arr << l
		end

		if s_hash["#{t}"] == nil and t != name
			arr << t
		end

		s_hash["#{l}"] = s_hash["#{l}"].to_i + cnt
		s_hash["#{t}"] = s_hash["#{t}"].to_i + cnt
	end

end

arr.sort!

arr.sort_by! {|element| [-s_hash["#{element}"].to_i, -element] }

c = arr.size

c.times do |i|
	puts  arr[i]
end

[{'input': ["ahmed\r\n3\r\nahmed posted on fatma's wall\r\nfatma commented on ahmed's post\r\nmona likes ahmed's post\r\n"], 'output': ['fatma\r\nmona\r\n']}, {'input': ["aba\r\n1\r\nlikes likes posted's post\r\n"], 'output': ['likes\r\nposted\r\n']}, {'input': ["nu\r\n5\r\ng commented on pwyndmh's post\r\nqv posted on g's wall\r\ng likes nu's post\r\ng posted on nu's wall\r\nqv commented on pwyndmh's post\r\n"], 'output': ['g\r\npwyndmh\r\nqv\r\n']}, {'input': ["szfwtzfp\r\n5\r\nzqx posted on szfwtzfp's wall\r\nr commented on scguem's post\r\nr posted on civ's wall\r\nr likes scguem's post\r\nr likes scguem's post\r\n"], 'output': ['zqx\r\nciv\r\nr\r\nscguem\r\n']}, {'input': ["oaquudhavr\r\n3\r\ni posted on cwfwujpc's wall\r\ni likes oaquudhavr's post\r\noaquudhavr commented on cwfwujpc's post\r\n"], 'output': ['cwfwujpc\r\ni\r\n']}, {'input': ["eo\r\n4\r\neo commented on xkgjgwxtrx's post\r\neo posted on iqquh's wall\r\nn commented on xkgjgwxtrx's post\r\niqquh commented on n's post\r\n"], 'output': ['iqquh\r\nxkgjgwxtrx\r\nn\r\n']}, {'input': ["plwun\r\n3\r\neusjuq commented on plwun's post\r\nagktgdar likes eusjuq's post\r\nagppcoil likes agktgdar's post\r\n"], 'output': ['eusjuq\r\nagktgdar\r\nagppcoil\r\n']}, {'input': ["fgzrn\r\n3\r\nzhl likes fgzrn's post\r\nxryet likes fgzrn's post\r\nzhl commented on fgzrn's post\r\n"], 'output': ['zhl\r\nxryet\r\n']}, {'input': ["qatugmdjwg\r\n3\r\nb posted on cf's wall\r\nyjxkat posted on b's wall\r\nko commented on qatugmdjwg's post\r\n"], 'output': ['ko\r\nb\r\ncf\r\nyjxkat\r\n']}, {'input': ["dagwdwxsuf\r\n5\r\nesrvncb commented on dagwdwxsuf's post\r\nzcepigpbz posted on dagwdwxsuf's wall\r\nesrvncb commented on zcepigpbz's post\r\nesrvncb commented on dagwdwxsuf's post\r\ndagwdwxsuf commented on esrvncb's post\r\n"], 'output': ['esrvncb\r\nzcepigpbz\r\n']}, {'input': ["a\r\n1\r\nb likes c's post\r\n"], 'output': ['b\r\nc\r\n']}, {'input': ["a\r\n1\r\nc likes b's post\r\n"], 'output': ['b\r\nc\r\n']}, {'input': ["wuaiz\r\n10\r\nmnbggnud posted on xttaqvel's wall\r\ns posted on xopffmspf's wall\r\nkysxb likes qnrtpzkh's post\r\ngptks likes quebtsup's post\r\nkgmd commented on kmtnhsiue's post\r\newqjtxtiyn commented on a's post\r\nol posted on iglplaj's wall\r\nif posted on yuo's wall\r\nfs posted on dwjtuhgrq's wall\r\nygmdprun likes tzfneuly's post\r\n"], 'output': ['a\r\ndwjtuhgrq\r\newqjtxtiyn\r\nfs\r\ngptks\r\nif\r\niglplaj\r\nkgmd\r\nkmtnhsiue\r\nkysxb\r\nmnbggnud\r\nol\r\nqnrtpzkh\r\nquebtsup\r\ns\r\ntzfneuly\r\nxopffmspf\r\nxttaqvel\r\nygmdprun\r\nyuo\r\n']}, {'input': ["fzhzg\r\n11\r\nv likes xyf's post\r\nktqtpzhlh commented on ffsxarrn's post\r\nktqtpzhlh commented on lbt's post\r\njcdwpcycj commented on qbuigcgflm's post\r\nl likes pmg's post\r\nracszbmsk posted on ojr's wall\r\nojr commented on n's post\r\nnzqx commented on lkj's post\r\nv posted on lzoca's wall\r\nnwqnoham commented on gyivezpu's post\r\nfzhzg likes uqvzgzrpac's post\r\n"], 'output': ['uqvzgzrpac\r\nffsxarrn\r\ngyivezpu\r\njcdwpcycj\r\nktqtpzhlh\r\nl\r\nlbt\r\nlkj\r\nlzoca\r\nn\r\nnwqnoham\r\nnzqx\r\nojr\r\npmg\r\nqbuigcgflm\r\nracszbmsk\r\nv\r\nxyf\r\n']}, {'input': ["qdrnpb\r\n12\r\nymklhj commented on dkcbo's post\r\nhcucrenckl posted on mut's wall\r\nnvkyta commented on eo's post\r\npvgow likes mut's post\r\nob likes wlwcxtf's post\r\npvgow commented on advpu's post\r\nkfflyfbr commented on igozjnrxw's post\r\nsq commented on qdrnpb's post\r\nmrvn posted on lahduc's wall\r\ngsnlicy likes u's post\r\ndltqujf commented on qgzk's post\r\nr posted on bey's wall\r\n"], 'output': ['sq\r\nadvpu\r\nbey\r\ndkcbo\r\ndltqujf\r\neo\r\ngsnlicy\r\nhcucrenckl\r\nigozjnrxw\r\nkfflyfbr\r\nlahduc\r\nmrvn\r\nmut\r\nnvkyta\r\nob\r\npvgow\r\nqgzk\r\nr\r\nu\r\nwlwcxtf\r\nymklhj\r\n']}, {'input': ["biycvwb\r\n13\r\nhp likes cigobksf's post\r\nmcoqt commented on gaswzwat's post\r\nnz posted on xyvetbokl's wall\r\nqbnwy commented on ylkfbwjy's post\r\nqdwktrro likes rxgujnzecs's post\r\nbbsw commented on hwtatkfnps's post\r\ngspx posted on ugjxfnahuc's wall\r\nxlmut likes plle's post\r\numbwlleag commented on xfwlhen's post\r\nrlwxqksbwi commented on rypqtrgf's post\r\nbj posted on vovq's wall\r\nozpdpb commented on zti's post\r\nhqj posted on rxgujnzecs's wall\r\n"], 'output': ['bbsw\r\nbj\r\ncigobksf\r\ngaswzwat\r\ngspx\r\nhp\r\nhqj\r\nhwtatkfnps\r\nmcoqt\r\nnz\r\nozpdpb\r\nplle\r\nqbnwy\r\nqdwktrro\r\nrlwxqksbwi\r\nrxgujnzecs\r\nrypqtrgf\r\nugjxfnahuc\r\numbwlleag\r\nvovq\r\nxfwlhen\r\nxlmut\r\nxyvetbokl\r\nylkfbwjy\r\nzti\r\n']}, {'input': ["kmircqsffq\r\n14\r\nfrnf likes xgmmp's post\r\nfnfdpupayp commented on syz's post\r\nxefshpn commented on xgmmp's post\r\nm posted on gdwydzktok's wall\r\neskm likes pqmbnuc's post\r\npnqiapduhz likes zzqvjdz's post\r\nx likes nouuurc's post\r\nvnyxhoukuo posted on uhblapjab's wall\r\nblpjpxn likes zvwbger's post\r\nj posted on vuknetvl's wall\r\nscsw commented on xaggwxlxe's post\r\npqmbnuc commented on ojwaibie's post\r\niaazdlqdew commented on kmircqsffq's post\r\nqznqshxdi commented on umdqztoqun's post\r\n"], 'output': ['iaazdlqdew\r\nblpjpxn\r\neskm\r\nfnfdpupayp\r\nfrnf\r\ngdwydzktok\r\nj\r\nm\r\nnouuurc\r\nojwaibie\r\npnqiapduhz\r\npqmbnuc\r\nqznqshxdi\r\nscsw\r\nsyz\r\nuhblapjab\r\numdqztoqun\r\nvnyxhoukuo\r\nvuknetvl\r\nx\r\nxaggwxlxe\r\nxefshpn\r\nxgmmp\r\nzvwbger\r\nzzqvjdz\r\n']}, {'input': ["posted\r\n3\r\nposted posted on fatma's wall\r\nfatma commented on posted's post\r\nmona likes posted's post\r\n"], 'output': ['fatma\r\nmona\r\n']}, {'input': ["posted\r\n3\r\nposted posted on wall's wall\r\nwall commented on posted's post\r\nmona likes posted's post\r\n"], 'output': ['wall\r\nmona\r\n']}, {'input': ["posted\r\n3\r\nposted posted on wall's wall\r\nwall commented on posted's post\r\npost likes posted's post\r\n"], 'output': ['wall\r\npost\r\n']}, {'input': ["wall\r\n5\r\nwall posted on posted's wall\r\nwall posted on on's wall\r\nwall posted on commented's wall\r\nwall posted on likes's wall\r\nwall posted on post's wall\r\n"], 'output': ['commented\r\nlikes\r\non\r\npost\r\nposted\r\n']}, {'input': ["commented\r\n5\r\non commented on commented's post\r\npos commented on commented's post\r\nlikes commented on commented's post\r\nposted commented on commented's post\r\nwall commented on commented's post\r\n"], 'output': ['likes\r\non\r\npos\r\nposted\r\nwall\r\n']}, {'input': ["likes\r\n3\r\nlikes posted on post's wall\r\nlikes commented on on's post\r\nlikes likes commented's post\r\n"], 'output': ['post\r\non\r\ncommented\r\n']}, {'input': ["on\r\n4\r\non posted on posted's wall\r\non commented on commented's post\r\non posted on wall's wall\r\non commented on post's post\r\n"], 'output': ['posted\r\nwall\r\ncommented\r\npost\r\n']}, {'input': ["wall\r\n9\r\nwall posted on posted's wall\r\non commented on wall's post\r\nwall likes post's post\r\nposted posted on wall's wall\r\nwall commented on post's post\r\nlikes likes wall's post\r\nwall posted on on's wall\r\npost commented on wall's post\r\nwall likes likes's post\r\n"], 'output': ['posted\r\non\r\npost\r\nlikes\r\n']}, {'input': ["post\r\n9\r\npost posted on wall's wall\r\non commented on post's post\r\npost likes likes's post\r\ncommented posted on post's wall\r\npost commented on likes's post\r\nlikes likes post's post\r\npost posted on posted's wall\r\non commented on post's post\r\npost likes commented's post\r\n"], 'output': ['commented\r\nlikes\r\non\r\nposted\r\nwall\r\n']}, {'input': ["ahmed\r\n9\r\npost posted on ahmeds's wall\r\nahmeds commented on post's post\r\npost likes ahmeds's post\r\nahmeds posted on post's wall\r\npost commented on ahmeds's post\r\nahmeds likes post's post\r\npost posted on ahmeds's wall\r\nahmeds commented on post's post\r\npost likes ahmeds's post\r\n"], 'output': ['ahmeds\r\npost\r\n']}]


t = gets.chomp.to_i
hh, mm = gets.chomp.split(':').map(&:to_i)

mm = mm % 10 if 59 < mm
if t == 12
  hh = hh % 10 if 12 < hh
  hh = 10 if hh == 0
else
  hh = hh % 10 if 24 < hh
end

puts '%02d:%02d' % [hh, mm]

You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.

format = gets.to_i
hour, minute = gets.strip.split(":").map(&:to_i)
if format == 12 and hour == 0
  hour = 1
elsif format == 12 and hour > 12
  hour %= 10
  hour = 10 if hour == 0
elsif format == 24 and hour >= 24
  hour %= 10
end
if minute >= 60
  minute %= 10
end
puts "%02d:%02d" % [hour, minute]


#!/usr/bin/ruby
a,b,n=gets.split.map(&:to_i)
if a==0
	puts b==0 ? 1 : 'No solution'
	exit
end
if a<0 then a=-a;b=-b end
sign=1
if b<0
	sign=-1 if n.odd?
	b=-b
end
r=(b.to_f/a)**(1.0/n)+1e-7
if (r-r.to_i).abs>1e-7 then puts 'No solution';exit end
p r.to_i*sign

A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative — it means that there was a loss in the correspondent year). King wants to show financial stability. To do this, he needs to find common coefficient X — the coefficient of income growth during one year. This coefficient should satisfy the equation:A·Xn = B.Surely, the king is not going to do this job by himself, and demands you to find such number X.It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient X must be integers. The number X may be zero or negative.

The input contains three integers A, B, n (|A|, |B| ≤ 1000, 1 ≤ n ≤ 10).

Output the required integer coefficient X, or «No solution», if such a coefficient does not exist or it is fractional. If there are several possible solutions, output any of them.

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if (result - result.round).abs < 0.000000001
  if (b/a < 0)
    print "-"
  end
  print result.round.to_s.split(".")[0]
else
  puts "No solution"
end


def solve(a)
  return a if a < 10
  l, r = a, a % 10
  while l >= 10
    l /= 10
  end
  ans = a / 10 + 9
  ans -= 1 if r > l
  return ans
end

l, r = gets.split.map { |i| i.to_i }
puts solve(r) - solve(rl - 1)

The Little Elephant very much loves sums on intervals.This time he has a pair of integers l and r (l ≤ r). The Little Elephant has to find the number of such integers x (l ≤ x ≤ r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not.Help him and count the number of described numbers x for a given pair l and r.

The single line contains a pair of integers l and r (1 ≤ l ≤ r ≤ 1018) — the boundaries of the interval. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

On a single line print a single integer — the answer to the problem.

NoteIn the first sample the answer includes integers 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44.

l,r = gets.split

k=0

l1 = l.clone
r1 = r.clone

l1[-1] = l1[0]
if l1.to_i<l.to_i then
  l1=(l1.to_i+10).to_s
  l1[-1]=l1[0]
end

if r1=='10' then r1='9' end
r1[-1] = r1[0]
if r1.to_i>r.to_i then
  r1=(r1.to_i-10).to_s
  r1[-1]=r1[0]
end

def count(b,e,x)
  (e-b+1)*(10**([x-2 ,0].max))
end

def ans(s)
  z=0
  (1..s.length-1).each do |por|
    z+=count(1,9,por)
  end
  z+=count(1,s[0].to_i-1,s.length)+s[1..-2].to_i+1
end
k+=ans(r1)
k-=ans(l1)
k+=1
puts k


n,l=gets.split.map(&:to_i)
ans=0
a=gets.split.map(&:to_i)
a.each{|b|
        ans+=b/l
}
p ans*l

The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they may not have the same length (it is even possible for them to have different lengths)Every stripe can be cut into two or more parts. The cuttings are made perpendicularly to the side along which the length is measured. Thus the cuttings do not change the width of a stripe but each of the resulting pieces has a lesser length (the sum of which is equal to the length of the initial stripe)After all the cuttings the blinds are constructed through consecutive joining of several parts, similar in length, along sides, along which length is measured. Also, apart from the resulting pieces an initial stripe can be used as a blind if it hasn't been cut. It is forbidden to construct blinds in any other way.Thus, if the blinds consist of k pieces each d in length, then they are of form of a rectangle of k × d bourlemeters. Your task is to find for what window possessing the largest possible area the blinds can be made from the given stripes if on technical grounds it is forbidden to use pieces shorter than l bourlemeter. The window is of form of a rectangle with side lengths as positive integers.

The first output line contains two space-separated integers n and l (1 ≤ n, l ≤ 100). They are the number of stripes in the warehouse and the minimal acceptable length of a blind stripe in bourlemeters. The second line contains space-separated n integers ai. They are the lengths of initial stripes in bourlemeters (1 ≤ ai ≤ 100).

Print the single number — the maximal area of the window in square bourlemeters that can be completely covered. If no window with a positive area that can be covered completely without breaking any of the given rules exist, then print the single number 0.

NoteIn the first sample test the required window is 2 × 4 in size and the blinds for it consist of 4 parts, each 2 bourlemeters long. One of the parts is the initial stripe with the length of 2, the other one is a part of a cut stripe with the length of 3 and the two remaining stripes are parts of a stripe with the length of 4 cut in halves.

n,l = gets.chomp.split(/ /).map!{|x| x.to_i}
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
ar.sort!
ar.reverse!
maxsum = 0
for j in l..ar[0]
	sum = 0
	for i in 0..ar.length-1
		if ar[i] >= j
			dv = ar[i] / j
			sum += dv * j
		end
	end
	maxsum = sum if maxsum < sum
end
puts maxsum


x, y = gets.strip.split(?.)
if x % 10 == 9
    puts 'GOTO Vasilisa.'
else
   puts x.to_i +  (y[0] > ?4 ? 1 : 0)
end

In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this: If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the number’s integer part.  If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the number’s integer part. If the number’s integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position. Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King’s order?

The first line contains a single number to round up — the integer part (a non-empty set of decimal digits that do not start with 0 — with the exception of a case when the set consists of a single digit — in this case 0 can go first), then follows character «.» (a dot), and then follows the fractional part (any non-empty set of decimal digits). The number's length does not exceed 1000 characters, including the dot. There are no other characters in the input data.

If the last number of the integer part is not equal to 9, print the rounded-up number without leading zeroes. Otherwise, print the message "GOTO Vasilisa." (without the quotes).

x, y = gets.strip.split(?.); x = x.to_i
puts x % 10 == 9 ? 'GOTO Vasilisa.' : x + (y[0] > ?4 ? 1 : 0)


ss = gets.chomp
if ss.slice(ss.length-1) == "."
  puts "NO"
  exit
end
s = ss.split(".")
ret = []
pp = ""
for i in 0..s.length-1
   if s[i].length <= 0
      ret = nil
      break
   end
   if i == 0
    if s[i].length > 8
      ret = nil
      break
    end
    pp = s[i]
  elsif i == s.length-1
    if s[i].length > 3
      ret = nil
      break
    end
    ret << pp + "." + s[i]
  else
    if s[i].length > 11 || s[i].length <= 1
      ret = nil
      break
    end
    if s[i].length == 2
      ret << pp + "." + s[i].slice(0,1)
      pp = s[i].slice(1,1)
    elsif s[i].length == 3
      ret << pp + "." + s[i].slice(0,2)
      pp = s[i].slice(2,1)
    else
      ret << pp + "." + s[i].slice(0,3)
      pp = s[i].slice(3,s[i].length-3)
    end
   end
end

if ret == nil
    puts "NO"
else
    puts "YES"
    for i in 0..ret.length-1
      puts ret[i]
    end
end

Eudokimus, a system administrator is in trouble again. As a result of an error in some script, a list of names of very important files has been damaged. Since they were files in the BerFS file system, it is known that each file name has a form "name.ext", where:   name is a string consisting of lowercase Latin letters, its length is from 1 to 8 characters;  ext is a string consisting of lowercase Latin letters, its length is from 1 to 3 characters. For example, "read.me", "example.txt" and "b.cpp" are valid file names and "version.info", "ntldr" and "contestdata.zip" are not.Damage to the list meant that all the file names were recorded one after another, without any separators. So now Eudokimus has a single string.Eudokimus needs to set everything right as soon as possible. He should divide the resulting string into parts so that each part would be a valid file name in BerFS. Since Eudokimus has already proved that he is not good at programming, help him. The resulting file list can contain the same file names.

The input data consists of a single string s, its length is from 1 to 4·105 characters. The string can contain only lowercase Latin letters ('a' - 'z') and periods ('.').

In the first line print "YES" (without the quotes), if it is possible to divide s into parts as required. In this case, the following lines should contain the parts of the required partition, one per line in the order in which they appear in s. The required partition can contain the same file names. If there are multiple solutions, print any of them. If the solution does not exist, then print in a single line "NO" (without the quotes).

[{'input': 'read.meexample.txtb.cpp\r\n', 'output': ['YES\r\nread.m\r\neexample.t\r\nxtb.cpp\r\n']}, {'input': 'version.infontldrcontestdata.zip\r\n', 'output': ['NO\r\n']}, {'input': 'thisis.text.txt\r\n', 'output': ['YES\r\nthisis.t\r\next.txt\r\n']}, {'input': 'oops.t\r\n', 'output': ['YES\r\noops.t\r\n']}, {'input': 'thisislongfilename\r\n', 'output': ['NO\r\n']}, {'input': 'double..dot\r\n', 'output': ['NO\r\n']}, {'input': 'one.one.one.one.one.one.one.one.one.one\r\n', 'output': ['YES\r\none.o\r\nne.o\r\nne.o\r\nne.o\r\nne.o\r\nne.o\r\nne.o\r\nne.o\r\nne.one\r\n']}, {'input': '.\r\n', 'output': ['NO\r\n']}, {'input': 'z\r\n', 'output': ['NO\r\n']}, {'input': 'a.\r\n', 'output': ['NO\r\n']}, {'input': '.a\r\n', 'output': ['NO\r\n']}, {'input': 'za\r\n', 'output': ['NO\r\n']}, {'input': '..\r\n', 'output': ['NO\r\n']}, {'input': 'xlq\r\n', 'output': ['NO\r\n']}, {'input': '.r.\r\n', 'output': ['NO\r\n']}, {'input': 'ulmc\r\n', 'output': ['NO\r\n']}, {'input': 'nja.\r\n', 'output': ['NO\r\n']}, {'input': 't..kz\r\n', 'output': ['NO\r\n']}, {'input': 'twaha\r\n', 'output': ['NO\r\n']}, {'input': 'm..dw.\r\n', 'output': ['NO\r\n']}, {'input': 'utsvfg.\r\n', 'output': ['NO\r\n']}, {'input': '.we.voae\r\n', 'output': ['NO\r\n']}, {'input': 'kw.gkcxk.\r\n', 'output': ['NO\r\n']}, {'input': '.c.v.hpehh\r\n', 'output': ['NO\r\n']}, {'input': 'akymwh\r\n', 'output': ['NO\r\n']}, {'input': 'jx.lqv.\r\n', 'output': ['NO\r\n']}, {'input': 'qkwtq.zw\r\n', 'output': ['YES\r\nqkwtq.zw\r\n']}, {'input': 'yxwvlk..b\r\n', 'output': ['NO\r\n']}, {'input': 'ph..qlr.pt\r\n', 'output': ['NO\r\n']}, {'input': 'cab.ab.bac\r\n', 'output': ['YES\r\ncab.a\r\nb.bac\r\n']}, {'input': 'badaba.ae\r\n', 'output': ['YES\r\nbadaba.ae\r\n']}, {'input': 'badabaca.mor\r\n', 'output': ['YES\r\nbadabaca.mor\r\n']}, {'input': 'bae.a\r\n', 'output': ['YES\r\nbae.a\r\n']}, {'input': 'b.baba.ebpbac.iabaeabac.abab.adabacaba.ahcggibij.adaacab.ebaba.aa.abacaba.dacabada.daqjcpc.jadab.dab\r\n', 'output': ['YES\r\nb.b\r\naba.e\r\nbpbac.i\r\nabaeabac.a\r\nbab.a\r\ndabacaba.a\r\nhcggibij.a\r\ndaacab.e\r\nbaba.a\r\na.a\r\nbacaba.d\r\nacabada.d\r\naqjcpc.j\r\nadab.dab\r\n']}, {'input': '.ab\r\n', 'output': ['NO\r\n']}, {'input': 'aa.aa.aaaabbbbccc.ddd.ee\r\n', 'output': ['YES\r\naa.a\r\na.aaa\r\nabbbbccc.d\r\ndd.ee\r\n']}, {'input': 'a.aaaa\r\n', 'output': ['NO\r\n']}, {'input': 'aaaaread.meexample.txtb.cpp\r\n', 'output': ['YES\r\naaaaread.m\r\neexample.t\r\nxtb.cpp\r\n']}, {'input': 'abcdabcd.a\r\n', 'output': ['YES\r\nabcdabcd.a\r\n']}, {'input': 'qwertyuio.qwe\r\n', 'output': ['NO\r\n']}, {'input': 'asd.\r\n', 'output': ['NO\r\n']}, {'input': 'aaaaaaaa.\r\n', 'output': ['NO\r\n']}, {'input': 'a.txtaaaaaaaaa.txt\r\n', 'output': ['NO\r\n']}, {'input': '.abcde.cpp\r\n', 'output': ['NO\r\n']}, {'input': '.abc.cpp\r\n', 'output': ['NO\r\n']}, {'input': 'abcdefgh.aaaabcdefgh.bbb\r\n', 'output': ['YES\r\nabcdefgh.aaa\r\nabcdefgh.bbb\r\n']}, {'input': 'filename.exe\r\n', 'output': ['YES\r\nfilename.exe\r\n']}, {'input': '.abcd.cpp\r\n', 'output': ['NO\r\n']}, {'input': 'abc.bcdabcdabcd.abc\r\n', 'output': ['YES\r\nabc.bcd\r\nabcdabcd.abc\r\n']}, {'input': 'abc.abcde\r\n', 'output': ['NO\r\n']}, {'input': 'a.cp\r\n', 'output': ['YES\r\na.cp\r\n']}, {'input': 'a.b.c\r\n', 'output': ['NO\r\n']}, {'input': '.ha\r\n', 'output': ['NO\r\n']}, {'input': 'a.a.a.a\r\n', 'output': ['NO\r\n']}, {'input': 'a.a.a\r\n', 'output': ['NO\r\n']}, {'input': 'qwertyui.cp\r\n', 'output': ['YES\r\nqwertyui.cp\r\n']}, {'input': 'ss.aaaaaaaaaaaa.aa\r\n', 'output': ['NO\r\n']}, {'input': 'name.extnamename.ext\r\n', 'output': ['YES\r\nname.ext\r\nnamename.ext\r\n']}, {'input': '.aaaa.aaa\r\n', 'output': ['NO\r\n']}, {'input': 'aaaaaaaaaaaaaaaaaaaa.a\r\n', 'output': ['NO\r\n']}, {'input': '.filena.exe\r\n', 'output': ['NO\r\n']}, {'input': 'a.aaaaaaaaaaa.a\r\n', 'output': ['YES\r\na.aaa\r\naaaaaaaa.a\r\n']}, {'input': '.aa.w\r\n', 'output': ['NO\r\n']}]


#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
require 'prime'
require 'mathn'
#=================================

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

board_main=[]
board_copy=[]
n.times{
	line = gets.strip.split(//)
	board_main << line
	board_copy << line.dup
}

for i in 0...n
	for j in 0...m
		ch = board_main[i][j]

		# rows
		count=0
		for row_index in 0...n
			count+=1 if board_main[row_index][j]==ch
		end

		if count!=1
			for row_index in 0...n
				board_copy[row_index][j]="_" if board_main[row_index][j]==ch
			end
		end

		# cols
		count=0
		for col_index in 0...m
			count+=1 if board_main[i][col_index]==ch
		end

		if count!=1
			for col_index in 0...m
				board_copy[i][col_index]="_" if board_main[i][col_index]==ch
			end
		end
	end
end

for i in 0...n
	for j in 0...m
		print board_copy[i][j]
	end
	puts
end

An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.

The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.

Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.

n,m = gets.chomp.split(/ /).map!{|x| x.to_i}
bd = Array.new(n)
bdf = Array.new(n)
for i in 0..n-1
	bd[i] = gets.chomp.split(//)
	bdf[i] = Array.new(m)
end

for i in 0..n-1
	for j in 0..m-1
		bdf[i][j] = true
	end
end

for i in 0..n-1
	h = Hash.new
	for j in 0..m-1
		if h.key?(bd[i][j])
			h[bd[i][j]] += 1
		else
			h[bd[i][j]] = 1
		end
	end
	for j in 0..m-1
		bdf[i][j] = false if h[bd[i][j]] > 1
	end
end

for j in 0..m-1
	h = Hash.new
	for i in 0..n-1
		if h.key?(bd[i][j])
			h[bd[i][j]] += 1
		else
			h[bd[i][j]] = 1
		end
	end
	for i in 0..n-1
		bdf[i][j] = false if h[bd[i][j]] > 1
	end
end

for i in 0..n-1
	for j in 0..m-1
		print bd[i][j] if bdf[i][j] == true
	end
end

puts ""

[{'input': '3 3\r\ncba\r\nbcd\r\ncbc\r\n', 'output': ['abcd']}, {'input': '5 5\r\nfcofd\r\nooedo\r\nafaoa\r\nrdcdf\r\neofsf\r\n', 'output': ['codeforces']}, {'input': '4 4\r\nusah\r\nusha\r\nhasu\r\nsuha\r\n', 'output': ['ahhasusu']}, {'input': '7 5\r\naabcd\r\neffgh\r\niijkk\r\nlmnoo\r\npqqrs\r\nttuvw\r\nxxyyz\r\n', 'output': ['bcdeghjlmnprsuvwz']}, {'input': '10 10\r\naaaaaaaaaa\r\nbccceeeeee\r\ncdfffffffe\r\ncdfiiiiile\r\ncdfjjjjile\r\ndddddddile\r\nedfkkkkile\r\nedddddddde\r\ngggggggggg\r\nhhhhhhhhhe\r\n', 'output': ['b']}, {'input': '15 3\r\njhg\r\njkn\r\njui\r\nfth\r\noij\r\nyuf\r\nyfb\r\nugd\r\nhgd\r\noih\r\nhvc\r\nugg\r\nyvv\r\ntdg\r\nhgf\r\n', 'output': ['hkniftjfbctd']}, {'input': '17 19\r\nbmzbmweyydiadtlcoue\r\ngmdbyfwurpwbpuvhifn\r\nuapwyndmhtqvkgkbhty\r\ntszotwflegsjzzszfwt\r\nzfpnscguemwrczqxyci\r\nvdqnkypnxnnpmuduhzn\r\noaquudhavrncwfwujpc\r\nmiggjmcmkkbnjfeodxk\r\ngjgwxtrxingiqquhuwq\r\nhdswxxrxuzzfhkplwun\r\nfagppcoildagktgdarv\r\neusjuqfistulgbglwmf\r\ngzrnyxryetwzhlnfewc\r\nzmnoozlqatugmdjwgzc\r\nfabbkoxyjxkatjmpprs\r\nwkdkobdagwdwxsufees\r\nrvncbszcepigpbzuzoo\r\n', 'output': ['lcorviunqvgblgjfsgmrqxyivyxodhvrjpicbneodxjtfkpolvejqmllqadjwotmbgxrvs']}, {'input': '1 1\r\na\r\n', 'output': ['a']}, {'input': '2 2\r\nzx\r\nxz\r\n', 'output': ['zxxz']}, {'input': '1 2\r\nfg\r\n', 'output': ['fg']}, {'input': '2 1\r\nh\r\nj\r\n', 'output': ['hj']}, {'input': '1 3\r\niji\r\n', 'output': ['j']}, {'input': '3 1\r\nk\r\np\r\nk\r\n', 'output': ['p']}, {'input': '2 3\r\nmhw\r\nbfq\r\n', 'output': ['mhwbfq']}, {'input': '3 2\r\nxe\r\ner\r\nwb\r\n', 'output': ['xeerwb']}, {'input': '3 7\r\nnutuvjg\r\ntgqutfn\r\nyfjeiot\r\n', 'output': ['ntvjggqfnyfjeiot']}, {'input': '5 4\r\nuzvs\r\namfz\r\nwypl\r\nxizp\r\nfhmf\r\n', 'output': ['uzvsamfzwyplxizphm']}, {'input': '8 9\r\ntjqrtgrem\r\nrwjcfuoey\r\nywrjgpzca\r\nwabzggojv\r\najqmmcclh\r\nozilebskd\r\nqmgnbmtcq\r\nwakptzkjr\r\n', 'output': ['mrjcfuyyrjpzabzvalhozilebskdgnbtpzr']}, {'input': '9 3\r\njel\r\njws\r\ntab\r\nvyo\r\nkgm\r\npls\r\nabq\r\nbjx\r\nljt\r\n', 'output': ['elwtabvyokgmplabqbxlt']}, {'input': '7 6\r\neklgxi\r\nxmpzgf\r\nxvwcmr\r\nrqssed\r\nouiqpt\r\ndueiok\r\nbbuorv\r\n', 'output': ['eklgximpzgfvwcmrrqedoiqptdeiokuorv']}, {'input': '14 27\r\npzoshpvvjdpmwfoeojapmkxjrnk\r\nitoojpcorxjdxrwyewtmmlhjxhx\r\ndoyopbwusgsmephixzcilxpskxh\r\nygpvepeuxjbnezdrnjfwdhjwjka\r\nrfjlbypoalbtjwrpjxzenmeipfg\r\nkhjhrtktcnajrnbefhpavxxfnlx\r\nvwlwumqpfegjgvoezevqsolaqhh\r\npdrvrtzqsoujqfeitkqgtxwckrl\r\nxtepjflcxcrfomhqimhimnzfxzg\r\nwhkfkfvvjwkmwhfgeovwowshyhw\r\nolchgmhiehumivswgtfyhqfagbp\r\ntdudrkttpkryvaiepsijuejqvmq\r\nmuratfqqdbfpefmhjzercortroh\r\nwxkebkzchupxumfizftgqvuwgau\r\n', 'output': ['zshdanicdyldybwgclygzrhkayatwxznmicbpvlupfsoewcleploqngsyolceswtyqbpyasmuadbpcehqva']}, {'input': '1 100\r\nysijllpanprcrrtvokqmmupuptvawhvnekeybdkzqaduotmkfwybqvytkbjfzyqztmxckizheorvkhtyoohbswcmhknyzlgxordu\r\n', 'output': ['g']}, {'input': '2 100\r\ngplwoaggwuxzutpwnmxhotbexntzmitmcvnvmuxknwvcrnsagvdojdgaccfbheqojgcqievijxapvepwqolmnjqsbejtnkaifstp\r\noictcmphxbrylaarcwpruiastazvmfhlcgticvwhpxyiiqokxcjgwlnfykkqdsfmrfaedzchrfzlwdclqjxvidhomhxqnlmuoowg\r\n', 'output': ['rbe']}, {'input': '3 100\r\nonmhsoxoexfwavmamoecptondioxdjsoxfuqxkjviqnjukwqjwfadnohueaxrkreycicgxpmogijgejxsprwiweyvwembluwwqhj\r\nuofldyjyuhzgmkeurawgsrburovdppzjiyddpzxslhyesvmuwlgdjvzjqqcpubfgxliulyvxxloqyhxspoxvhllbrajlommpghlv\r\nvdohhghjlvihrzmwskxfatoodupmnouwyyfarhihxpdnbwrvrysrpxxptdidpqabwbfnxhiziiiqtozqjtnitgepxjxosspsjldo\r\n', 'output': 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nm\r\nyq\r\ncw\r\nov\r\nxk\r\npg\r\noh\r\npl\r\nuo\r\ngf\r\nul\r\n', 'output': ['dvy']}, {'input': '100 3\r\nruy\r\nmye\r\njgp\r\nscn\r\nktq\r\nalx\r\nmvk\r\nlpm\r\nkry\r\norb\r\nmpu\r\nzcv\r\nlge\r\nkft\r\ndzp\r\ntfb\r\nhqz\r\nuur\r\nhry\r\nzjx\r\ncuo\r\nqqc\r\ntih\r\nenj\r\nvnp\r\nbwi\r\nzzh\r\nhkc\r\nwdr\r\nldh\r\nvel\r\nizj\r\nfhb\r\nqrn\r\nqpp\r\nvzs\r\nlhg\r\nkee\r\nlbq\r\nzhy\r\nwcl\r\nyaa\r\nton\r\nfly\r\nkyw\r\nept\r\ngwq\r\ncoe\r\nopd\r\neez\r\nnmx\r\nnjg\r\nwhy\r\nvel\r\nafq\r\nnbq\r\nulx\r\noxs\r\nbbo\r\nyhx\r\nfmz\r\nnrg\r\nnfm\r\njek\r\nbeu\r\ntya\r\nxgs\r\nsgg\r\nnkq\r\nbbv\r\nwkd\r\ntns\r\nfdt\r\neox\r\nobc\r\neab\r\nkkj\r\noub\r\ngji\r\nrht\r\nozv\r\nysk\r\nsbt\r\nflf\r\npbu\r\nlxb\r\npzs\r\nrzh\r\ncea\r\nkmi\r\nuea\r\nncc\r\nzng\r\nvkn\r\njhn\r\njqw\r\nlqc\r\nmbt\r\nlov\r\ngam\r\n', 'output': ['tvdiixs']}]


inp = gets.split(" ")
n = inp[0].to_i
m = inp[1].to_i
l = Array.new(m){[]}
for i in 0..(n-1)
  inp = gets
  for j in 0..(m-1)
    l[j] << inp[j]
  end
end

count = 1
l.each do |arr|
  arr.sort!
  #p arr
  unq = 1
  curr = 0
  while curr < (n - 1)
    if arr[curr] != arr[curr+1]
      unq += 1
	end
	curr += 1
  end
  #puts unq
  count *= unq
end

puts count

One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, 1 ≤ k ≤ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7).

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.

Print the single number — the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7).

NoteIn the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB".

require 'set'

n,m = gets.chomp.split(/ /).map!{|x| x.to_i}
s = []
for i in 0..n-1
	s << gets.chomp
end
ret = 1
for i in 0..m-1
	ws = Set.new
	for j in 0..n-1
		ws.add(s[j][i])
	end
	ret *= ws.length
end
ret %= 1000000007
puts ret

[{'input': '2 3\r\nAAB\r\nBAA\r\n', 'output': ['4\r\n']}, {'input': '4 5\r\nABABA\r\nBCGDG\r\nAAAAA\r\nYABSA\r\n', 'output': ['216\r\n']}, {'input': '1 1\r\nE\r\n', 'output': ['1\r\n']}, {'input': '2 2\r\nNS\r\nPD\r\n', 'output': ['4\r\n']}, {'input': '3 4\r\nPJKD\r\nNFJX\r\nFGFK\r\n', 'output': ['81\r\n']}, {'input': '4 5\r\nSXFMY\r\nATHLM\r\nKDDQW\r\nZWGDS\r\n', 'output': ['1024\r\n']}, {'input': '20 14\r\nJNFKBBBJYZHWQE\r\nLBOKZCPFNKDBJY\r\nXKNWGHQHIOXUPF\r\nDDNRUKVUGHWMXW\r\nMTIZFNAAFEAPHX\r\nIXBQOOHEULZYHU\r\nMRCSREUEOOMUUN\r\nHJTSQWKUFYZDQU\r\nGMCMUZCOPRVE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r\nLBRNWJZNYE\r\nJVMOHTPZYJ\r\nWTARFJLZVV\r\nLVJCWOURVW\r\nLCLQFJYRVV\r\nQVBVGNJRYF\r\nNTZGHOLRYE\r\nMGQKHOUPYJ\r\nRRSSBXPZYJ\r\nRYCRGTLZYJ\r\nJRDEGNKRVW\r\nRZKFGHYRVG\r\nMDJBFNIZYG\r\nMPLWHXIZYE\r\nSRZMHMURVE\r\nMTEBBMRZYJ\r\nJPJIFOLZYM\r\n', 'output': ['919913906\r\n']}, {'input': '40 7\r\nPNTVVER\r\nPAHTQDR\r\nRXMJVAS\r\nVIQNLYC\r\nILPUSVX\r\nYJOXQDJ\r\nSEFODTO\r\nOTJMREL\r\nLIQRZGD\r\nLBJJPOR\r\nRUTYHQO\r\nRIWEPBD\r\nKQUMFIB\r\nISTRRYH\r\nXBTOTGK\r\nRFQODEY\r\nHDSTZTP\r\nYCXFAGL\r\nAREGRFU\r\nLELZUYU\r\nGVABDKH\r\nFJAMMME\r\nACVULXE\r\nJHVPJAS\r\nAAQNMBX\r\nJJGUCXG\r\nOQATILQ\r\nNEOSHJM\r\nHFLWOFM\r\nICYEQHY\r\nFACGLYP\r\nPLLXJEQ\r\nDCHXYPB\r\nAGDDZJJ\r\nLSQRXTN\r\nHDQZXIY\r\nNAHDDWW\r\nQCMXRQN\r\nFDUDSZO\r\nHKBEVTW\r\n', 'output': ['206575993\r\n']}, {'input': '2 2\r\nAA\r\nBB\r\n', 'output': ['4\r\n']}, {'input': '1 10\r\nAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '2 8\r\nAAAAAAAA\r\nBBBBBBBB\r\n', 'output': ['256\r\n']}, {'input': '10 10\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\nCCCCCCCCCC\r\nDDDDDDDDDD\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\nCCCCCCCCCC\r\nDDDDDDDDDD\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\n', 'output': ['1048576\r\n']}, {'input': '1 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Z\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\n', 'output': ['26\r\n']}]


s, cnt, k = gets.chomp, Array.new(26, 0), gets.to_i
s.chars {|c| cnt[c.ord - 97] += 1}
cnt.reject! {|c| c.zero?}
puts k > s.length ? :impossible : k - cnt.length

Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s). Second line of input contains integer k (1 ≤ k ≤ 26).

Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.

NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.

s=gets.chomp
n=gets.to_i
puts s.size<n ? :impossible : [0,n-s.chars.uniq.size].max

[{'input': 'yandex\r\n6\r\n', 'output': ['0\r\n']}, {'input': 'yahoo\r\n5\r\n', 'output': ['1\r\n']}, {'input': 'google\r\n7\r\n', 'output': ['impossible\r\n']}, {'input': 'a\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'z\r\n2\r\n', 'output': ['impossible\r\n']}, {'input': 'fwgfrwgkuwghfiruhewgirueguhergiqrbvgrgf\r\n26\r\n', 'output': ['14\r\n']}, {'input': 'nfevghreuoghrueighoqghbnebvnejbvnbgneluqe\r\n26\r\n', 'output': ['12\r\n']}, {'input': 'a\r\n3\r\n', 'output': ['impossible\r\n']}, {'input': 'smaxpqplaqqbxuqxalqmbmmgubbpspxhawbxsuqhhegpmmpebqmqpbbeplwaepxmsahuepuhuhwxeqmmlgqubuaxehwuwasgxpqmugbmuawuhwqlswllssueglbxepbmwgs\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'cuguccgcugcugucgggggcgcgucgucugcuuuccccuugccg\r\n4\r\n', 'output': ['1\r\n']}, {'input': 'fcfccfcfccfcfcffcffffffcfccfccfcffccccfcffffccfccfcffcfcccccffcfffcccffcfccfffffcccfccffffffccfccccf\r\n20\r\n', 'output': ['18\r\n']}, {'input': 'swmkwaruyv\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'tnbqpsuhkczmejirvyfdolxwga\r\n22\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abb\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'aaaa\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'yandex\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'aaabbbccc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'asdfgh\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'aab\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'mynameissako\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abcdef\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'abcdefg\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'abc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'asdafjsgljdllgjdgkl\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'yaay\r\n3\r\n', 'output': ['1\r\n']}, {'input': 'yaay\r\n4\r\n', 'output': ['2\r\n']}, {'input': 'zzzzzz\r\n2\r\n', 'output': ['1\r\n']}]


n = gets.to_i
a = gets.split(' ').map(&:to_i).sort
res = 0
n.times do |i|
  if a[i] != i+1; res += 1; end;
end
p res

"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

require 'set'
n = gets.to_i
a = Set.new(gets.split(' ').map(&:to_i))
res = 0
n.times do |i|
  unless a.include?(i+1); res += 1; end;
end
p res


n,t=gets.split.map(&:to_i)
built=[]
n.times{
	x,a=gets.split.map(&:to_i)
	built<<[x-a/2,x+a/2]
}
amount=2 #left and right most already possible
built.sort{|a,b|a[0]<=>b[0]}.each_cons(2){|(l,r)|amount+=r[0]-l[1]<=>t}
puts amount+n-1

A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the Оx-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?

The first line of the input data contains numbers n and t (1 ≤ n, t ≤ 1000). Then there follow n lines, each of them contains two space-separated integer numbers: xi ai, where xi — x-coordinate of the centre of the i-th house, and ai — length of its side ( - 1000 ≤ xi ≤ 1000, 1 ≤ ai ≤ 1000).

Output the amount of possible positions of the new house.

NoteIt is possible for the x-coordinate of the new house to have non-integer value.

# Problem A
# by vi002

n, t = gets.split.map { |v| v.to_i }
data = Array.new(n) { gets.split.map { |v| v.to_i } }.sort

result = 2
(0 ... n - 1).each do |pos|
  distance = 2 * (data[pos + 1].first - data[pos].first)
  distance -= data[pos][1] + data[pos + 1][1]
  result += 2 if distance > 2 * t
  result += 1 if distance == 2 * t
end

puts result


class Drift
  attr_reader :x, :y
  attr_accessor :zone
  def initialize(x, y)
    @x = x
    @y = y
    @zone = nil;
  end
end

n = gets.to_i
map = Array.new(n)
for i in 0...n
  input = gets.split
  map[i] = Drift.new(input[0].to_i, input[1].to_i)
end

z = 0
for i in 0...n
  if map[i].zone == nil
    map[i].zone = z
    for j in (i+1)...n
      map[j].zone = z unless map[i].x != map[j].x && map[i].y != map[j].y
    end
    z += 1
  end
end
print z-1

Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

class Drift
  attr_reader :x, :y
  attr_accessor :zone, :adj
  def initialize(x, y)
    @x = x
    @y = y
    @zone = nil
    @adj = Array.new
  end
end

class Map
  attr_accessor :d, :n
  def initialize
    @d = Array.new
    @n = 0
  end
  def add(x, y)
    d << Drift.new(x, y)
    for i in 0...@n
      if d[i].x == d[@n].x || d[i].y == d[@n].y
        d[i].adj << @n
        d[@n].adj << i
      end
    end
    @n += 1
  end
  def at(n)
    @d[n]
  end
  def dfs(n, z)
    d[n].zone = z
    for i in d[n].adj
      dfs(i, z) if d[i].zone == nil
    end
  end
end

n = gets.to_i
map = Map.new
for i in 0...n
  x, y = gets.split(" ").map(&:to_i)
  map.add(x, y)
end
z = 0
for i in 0...map.n
  if map.at(i).zone == nil
    map.dfs(i, z)
    z += 1
  end
end
print z-1


n = gets.chomp.to_i
a = gets.chomp.split(" ").map{|e| e.to_i}

a << 0
a << 0

days = 0
loop do
  bang = false
  for i in 0 .. (n - 2) do
    bang = true if ! ((a[i] > 0 and (a[i + 1] > 0 or a[i + 2] > 0)) or (a[i] == 0 and a[i + 1] > 0))
  end

  break if bang

  days += 1

  a.map!{|e|
    e > 0 ? e -= 1 : e
  }
end

puts days

In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.

The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles. The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103).

Print a single number — the sought number of days.

NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.

n = gets.chomp.to_i
a = gets.chomp.split(" ").map{|e| e.to_i}

days = 0
loop do
  break if a[0] == 0 or a[-1] == 0

  bang = false
  for i in 1 .. (n - 2) do
    bang = true if a[i] == 0 and a[i + 1] == 0
  end
  break if bang

  days += 1

  a.map!{|e|
    e > 0 ? e -= 1 : e
  }
end

puts days


sn, sm = gets.chop.split(/\s+/)

count = sn.to_i
countRelation = sm.to_i

costs = Array.new(0)
scosts = gets.chop.split(/\s+/)
(0..count-1).each { |i|
  costs[i] = scosts[i].to_i
}

relations = Array.new()
(0..count-1).each { |i|
  relations[i] = Array.new()
  (0..count-1).each { |j|
    relations[i][j] = false
  }
}

(0..countRelation-1).each { |i|
  su, sv = gets.chop.split(/\s+/)
  u = su.to_i - 1;
  v = sv.to_i - 1;
  relations[u][v] = true
  relations[v][u] = true
}

solves = Array.new(0)

(0..count-2).each { |row|
  (row..count-2).each { |col|
    if (relations[row][col] == true and relations[row][col+1] == true and relations[row+1][col+1] == true)
      solves[solves.length] =  costs[row] + costs[col] + costs[col+1]
    end
  }
}

if (solves.length > 0)
  puts solves.min
else
  puts "-1"
end

A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.

The first input file line contains integers n and m — the total number of clothing items in the shop and the total number of matching pairs of clothing items (). Next line contains n integers ai (1 ≤ ai ≤ 106) — the prices of the clothing items in rubles. Next m lines each contain a pair of space-separated integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi). Each such pair of numbers means that the ui-th and the vi-th clothing items match each other. It is guaranteed that in each pair ui and vi are distinct and all the unordered pairs (ui, vi) are different.

Print the only number — the least possible sum in rubles that Gerald will have to pay in the shop. If the shop has no three clothing items that would match each other, print "-1" (without the quotes).

NoteIn the first test there only are three pieces of clothing and they all match each other. Thus, there is only one way — to buy the 3 pieces of clothing; in this case he spends 6 roubles.The second test only has three pieces of clothing as well, yet Gerald can't buy them because the first piece of clothing does not match the third one. Thus, there are no three matching pieces of clothing. The answer is -1.In the third example there are 4 pieces of clothing, but Gerald can't buy any 3 of them simultaneously. The answer is -1.

n,m=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
g=Array.new(n){Array.new(n,0)}
m.times{
        p,q=gets.split.map(&:to_i)
        g[p-1][q-1]=g[q-1][p-1]=1
}
ans=9999999999
0.upto(n-1){|i|
        (i+1).upto(n-1){|j|
                if g[i][j]==0 then
                        next
                end
                (j+1).upto(n-1){|k|
                        if g[i][k]==0 || g[j][k]==0 then
                                next
                        end
                        ans=[ans,a[i]+a[j]+a[k]].min
                }
        }
}
puts (ans>=999999999)?-1:ans


tot, min, min_index, input = gets.to_i, 20000, -1, gets.split(' ').map{|n| n.to_i}
input.each_cons(2).to_a.each_with_index { |(a, b), index| min, min_index = (a - b).abs, index if (((a - b).abs) < min) }
min_index = tot - 1 if (min > (input[0] - input[input.length - 1]).abs)
max_index = (min_index == tot - 1) ? 0 : min_index + 1
p (min_index + 1).to_s + ' ' + (max_index + 1).to_s

n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.

The first line contains integer n (2 ≤ n ≤ 100) — amount of soldiers. Then follow the heights of the soldiers in their order in the circle — n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1000). The soldier heights are given in clockwise or counterclockwise direction.

Output two integers — indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.

n = gets.chomp.to_i
s = gets.chomp
sa = s.split(/ /)
sa.map!{|x| x.to_i}

mindiff = (sa[1]-sa[0]).abs
minidx1 = 1
minidx2 = 2

for i in 1..n-1
	j = i+1
	j = 0 if j >= n
	wk = (sa[i]-sa[j]).abs
	if wk < mindiff
		mindiff = wk
		minidx1 = i+1
		minidx2 = j+1
	end
end

puts minidx1.to_s + " " + minidx2.to_s


n,m=gets.chomp.split.collect{|a| a.to_i -1}
puts (n.gcd(m)+1)

Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed.  It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located.You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n × m in size.

The first line contains two integers n and m (2 ≤ n, m ≤ 106).

Print a single number, the maximum possible number of billiard balls that do not pairwise beat each other. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator).

n,m=gets.chomp.split.collect{|a| a.to_i}
puts ((n-1).gcd(m-1)+1)


Berland scientists noticed long ago that the world around them depends on Berland population. Due to persistent research in this area the scientists managed to find out that the Berland chronology starts from the moment when the first two people came to that land (it is considered to have happened in the first year). After one Berland year after the start of the chronology the population had already equaled 13 people (the second year). However, tracing the population number during the following years was an ultimately difficult task, still it was found out that if di — the number of people in Berland in the year of i, then either di = 12di - 2, or di = 13di - 1 - 12di - 2. Of course no one knows how many people are living in Berland at the moment, but now we can tell if there could possibly be a year in which the country population equaled A. That's what we ask you to determine. Also, if possible, you have to find out in which years it could be (from the beginning of Berland chronology). Let's suppose that it could be in the years of a1, a2, ..., ak. Then you have to define how many residents could be in the country during those years apart from the A variant. Look at the examples for further explanation.

The first line contains integer A (1 ≤ A < 10300). It is guaranteed that the number doesn't contain leading zeros.

On the first output line print YES, if there could be a year in which the total population of the country equaled A, otherwise print NO.  If the answer is YES, then you also have to print number k — the number of years in which the population could equal A. On the next line you have to output precisely k space-separated numbers — a1, a2, ..., ak. Those numbers have to be output in the increasing order. On the next line you should output number p — how many variants of the number of people could be in the years of a1, a2, ..., ak, apart from the A variant. On each of the next p lines you have to print one number — the sought number of residents. Those number also have to go in the increasing order.  If any number (or both of them) k or p exceeds 1000, then you have to print 1000 instead of it and only the first 1000 possible answers in the increasing order. The numbers should have no leading zeros.


def calculate_cost(room, wallpapers)
  min_cost = Float::INFINITY

  # Calculate the perimeter of the room
  perimeter = 2 * (room[0] + room[1])

  # Iterate through each wallpaper type
  wallpapers.each do |wallpaper|
    # Calculate the number of rolls required
    rolls = (perimeter.to_f / wallpaper[1]).ceil

    # Calculate the cost of rolls
    cost = rolls * wallpaper[2]

    # Update the minimum cost if necessary
    min_cost = [min_cost, cost].min
  end

  min_cost
end

# Calculate the minimum total cost for all rooms
total_cost = rooms.map { |room| calculate_cost(room, wallpapers) }.sum

# Print the minimum total cost
puts total_cost

Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height).Boris chose m types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type.The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely.After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him.

The first line contains a positive integer n (1≤n≤500) — the number of rooms in Boris's apartment.
Each of the next n lines contains three space-separated positive integers — the length, width and height of the walls in a given room in meters, respectively.
The next line contains a positive integer m (1≤m≤500) — the number of available wallpaper types.
Each of the following m lines contains three space-separated positive integers — the length and width in meters of a given wallpaper and the price of one roll, respectively.
All numbers in the input data do not exceed 500. It is guaranteed that each room can be papered using these types of wallpaper.

Print a single number — the minimum total cost of the rolls.

Note to the sample:
The total length of the walls (the perimeter) of the room is 20 m.
One roll of the first type can be cut into pieces to get three vertical 1 meter wide strips, ergo you need 7 rolls of this type, the price equals 700.
A roll of the second type can be cut into pieces to get five 2 meter wide strips, we need 2 rolls, the price is 640.
One roll of the third type can immediately paper 19 meters out of 20, but we cannot use other types and we have to buy a second roll, the price is 1000.

def min_cost_of_wallpaper(n, rooms, m, wallpapers)
  costs = Array.new(n, Float::INFINITY)
  n.times do |i|
    l, w, h = rooms[i]
    perimeter = 2 * (l + w)
    m.times do |j|
      roll_len, roll_wid, price = wallpapers[j]
      strips_per_roll = roll_len / h
      if strips_per_roll >= 1
        rolls_needed = (perimeter.to_f / (strips_per_roll * roll_wid)).ceil
        cost = rolls_needed * price
        costs[i] = [costs[i], cost].min
      end
    end
  end
  costs.sum.to_s
end

n = gets.to_i
rooms = Array.new(n) { gets.split.map(&:to_i) }
m = gets.to_i
wallpapers = Array.new(m) { gets.split.map(&:to_i) }
puts min_cost_of_wallpaper(n, rooms, m, wallpapers)


small_size, big_indexes = gets.chomp.split.map{|s| s.to_i}
smalls = []
small_size.times do
  array = gets.chomp.split.map{|s| s.to_i}
  array.shift
  sum = r_sum = 0
  left = right = max = -1001
  tmp = 0
  array.size.times do |i|
    sum += array[i]
    r_sum += array[-i - 1]
    left = [sum, left].max
    right = [r_sum, right].max
    max = [max, array[i]].max
    tmp += array[i]
    if tmp < 0
      tmp = 0
    else
      max = [max, tmp].max
    end
  end
  small = {
    :sum => sum,
    :left => left,
    :right => right,
    :max => max,
  }
  smalls << small
end
max = -1001
tmp = 0
gets.chomp.split.map{|s| s.to_i}.each do |i|
  i -= 1
  max = [max, smalls[i][:max]].max
  max = [max, tmp + smalls[i][:left]].max if tmp > 0
  tmp = [0, [smalls[i][:right], tmp + smalls[i][:sum]].max].max
end
puts max

Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.This problem is similar to a standard problem but it has a different format and constraints.In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.But in this problem you are given n small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.Can you help Mostafa solve this problem?

The first line contains two integers n and m, n is the number of the small arrays (1 ≤ n ≤ 50), and m is the number of indexes in the big array (1 ≤ m ≤ 250000). Then follow n lines, the i-th line starts with one integer l which is the size of the i-th array (1 ≤ l ≤ 5000), followed by l integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains m integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to n. The small arrays are numbered from 1 to n in the same order as given in the input. Some of the given small arrays may not be used in big array. Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded.

Print one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty. Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).

small_size, big_indexes = gets.chomp.split.map{|s| s.to_i}
smalls = []
small_size.times do
  array = gets.chomp.split.map{|s| s.to_i}
  array.shift
  sum = r_sum = 0
  left = right = max = -1001
  tmp = 0
  array.size.times do |i|
    sum += array[i]
    r_sum += array[-i - 1]
    left = sum if sum > left
    right = r_sum if r_sum > right
    max = array[i] if array[i] > max
    tmp += array[i]
    if tmp < 0
      tmp = 0
    else
      max = tmp if tmp > max
    end
  end
  small = {
    :sum => sum,
    :left => left,
    :right => right,
    :max => max,
  }
  smalls << small
end
max = -1001
tmp = 0
gets.chomp.split.map{|s| s.to_i}.each do |i|
  i -= 1
  max = smalls[i][:max] if smalls[i][:max] >= max
  max = tmp + smalls[i][:left] if tmp + smalls[i][:left] > max
  tmp += smalls[i][:sum]
  tmp = smalls[i][:right] if smalls[i][:right] > tmp
  tmp = 0 if tmp < 0
end
puts max


def is_jabber_id(string)
  # Check if the string matches the pattern for a Jabber ID
  if string =~ /^[\w]{1,16}@[a-zA-Z0-9_.]{1,16}(\/[\w]{1,16})?$/
    return "YES"
  else
    return "NO"
  end
end

# Read the input
input = gets.chomp

# Check if the input is a correct Jabber ID
result = is_jabber_id(input)

# Print the result
puts result

Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where   <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive.  <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive.  <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent.There are the samples of correct Jabber IDs: [email protected], [email protected]/contest.Your task is to write program which checks if given string is a correct Jabber ID.

The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive.

def is_jabber_id(str)
  # Check if the string matches the pattern for Jabber ID
  pattern = /^([a-zA-Z0-9_]{1,16})@(([a-zA-Z0-9_]{1,16})\.)*([a-zA-Z0-9_]{1,16})(\/([a-zA-Z0-9_]{1,16}))?$/
  if str.match?(pattern)
    return 'YES'
  else
    return 'NO'
  end
end

# Read the input
input = gets.chomp
# Call the function and print the result
puts is_jabber_id(input)

[{'input': ['mike@codeforces.com\r\n'], 'output': ['YES\r\n']}, {'input': ['john.smith@codeforces.ru/contest.icpc/12\r\n'], 'output': ['NO\r\n']}, {'input': ['test@test.ri/abacaba\r\n'], 'output': ['YES\r\n']}, {'input': ['@ops\r\n'], 'output': ['NO\r\n']}, {'input': ['this-is-the-test\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@codeforces.commike@codeforces.com\r\n'], 'output': ['NO\r\n']}, {'input': ['oooop/oooop\r\n'], 'output': ['NO\r\n']}, {'input': ['w@S8/XU.5._R7fHq.@../e.WP!54Ey1L\x7f.9jv\r\n'], 'output': ['NO\r\n']}, {'input': ['lNC9D1L5U@.L!_!CcAOEEx.0z.aiW/S430sbQT\r\n'], 'output': ['NO\r\n']}, {'input': ['@/YTd.K1@lD\r\n'], 'output': ['NO\r\n']}, {'input': ['Fyi!d1l@.OesGopTnRn.81xdSb8q\x7f./MzuI\r\n'], 'output': ['NO\r\n']}, {'input': ['_TlPy65\x7fw/@.Vl@.8k\r\n'], 'output': ['NO\r\n']}, {'input': ['xpS@._s8.e0l\x7fJci/.LdiT\r\n'], 'output': ['NO\r\n']}, {'input': ['lGwo\x7f8.D2@.3\r\n'], 'output': ['NO\r\n']}, {'input': ['Ccz9T5rKZQuEerGo@6l.\r\n'], 'output': ['NO\r\n']}, {'input': ['Y@5nh@8.9P.Bx5AaY.1g.Tc_MK7.g_..0.\r\n'], 'output': ['NO\r\n']}, {'input': ['Q2/6y!SP9s\x7fG@7zIGr.Du_nR8.\r\n'], 'output': ['NO\r\n']}, {'input': ['eWfLL@gW!BEJUxF\x7fh@dghf.d4.FiYp/2.Pr7a/5O6zXdAkikjCEDrb\r\n'], 'output': ['NO\r\n']}, {'input': ['8oI/\x7fa@Q\r\n'], 'output': ['NO\r\n']}, {'input': ['J@Y9Gz550l@\x7fPqVZdQ!u\r\n'], 'output': ['NO\r\n']}, {'input': ['VTE6aTTta@DHe4xeG@6.c2R.J.O7sndWEEW.9j@.l..3Bs\r\n'], 'output': ['NO\r\n']}, {'input': ['aeo2XkK@UX.nQJN!Tg..wGN5YOi68U.oP2Yl3/\r\n'], 'output': ['NO\r\n']}, {'input': ['m13zREg8LbPr@T2.Z9@g.9u.v.A..XNH/1/tloIceXydZf3\r\n'], 'output': ['NO\r\n']}, {'input': ['4@@..f3ZT./oUGZ@\r\n'], 'output': ['NO\r\n']}, {'input': ['G.rVAxwDx@a.PVSe!KtpX4tzs/0yQGzZCPJPJoda\r\n'], 'output': ['NO\r\n']}, {'input': ['SV9T5RR425Sl0b@kzj.XT.PFWc..ho/VE7gjf\r\n'], 'output': ['NO\r\n']}, {'input': ['bgko@1../xwSj_\x7fJ\r\n'], 'output': ['NO\r\n']}, {'input': ['n5ymLC.bE@ukio.im2../.\r\n'], 'output': ['NO\r\n']}, {'input': ['zr.KB_6ZMSwI2GA5@R/4iP1ZKHpszW!YN/\r\n'], 'output': ['NO\r\n']}, {'input': ['@alK@pR\r\n'], 'output': ['NO\r\n']}, {'input': ['al_Y2I4IKp@A_N.\x7fruCw0VL/hRzJtx.S7sp/r!c.n9ffh\r\n'], 'output': ['NO\r\n']}, {'input': ['C1rE26_rTAVzLm@6@X5OGX.ibJ9./kkBEVlcU\r\n'], 'output': ['NO\r\n']}, {'input': ['feGSXP@eyUfr\x7f8.x4Re.JL.6B.r/fX_\r\n'], 'output': ['NO\r\n']}, {'input': ['Ht15T@50eo.E@.\r\n'], 'output': ['NO\r\n']}, {'input': ['k9MITs_Ar.JL2RRs4@VRq.wCuJ.6..amF.fE4.5I.6fJ7gz7\r\n'], 'output': ['NO\r\n']}, {'input': ['Mi\x7fWPE8@fc./IViqq4T4PSUuMdhH\r\n'], 'output': ['NO\r\n']}, {'input': ['pxSCmv!NbMvz2@pTQ.t!.Ntz/QEh_sl\r\n'], 'output': ['NO\r\n']}, {'input': ['s@mH@RO\x7f_/iWD\r\n'], 'output': ['NO\r\n']}, {'input': ['UP51i49wX@pvx@2LWm8w/G4M3J./9L6Szy\r\n'], 'output': ['NO\r\n']}, {'input': ['xC_5Vx8NgF..\x7fln@X1.drRTX..1vx.Xb3of@/PQYPeq@_y8!h_iF\r\n'], 'output': ['NO\r\n']}, {'input': ['qG3@LKp\r\n'], 'output': ['YES\r\n']}, {'input': ['flTq1knyb@2!Mtfss\r\n'], 'output': ['NO\r\n']}, {'input': ['/pqi7WXQPJFM4q1@hxUyUy\x7f/_pWo0n\r\n'], 'output': ['NO\r\n']}, {'input': ['zXme@.Dq.TWBs.fB.M\r\n'], 'output': ['NO\r\n']}, {'input': ['o3EaAnc3K6@h\r\n'], 'output': ['YES\r\n']}, {'input': ['G/AZdVMTzRLV4Ucm@eQ!..pq!..tRTi5.Ejkqa/HGpFYk\r\n'], 'output': ['NO\r\n']}, {'input': ['.c_V@L.1v!AFAEk7glM\x7fq.ag8Sy8@0.Qm/OLKoJpZlac\r\n'], 'output': ['NO\r\n']}, {'input': ['WKxNIM79u\x7f@I.RM\r\n'], 'output': ['NO\r\n']}, {'input': ['POTjlYcxAZsbyZPDh@sPm.z6aVaO.H1wEUhD9YvROQFUk/M_jTHS_6!\r\n'], 'output': ['NO\r\n']}, {'input': ['pbRIiuA@KZ2hVed2fMikA.@ebd.tE2Y\r\n'], 'output': ['NO\r\n']}, {'input': ['OlS_OwxYhH@im.0A7o/juNlxB\r\n'], 'output': ['YES\r\n']}, {'input': ['xkjHHDRBEFwgNP@G9TGStEs2Lu.BJge3EBXw3c9EfE\r\n'], 'output': ['YES\r\n']}, {'input': ['bK@8X7tQO.pXBHJpDewD\r\n'], 'output': ['YES\r\n']}, {'input': ['kKUXy6@0WefbXz39ywP.Q3r7uF\r\n'], 'output': ['YES\r\n']}, {'input': ['SllbRLdZ6@.T.E3x.BE2nIv.5db_.38./zgVGNjpldr\r\n'], 'output': ['NO\r\n']}, {'input': ['4lBJkY8c097oa@ZYmVbtiyyYN.gbj\r\n'], 'output': ['YES\r\n']}, {'input': ['F@JX4.SI1/0EY3XmYatfY\r\n'], 'output': ['YES\r\n']}, {'input': ['oLo01@B77Pu.9R.vtAZG0.HQSunv0J.\r\n'], 'output': ['NO\r\n']}, {'input': ['xLEctap0T@22U9W_fA/7iQeJGFu1lSgMZ\r\n'], 'output': ['YES\r\n']}, {'input': ['WYh@yUWfOQiF.gOK9k8aEa\r\n'], 'output': ['YES\r\n']}, {'input': ['BPxNVANhtEh@Oh_go.\r\n'], 'output': ['NO\r\n']}, {'input': ['mGIY@cHRNC8GlJ/2pcl3LYxpi3PaKGs\r\n'], 'output': ['YES\r\n']}, {'input': ['x6yfn7BGwqWd@.N/UXC\r\n'], 'output': ['NO\r\n']}, {'input': ['cUIr@cP.eGQC2xJXvI1X7\r\n'], 'output': ['YES\r\n']}, {'input': ['MLZ6e1vgZ4hOI@ktWk.Ro.o6C4/i8cnKHT\r\n'], 'output': ['YES\r\n']}, {'input': ['XCJIa@jFaP.Eu28YaoT9Z.Epk.Z/4TBzLWf724zE1r\r\n'], 'output': ['YES\r\n']}, {'input': ['Cz1U1xjg6iW0U@.97HoVA.YG.Qd.eI.DCXxtibi6HG.GV/0sN\r\n'], 'output': ['NO\r\n']}, {'input': ['nrKbWV@P0irxQoRxDsNvG/69WxCwCsfB\r\n'], 'output': ['YES\r\n']}, {'input': ['yI1nRv3FbuhgaI@.Y9vKe.8oc.BLi.6JfYT/tT5d36\r\n'], 'output': ['NO\r\n']}, {'input': ['IGsma3L6YTJRrXS@1g.yR3mC.c.xoCns7Wo1.9C.Oe.5ebkR/_97Ltj3\r\n'], 'output': ['YES\r\n']}, {'input': ['Uu538LDu9Bye@Gu0W0P5a.b9zA9nSaNhzB_TQ2.z/qfi5CZrH\r\n'], 'output': ['YES\r\n']}, {'input': ['bdHl525me@XzR_iO23v.YFXbnHUybbgw.i/WVEhm\r\n'], 'output': ['YES\r\n']}, {'input': ['NQsZ0K@eE8VMB.w2nYtKImB.4nUF\r\n'], 'output': ['YES\r\n']}, {'input': ['186@E.MmBaKLj.WYpt4wPZkzv93\r\n'], 'output': ['YES\r\n']}, {'input': ['hmhYxkGtWYRJFtBU@Drg3L7WKujE.lU61Ljqxv./FJ4X\r\n'], 'output': ['NO\r\n']}, {'input': ['t1RIUz9l3FA15@tOL9.rv.NjhouD.\r\n'], 'output': ['NO\r\n']}, {'input': ['_I4ytjyccT@q.WIc.Cqn\r\n'], 'output': ['YES\r\n']}, {'input': ['LwHHRYq@whOoq.e9b6i0xnoWBl7z.SGJiJe/iUij1x7\r\n'], 'output': ['YES\r\n']}, {'input': ['Yesx@9_KiJq2cBI6.\r\n'], 'output': ['NO\r\n']}, {'input': ['Zu5VFUtSbIw@ner5e\r\n'], 'output': ['YES\r\n']}, {'input': ['test@test.\r\n'], 'output': ['NO\r\n']}, {'input': ['test@.test\r\n'], 'output': ['NO\r\n']}, {'input': ['est.@test\r\n'], 'output': ['NO\r\n']}, {'input': ['test@test.ru/\r\n'], 'output': ['NO\r\n']}, {'input': ['asd@asd@\r\n'], 'output': ['NO\r\n']}, {'input': ['@\r\n'], 'output': ['NO\r\n']}, {'input': ['/\r\n'], 'output': ['NO\r\n']}, {'input': ['.\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@\r\n'], 'output': ['NO\r\n']}, {'input': ['@mike\r\n'], 'output': ['NO\r\n']}, {'input': ['@mail.ru\r\n'], 'output': ['NO\r\n']}, {'input': ['test.me\r\n'], 'output': ['NO\r\n']}, {'input': ['$@ru\r\n'], 'output': ['NO\r\n']}, {'input': ['testme@o.o.o.o.o/ooooo\r\n'], 'output': ['YES\r\n']}, {'input': ['oooop/oooop\r\n'], 'output': ['NO\r\n']}, {'input': ['mail.ru/a\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@mail.ru/aaa\r\n'], 'output': ['YES\r\n']}, {'input': ['mike@mike.mike\r\n'], 'output': ['YES\r\n']}]


def polygon_area(vertices)
  n = vertices.length
  area = 0

  (0...n).each do |i|
    x1, y1 = vertices[i]
    x2, y2 = vertices[(i + 1) % n]
    area += (x1 * y2 - x2 * y1)
  end

  area.abs / 2.0
end

def expected_area(n, vertices)
  polygon = []
  vertices.each do |vertex|
    polygon << vertex.split.map(&:to_i)
  end

  total_points = 0
  total_area = 0

  polygon.each_with_index do |vertex, i|
    x1, y1 = vertex
    x2, y2 = polygon[(i + 1) % n]

    min_x = [x1, x2].min
    max_x = [x1, x2].max
    min_y = [y1, y2].min
    max_y = [y1, y2].max

    total_points += (max_x - min_x + 1) * (max_y - min_y + 1)
    total_area += polygon_area([vertex, polygon[(i + 1) % n]])
  end

  total_area / total_points
end

input = gets.chomp.split("\n")
n = input[0].to_i
vertices = input[1..-1]

puts expected_area(n, vertices)

Ksusha is a vigorous mathematician. She is keen on absolutely incredible mathematical riddles. Today Ksusha came across a convex polygon of non-zero area. She is now wondering: if she chooses a pair of distinct points uniformly among all integer points (points with integer coordinates) inside or on the border of the polygon and then draws a square with two opposite vertices lying in the chosen points, what will the expectation of this square's area be?A pair of distinct points is chosen uniformly among all pairs of distinct points, located inside or on the border of the polygon. Pairs of points p,q (p≠q) and q,p are considered the same.Help Ksusha! Count the required expectation.

The first line contains integer n (3≤n≤10^5) — the number of vertices of Ksusha's convex polygon. Next n lines contain the coordinates of the polygon vertices in clockwise or counterclockwise order. The i-th line contains integers xi,yi (|xi|,|yi|≤10^6) — the coordinates of the vertex that goes i-th in that order.

Print a single real number — the required expected area.
The answer will be considered correct if its absolute and relative error doesn't exceed 10^-6.

def polygon_area(vertices)
  n = vertices.length
  sum = 0
  for i in 0...n
    j = (i+1)%n
    sum += vertices[i][0]*vertices[j][1] - vertices[j][0]*vertices[i][1]
  end
  return sum.abs/2.0
end

def sum_squares(n)
  return n*(n+1)*(2*n+1)/6
end

def solve(n, vertices)
  vertices.sort_by! {|x, y| [x, y]}
  x_values = vertices.map {|x, y| x}.uniq
  y_values = Array.new(x_values.length, 0)
  x_values.each_with_index do |x, i|
    y_values[i] = vertices.select {|vx, vy| vx == x}.map {|vx, vy| vy}.sort
  end
  total_sum = 0
  total_count = 0
  x_values.each_with_index do |x, i|
    count = y_values[i].length
    sum = y_values[i].sum
    total_sum += sum_squares(x)*(2*count-sum) + sum_squares(n-x-1)*(2*count-sum)
    total_count += count*count
  end
  return total_sum/total_count.to_f
end

lines = gets.chomp.split('\n').map {|line| line.split.map(&:to_i)}
n = lines.shift[0]
vertices = lines
puts '%.10f' % solve(n, vertices)


def find_new_representation(n, r1, r2, roads)
  new_representation = []
  old_representation = roads.split.map(&:to_i)

  # Find the path from the old capital to the new capital
  path = [r2]
  while path.last != r1
    path << old_representation[path.last - 2]
  end

  # Reverse the path to get the new representation
  path.reverse.each_cons(2) do |a, b|
    new_representation << b
  end

  new_representation.join(' ')
end

input = gets.chomp.split
n = input[0].to_i
r1 = input[1].to_i
r2 = input[2].to_i
roads = gets.chomp

output = find_new_representation(n, r1, r2, roads)
puts output

There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i.Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above.

The first line contains three space-separated integers n, r1, r2 (2≤n≤5·10^4,1≤r1≠r2≤n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly.
The following line contains n-1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes.

Output n-1 numbers — new representation of the road map in the same format.

n, r1, r2 = gets.split.map(&:to_i)
graph = Array.new(n+1) {[]}
old_map = gets.split.map(&:to_i)

old_map.insert(r1-1, 0)

(1..n).each do |i|
  graph[i] << old_map[i-1]
  graph[old_map[i-1]] << i if old_map[i-1] != 0
end

visited = Array.new(n+1, false)
new_map = Array.new(n+1, 0)

queue = [r2]
visited[r2] = true

while !queue.empty?
  current_city = queue.shift
  graph[current_city].each do |neighbour|
    unless visited[neighbour]
      new_map[neighbour] = current_city
      visited[neighbour] = true
      queue << neighbour
    end
  end
end

(1..n).each { |i| print "#{new_map[i]} " if i != r2 }


def minimal_swaps(input)
  n = input[0].to_i
  positions = input[1].strip.chars

  # Count the number of hamsters and tigers
  hamster_count = positions.count('H')
  tiger_count = positions.count('T')

  # If all hamsters or all tigers are already together, no swaps needed
  return '0' if hamster_count == n || tiger_count == n

  # Find the maximum number of hamsters or tigers together
  max_count = [hamster_count, tiger_count].max

  # Find the minimum number of swaps needed to achieve the goal
  min_swaps = n

  # Iterate through each possible starting position
  (0..n-1).each do |start|
    # Count the number of swaps needed for this starting position
    swaps = 0
    (0..max_count-1).each do |i|
      current = positions[(start + i) % n]
      swaps += 1 if (current == 'H' && i >= tiger_count) || (current == 'T' && i >= hamster_count)
    end
    min_swaps = [min_swaps, swaps].min
  end

  min_swaps.to_s
end

input = gets.chomp.split('\n')
output = minimal_swaps(input)
puts output

Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him.

The first line contains number n (2≤n≤1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one.

Print the single number which is the minimal number of swaps that let the trainer to achieve his goal.

In the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then — the tiger in position 9 with the hamster in position 7.

def min_swaps
  n = gets.to_i
  s = gets.chomp.split('')
  tigers = s.count('T')
  hamsters = s.count('H')
  min_swaps = tigers
  s = s * 2
  (0...n).each do |i|
    tigers_in_range = s[i...(i+hamsters)].count('T')
    min_swaps = [min_swaps, tigers_in_range].min
  end
  puts min_swaps
end

min_swaps

[{'input': ['3\r\nHTH\r\n'], 'output': ['0\r\n']}, {'input': ['9\r\nHTHTHTHHT\r\n'], 'output': ['2\r\n']}, {'input': ['2\r\nTH\r\n'], 'output': ['0\r\n']}, {'input': ['4\r\nHTTH\r\n'], 'output': ['0\r\n']}, {'input': ['4\r\nHTHT\r\n'], 'output': ['1\r\n']}, {'input': ['7\r\nTTTHTTT\r\n'], 'output': ['0\r\n']}, {'input': ['8\r\nHHTHHTHH\r\n'], 'output': ['1\r\n']}, {'input': ['13\r\nHTTTHHHTTTTHH\r\n'], 'output': ['3\r\n']}, {'input': ['20\r\nTTHTHTHHTHTTHHTTTHHH\r\n'], 'output': ['4\r\n']}, {'input': ['35\r\nTTTTTTHTTHTTTTTHTTTTTTTTTTTHTHTTTTT\r\n'], 'output': ['3\r\n']}, {'input': ['120\r\nTTTTTTTHTHTHTTTTTHTHTTTTHTTTTTTTTTTTTTTTTTTTTHTTHTTTTHTTHTTTTTTTTTTTTTTTHTTTTTTHTHTTHTTTTTTHTTTTTTTTTHTTHTTTTHTTTHTTTTTH\r\n'], 'output': ['14\r\n']}, {'input': ['19\r\nHHHHHHHHHHHHHTTTHHH\r\n'], 'output': ['0\r\n']}, {'input': ['87\r\nHTHHTTHHHHTHHHHHTTTHHTHHHHTTTTHHHTTHHTHTHTHHTTHTHHTHTHTTHHHTTTTTHTTHHHHHHTHHTHHTHTTHTHH\r\n'], 'output': ['17\r\n']}, {'input': ['178\r\nTHHHTHTTTHTTHTTHHHHHTTTHTTHHTHTTTHTHTTTTTHHHTHTHHHTHHHTTTTTTTTHHHHTTHHTHHHHTHTTTHHHHHHTHHTHTTHTHTTTTTTTTTHHTTHHTHTTHHTHHHHHTTHHTTHHTTHHHTTHHTTTTHTHHHTHTTHTHTTTHHHHTHHTHHHTHTTTTTT\r\n'], 'output': ['40\r\n']}]


n, m = gets.split.map(&:to_i)
a = []
m.times do |t|
	s, c = gets.split
	s = s.to_i(2)
	c = c.to_i
	if t.zero? then
		a = [*0..n-1].combination(c).to_a.map{|i| i.map{|j| 1 << j}.inject{|x, y| x ^ y} || 0}
	else
		a.reject!{|i| (i ^ s).to_s(2).count('1') != c}
	end
end
p a.size

__END__
: || 0

Vasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.

The first input line contains two integers n and m (6 ≤ n ≤ 35, 1 ≤ m ≤ 10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow m lines, each containing space-separated si and ci which correspondingly indicate Vasya’s attempt (a line containing n numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively).

Print the single number which indicates how many possible code variants that do not contradict the m system responses are left.

$b = 4096.times.to_a.map{|i| i.to_s(2).count('1')}

def bits(x)
	$b[x & 4095] + $b[(x >> 12) & 4095] + $b[x >> 24]
end

n, m = gets.split.map(&:to_i)
a = []
m.times do |t|
	s, c = gets.split
	s = s.to_i(2)
	c = c.to_i
	if t.zero? then
		[*0..n-1].combination(c).each do |i|
			a << s
			i.each{|j| a[-1] ^= 1 << j}
		end
	else
		a.reject!{|i| bits(i ^ s) != c}
	end
end
p a.size

__END__
: || 0


def count_square_triangles(n, m, field)
  count = 0

  for i in 0..n-1
    for j in 0..m-1
      if field[i][j] == '*'
        for k in i+1..n-1
          for l in j+1..m-1
            if field[k][l] == '*' && field[i][l] == '*' && field[k][j] == '*'
              count += 1
            end
          end
        end
      end
    end
  end

  return count
end

input = gets.chomp.split('\n')
n, m = input[0].split.map(&:to_i)
field = input[1..-1]

result = count_square_triangles(n, m, field)
puts result

You are given a n×m field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle).

The first line contains two positive integer numbers n and m (1≤n,m≤1000). The following n lines consist of m characters each, describing the field. Only '.' and '*' are allowed.

Output a single number — total number of square triangles in the field. 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).

n, m = gets.split.map(&:to_i)
field = Array.new(n){Array.new(m, 0)}
rows = Array.new(n, 0)
cols = Array.new(m, 0)

n.times do |i|
  line = gets.chomp.chars
  m.times do |j|
    if line[j] == '*'
      field[i][j] = 1
      rows[i] += 1
      cols[j] += 1
    end
  end
end

count = 0
n.times do |i|
  m.times do |j|
    if field[i][j] == 1
      count += (rows[i] - 1) * (cols[j] - 1)
    end
  end
end

puts count


def cut_area(h, w)
  max_area = 0
  cut_height = 0
  cut_width = 0

  # Iterate through all possible cut heights
  (0..Math.log2(h).to_i).each do |i|
    height = 2**i
    # Calculate the corresponding cut width based on height-to-width ratio
    width = (height * (1.25)).to_i
    # Check if the width is within the limits and adjust if necessary
    width = [width, w].min
    # Calculate the area of the cut
    area = height * width

    # Update the maximum area and cut dimensions if the current area is larger
    if area > max_area
      max_area = area
      cut_height = height
      cut_width = width
    end
  end

  [cut_height, cut_width]
end

# Read input from standard input
input = gets.chomp.split.map(&:to_i)
h = input[0]
w = input[1]

# Call the cut_area function and print the result
result = cut_area(h, w)
puts result.join(' ')

One popular blog site edits the uploaded photos like this. It cuts a rectangular area out of them so that the ratio of height to width (i.e. the height/width quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 (2^x for some integer x). If those rules don't indicate the size of the cut are clearly, then the way with which the cut part possesses the largest area is chosen. Of course, both sides of the cut area should be integer. If there are several answers to this problem, you should choose the answer with the maximal height.

The first line contains a pair of integers h and w (1≤h,w≤10^9) which are the height and width of the uploaded photo in pixels.

Print two integers which are the height and width of the cut area.

def find_cut_area(h, w)
    max_height = 0
    max_width = 0
    max_area = 0

    (0..30).each do |i|
        size = 2 ** i
        break if size > h

        width = [w, (size / 0.8).floor].min
        next if width < size * 0.8 || width > size * 1.25

        area = size * width
        if area > max_area
            max_area = area
            max_height = size
            max_width = width
        end
    end

    (0..30).each do |i|
        size = 2 ** i
        break if size > w

        height = [h, (size / 0.8).floor].min
        next if height < size * 0.8 || height > size * 1.25

        area = size * height
        if area > max_area || (area == max_area && height > max_height)
            max_area = area
            max_height = height
            max_width = size
        end
    end

    return max_height, max_width
end

h, w = gets.split.map(&:to_i)
height, width = find_cut_area(h, w)
puts "#{height} #{width}"