You are on page 1of 138

Archives of the Sphere Online Judge

partial problemset

Editors:
Buda IM
Minh^^
avinash
Ziad Ouf
Felix Halim
Phng Tm
T-7
islam
(Tjandra Satria
Gunawan)(???)
Andrs Meja-Posada
Ricardo Oliveira
[UFPR]
Ramy
Vu+o+ng Trung Hie^u
Nghia
Thanh-Vy Hua
bashrc is back
Duc

Nikola P Borisov
Venezuelan Programming
League
Damon Doucet
Dulguun Batmunkh
Aufar Gilbran
Mir Wasi Ahmed
Trn Ha?i ng
Zhang Zhiyong Melvin
Mateus Dantas [ UFCG ]
Ahmad Zaky
Infinity
Atef
David Moran
Mostafa mahmoud
sieunhan
ahmed.abdrabo
Alex, DE & Friends

Last updated: 2013-06-29 16:32:45

Preface
This electronic material contains a set of algorithmic problems, forming the archives of the Sphere
Online Judge (http://www.spoj.com/), partial problemset. The document can be accessed at the
following URLs:
in PostScript format: http://www.spoj.com/problems/partial.ps
in Portable Document Format: http://www.spoj.com/problems/partial.pdf
These resources are constantly updated to synchronise with the ever-changing hypertext version of the
problems, and to include newly added problems. If you have obtained this document from another
source, it is strongly recommended that you should download the current version from one of the
aforementioned URLs.

Enjoy problem-solving at the Sphere Online Judge!

Disclaimer from the Editors. Despite our best efforts, it is possible that this document contains errors or that some of the
content differs slightly from its original hypertext form. We take no responsibility for any such faults and their
consequences. We neither authorise nor approve use of this material for any purpose other than facilitating problem solving
at the Sphere Online Judge site; nor do we guarantee its fitness for any purpose whatsoever.
The layout of the problems in this document is the copyright of the Editors named on the cover (as determined by the
appropriate footers in the problem description). The content is the copyright of the respective Editor unless the copyright
holder is otherwise stated in the resource section. The document as a whole is not protected by copyright, and fragments
of it are to be regarded independently. No responsibility is taken by the Editors if use or redistribution of this document
violates either their or third party copyright laws. When referring to or citing the whole or a fragment of this document,
please state clearly the aforementioned URLs at which the document is to be found, as well as the resources from which the
problems you are referring to originally came.
Remarks concerning this document should be sent to the following e-mail address: contact@spoj.com.

Table of Contents
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.

Problem PT07I (1486. The Ants in a Tree)


Problem REDUCT (3077. Copier Reduction)
Problem CONDIG (3079. Consecutive Digits)
Problem PAINTER (3080. Painter)
Problem PRIMESUB (3082. Primary X-Subfactor Series)
Problem PACK1 (3088. Packing)
Problem SYMORD (3095. Symmetric Order)
Problem BOOKSH (3096. Overflowing Bookshelf)
Problem FLOWLAY (3097. Flow Layout)
Problem GRAFT (3098. Tree Grafting)
Problem UPTIME (3132. Server Relocation)
Problem LINEARPA (3185. Linear Pachinko)
Problem FRSEARCH (3186. Frugal Search)
Problem GOGOGORE (3187. Go Go Gorelians)
Problem MST (3188. Minimum Spanning Tree)
Problem CONNECT2 (3448. Connect)
Problem SUMSQ (3449. Sum of Squares)
Problem FASTW (3450. Fast Width )
Problem BOIFAC (3610. BOI 97 - Factorial)
Problem BOI97TE (3677. BOI 97 - Task Execution)
Problem BOI97SN (4108. BOI 97 - Street Network)
Problem BRHQUADR (5167. Quadratics)
Problem SBRICKS (5201. Stacks of Bricks)
Problem SBRICKS2 (5202. Stacks of Bricks 2)
Problem BRHAR (5535. Accelerated Reading)
Problem BRHPHYS (5536. Physics Grade)
Problem BRHWURD (5537. Words)
Problem BRHMAIL (5538. Chain Mail)
Problem BRHMUSIC (5539. Musical Frequencies)
Problem SARRAY (6409. Suffix Array)
Problem CUTBOARD (6610. Ct ba?ng)
Problem MBUS (6671. Xe but)
Problem INSUL (6952. Cch nhie^.t)
Problem NKMATMA (6987. Mt m)
Problem SCRAMBLE (7670. SCRAMBLE1)
Problem DUGOVI (8195. Borrowing money)
Problem INSULENG (8559. Insulation)
Problem SAMDRAW (8595. Artistic Samhita)
Problem BGEEK (8601. Brainfuck Geek!!! (Bonus Question))
Problem SALESMAN (8760. Salesman)
Problem KAMION (9027. KAMION)
Problem NTKM (9028. DIEULINH)
Problem ANTJOUR (9548. The Journey of the Ant)
Problem MMO85 (9601. MMO85)
Problem CPP (9740. Closest Pair Problem)

46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.

Problem MRPATH (10178. Most Reliable Path)


Problem TRAKA (10337. TRAKA)
Problem PALINCOD (11131. Palindrome or not)
Problem REDOKS (11400. Redoks)
Problem RPL_T1 (11733. Find our next planet!)
Problem RPL_T2 (11734. Take & Run)
Problem OPC2408B (12054. Cipher)
Problem IOI11GRD (12189. Tropical Garden )
Problem T8GELO (12263. GELO)
Problem T8MOBIL (12264. Mobil Ajaib)
Problem T8PIANO (12265. Piano)
Problem T8STPD (12266. String Periodik)
Problem T8SHADOW (12267. Shadow)
Problem WARAKOM (12601. PiggybankRI)
Problem INFORMAC (12879. INFORMACIJE)
Problem RIOI_3_3 (12942. Spy Office)
Problem RIOI_3_4 (12947. Cheaters)
Problem NOINCDEC (13025. Making the Grade)
Problem V_AYP1_A (13561. Kart)
Problem V_AYP1_B (13562. Knight Circuit)
Problem V_AYP1_C (13563. Iridium)
Problem V_AYP1_D (13564. Time)
Problem V_AYP1_E (13565. Secret)
Problem V_AYP1_F (13566. A little help for Yon)
Problem V_AYP2_A (13567. Very Triangular)
Problem V_AYP2_B (13568. Sub-matrix Average)
Problem V_AYP2_C (13569. Magic)
Problem V_AYP2_D (13570. Military)
Problem V_AYP2_E (13571. Lazy Decision)
Problem V_AYP2_F (13572. Mirrors)
Problem GMLIFE (13737. Game of Life)
Problem DISCRT (13866. Discrete Roots)
Problem HICHEEL1 (14057. idet teg ?nts?gt)
Problem HICHEEL2 (14059. idet gurvalin)
Problem HICHEEL3 (14060. idet ooir)
Problem HICHEEL4 (14061. idet toonuud)
Problem HICHEEL5 (14062. idet ?segn??d)
Problem MFNNM (14440. Davy Joness Organ)
Problem SHUNT (14460. Scavenger Hunt)
Problem TREAP (14702. Yet another range difference query!)
Problem RACEHUB (14756. Rice Hub - IOI)
Problem SKIPLIST (14759. Yet another strings problem !!)
Problem SCRIVIOI (14859. Scrivener - IOI 2012)
Problem TOKI1493 (15228. Swap (Original))

SPOJ Problem Set (partial)

1486. The Ants in a Tree


Problem code: PT07I
In Ambers childhood, he usually liked to observe some little things for tickling his little curiosity. He
often found it interesting to climb up a tree, sit on a branch and watch the movement of a group of
lovely ants on the branches of the tree.
Amber finds there are n ant holes and m ants in the tree now. Because of his careful observation, he
knows all ants behaviors, the i-th ant wanna travel from one hole s i to another hole t i at the speed v i .
During the ants travel, if two ants arrive at the same position (meet or chase), they will touch their
feelers for exchanging the information about food or danger. Even at the moment that the travel starts
or finishes, the ant can also touch others feelers. But after the travel finishes, the ant will enter into the
hole and never touch feelers. What amber wonders is to count the times of touchings during the whole
traveling process.
Consider there are n - 1 branches in the tree. Each branch connects the adjacent ant holes and has a
particular length. Assume there is always a path that consists of branches between any two ant holes.
Assume that no two ants have the same speeds and the touching doesnt cost any time.

Input
Input consists of multiple testcases. The first line contains one integer t (1 <= t <= 20). For each
testcase, the input format is following.
The first line contains one integer n (1 <= n <= 10 6 ). In next n - 1 line, the i-th line contains an integer
triple (u i , v i , w i ) (1 <= u i , v i <= n, u i != v i , 1 <= w i <= 10 3 ). The triple means there is a branch
with the length w i between node u i and node v i .
The next line contains one integer m (1 <= m <= 10 3 ). In next m line, the i-th line contains an integer
triple (s i , t i , v i ) (1 <= s i , t i <= n, 1 <= v i <= 10 6 ). The triple means that the i-th ants travel is from
s i to t i at the speed v i .

Output
For each testcase, print a line that consists of an integer that means the times of the feeler touchings.

Example
Input:
1
3
1 2 1
2 3 1
3
1 3 1
3 1 1

1 2 3
Output:
2

Note: Its a partly correct problem, so score is set for each case. When you pass all cases, youll
get 300 points
Added by: Thanh-Vy Hua
Date:
2007-04-07
Time limit: 8s-15s
Source limit:50000B
Languages: All
Resource: Co-author Amber

SPOJ Problem Set ()

3077. Copier Reduction


Problem code: REDUCT
What do you do if you need to copy a 560x400mm image onto a standard sheet of US letter-size paper
(which is about 216x280mm), while keeping the image as large as possible? You can rotate the image
90 degrees (so that it is in landscape mode), then reduce it to 50% of its original size so that it is
200x280mm.Then it will fit on the paper without overlapping any edges. Your job is to solve this
problem in general.

Input
The input consists of one or more test cases, each of which is a single line containing four positive
integers A, B, C, and D, separated by a space, representing an AxBmm image and a CxDmm piece of
paper. All inputs will be less than one thousand. Following the test cases is a line containing four zeros
that signals the end of the input.

Output
For each test case, if the image fits on the sheet of paper without changing its size (but rotating it if
necessary), then the output is 100%. If the image must be reduced in order to fit, the output is the
largest integer percentage of its original size that will fit (rotating it if necessary). Output the
percentage exactly as shown in the examples below. You can assume that no image will need to be
reduced to less than 1% of its original size, so the answer will always be an integer percentage
between 1% and 100%, inclusive.

Example
Input:
560 400 218 280
10 25 88 10
8 13 5 1
9 13 10 6
199 333 40 2
75 90 218 280
999 99 1 10
0 0 0 0
Output:
50%
100%
12%
66%
1%
100%
1%

Added by: Nikola P Borisov


Date:
2008-10-01
Time limit: 5s
Source limit:50000B
Languages: All
Resource: ICPC North America Mid-Central Regional Contest 2005

SPOJ Problem Set ()

3079. Consecutive Digits


Problem code: CONDIG
As a recruiting ploy, Google once posted billboards in Harvard Square and in the Silicon Valley area
just stating "{first 10-digit prime found in consecutive digits of e}.com". In other words, find that
10-digit sequence and then connect to the web site -- and find out that Google is trying to hire people
who can solve a particular kind of problem.
Not to be outdone, Gaggle (a loosy-goosy fuzzy logic search firm), has devised its own recruiting
problem. Consider the base 7 expansion of a rational number. For example, the first few digits of the
base 7 expansion of 1/5 10 = 0.12541... 7 , 33/4 10 = 11.15151... 7 , and 6/49 10 = 0.06000... 7 , From this
expansion, find the digits in a particular range of positions to the right of the "decimal" point.

Input
The input file begins with a line containing a single integer specifying the number of problem sets in
the file. Each problem set is specified by four base 10 numbers on a single line, n d b e, where n and d
are the numerator and denominator of the rational number and 0 <= n <= 5,000 and 1 <= d <= 5,000. b
and e are the beginning and ending positions for the desired range of digits, with 0 <= b,e <= 250 and
0 <= (e-b) <= 20. Note that 0 is the position immediately to the right of the decimal point.

Output
Each problem set will be numbered (beginning at one) and will generate a single line: Problem set k: n
/ d, base 7 digits b through e: result where k is replaced by the problem set number, result is your
computed result, and the other values are the corresponding input values.

Example
Input:
4
1 5 0 0
6 49 1 3
33 4 2 7
511 977 122 126
Output:
Problem
Problem
Problem
Problem

set
set
set
set

1:
2:
3:
4:

1 / 5, base 7 digits 0 through 0: 1


6 / 49, base 7 digits 1 through 3: 600
33 / 4, base 7 digits 2 through 7: 151515
511 / 977, base 7 digits 122 through 126: 12425

Added by: Nikola P Borisov


Date:
2008-10-01
Time limit: 5s
Source limit:50000B
Languages: All
Resource: ICPC North America Mid-Central Regional Contest 2005

SPOJ Problem Set (partial)

3080. Painter
Problem code: PAINTER
The local toy store sells small fingerpainting kits with between three and twelve 50ml bottles of paint,
each a different color. The paints are bright and fun to work with, and have the useful property that if
you mix X ml each of any three different colors, you get X ml of gray. (The paints are thick and "airy",
almost like cake frosting, and when you mix them together the volume doesnt increase, the paint just
gets more dense.) None of the individual colors are gray; the only way to get gray is by mixing exactly
three distinct colors, but it doesnt matter which three. Your friend Emily is an elementary school
teacher and every Friday she does a fingerpainting project with her class. Given the number of
different colors needed, the amount of each color, and the amount of gray, your job is to calculate the
number of kits needed for her class.

Input
The input consists of one or more test cases, followed by a line containing only zero that signals the
end of the input. Each test case consists of a single line of five or more integers, which are separated
by a space. The first integer N is the number of different colors (3 <= N <= 12). Following that are N
different nonnegative integers, each at most 1,000, that specify the amount of each color needed. Last
is a nonnegative integer G <= 1,000 that specifies the amount of gray needed. All quantities are in ml.

Output
For each test case, output the smallest number of fingerpainting kits sufficient to provide the required
amounts of all the colors and gray. Note that all grays are considered equal, so in order to find the
minimum number of kits for a test case you may need to make grays using different combinations of
three distinct colors.

Example
Input:
3 40 95
7 25 60
4 90 95
4 90 95
5 0 0 0
0

21 0
400 250 0 60 0 500
75 95 10
75 95 11
0 0 333

Output:
2
8
2
3
4

Added by: Nikola P Borisov


Date:
2008-10-01
Time limit: 1s
Source limit:50000B
Languages: All
Resource: ICPC North America Mid-Central Regional Contest 2005

SPOJ Problem Set (partial)

3082. Primary X-Subfactor Series


Problem code: PRIMESUB
Let n be any positive integer. A factor of n is any number that divides evenly into n, without leaving a
remainder. For example, 13 is a factor of 52, since 52/13 = 4. A subsequence of n is a number without
a leading zero that can be obtained from n by discarding one or more of its digits. For example, 2, 13,
801, 882, and 1324 are subsequences of 8013824, but 214 is not (you cant rearrange digits), 8334 is
not (you cant have more occurrences of a digit than appear in the original number), 8013824 is not
(you must discard at least one digit), and 01 is not (you cant have a leading zero). A subfactor of n is
an integer greater than 1 that is both a factor and a subsequence of n. 8013824 has subfactors 8, 13,
and 14. Some numbers do not have a subfactor; for example, 6341 is not divisible by 6, 3, 4, 63, 64,
61, 34, 31, 41, 634, 631, 641, or 341.
An x-subfactor series of n is a decreasing series of integers n 1 , ..., n k , in which (1) n = n 1 , (2) k >= 1,
(3) for all 1 <= i < k, n i+1 is obtained from n i by first discarding the digits of a subfactor of n i , and
then discarding leading zeros, if any, and (4) n k has no subfactor. The term "x-subfactor" is meant to
suggest that a subfactor gets xed, or discarded, as you go from one number to the next. For example,
2004 has two distinct x-subfactor series, the second of which can be obtained in two distinct ways. The
highlighted digits show the subfactor that was removed to produce the next number in the series.
2004 4
2004 200 0
2004 200 0
The primary x-subfactor series has maximal length (the largest k possible, using the notation above). If
there are two or more maximal-length series, then the one with the smallest second number is primary;
if all maximal-length series have the same first and second numbers, then the one with the smallest
third number is primary; and so on. Every positive integer has a unique primary x-subfactor series,
although it may be possible to obtain it in more than one way, as is the case with 2004.

Input
The input consists of one or more positive integers, each less than one billion, without leading zeroes,
and on a line by itself. Following is a line containing only "0" that signals the end of the input.

Output
For each positive integer, output its primary x-subfactor series using the exact format shown in the
examples below.

Example
Input:
123456789
7
2004
6341
8013824
0

Output:
123456789 12345678 1245678 124568 12456 1245 124 12 1
7
2004 200 0
6341
8013824 13824 1324 132 12 1

Added by: Nikola P Borisov


Date:
2008-10-01
Time limit: 5s
Source limit:50000B
Languages: All
Resource: ICPC North America Mid-Central Regional Contest 2005

SPOJ Problem Set (partial)

3088. Packing
Problem code: PACK1
In the future the delivery services will be fully automated. A robot will come to your home to pick the
boxes and leaves them in the central processing office where boxes for the same address are packed
together. There is a machine that can pack two boxes into a one new box containing the privious two.
If we want N boxes delivered to a certain city then this machine with N-1 operation will be able to
consolidate them into single box.
Each box has its size and a price for packing it equal to this size. The size of the box resulting from the
machine packing two boxes together is simply equal to the sum of the two boxes that are packed
together. Your goal is to find out the minimum price for packing N boxes into a single one using the
packing machine.

Input
On the first line there will be one number N (1 < N < 5000001) - the number of boxes. N lines follow
each line with one number representing the size of N-th box. The size will be less then 1 000 000. In
50% of the test cases the size will be less then 4000.

Output
Your program should output a single integer - the minum price that have to be paid for packing the N
boxes into a single one using N-1 operations of the machine.

Example
Input:
4
1
1
1
1

Output:
8

Added by: Nikola P Borisov


Date:
2008-10-01
Time limit: 1s-25s
Source limit:50000B
Languages: All
Resource: Bulgarian National Olympiad Selection Contest 4 2005

SPOJ Problem Set (partial)

3095. Symmetric Order


Problem code: SYMORD
In your job at Albatross Circus Management (yes, its run by a bunch of clowns), you have just
finished writing a program whose output is a list of names in nondescending order by length (so that
each name is at least as long as the one preceding it). However, your boss does not like the way the
output looks, and instead wants the output to appear more symmetric, with the shorter strings at the top
and bottom and the longer strings in the middle. His rule is that each pair of names belongs on
opposite ends of the list, and the first name in the pair is always in the top part of the list. In the first
example set below, Bo and Pat are the first pair, Jean and Kevin the second pair, etc.

Input
The input consists of one or more sets of strings, followed by a final line containing only the value 0.
Each set starts with a line containing an integer, n, which is the number of strings in the set, followed
by n strings, one per line, sorted in nondescending order by length. None of the strings contain spaces.
There is at least one and no more than 15 strings per set. Each string is at most 25 characters long.

Output
For each input set print "SET n" on a line, where n starts at 1, followed by the output set as shown in
the sample output.

Example
Input:
7
Bo
Pat
Jean
Kevin
Claude
William
Marybeth
6
Jim
Ben
Zoe
Joey
Frederick
Annabelle
5
John
Bill
Fran
Stan
Cece
0
Output:

SET 1
Bo
Jean
Claude
Marybeth
William
Kevin
Pat
SET 2
Jim
Zoe
Frederick
Annabelle
Joey
Ben
SET 3
John
Fran
Cece
Stan
Bill

Added by: Nikola P Borisov


Date:
2008-10-01
Time limit: 1s
Source limit:50000B
Languages: All
Resource: ICPC North America Mid-Central Regional Contest 2004

SPOJ Problem Set (partial)

3096. Overflowing Bookshelf


Problem code: BOOKSH
Agnes C. Mulligan is a fanatical bibliophile - she is constantly buying new books, and trying to find
space for those books. In particular, she has a shelf for her "to be read" books, where she puts her
newest books. When she decides to read one of these books, she removes it from the shelf, making
space for more books. Sometimes, however, she buys a new book and puts it on the shelf, but because
of limited space, this pushes one or more books off the shelf at the other end. She always adds books
on the left side of the shelf, making books fall off the right side. Of course, she can remove a book
from any location on the shelf when she wants to read one.
Your task will be to write a simulator that will keep track of books added and removed from a shelf.
At the end of the simulation, display the books remaining on the shelf, in order from left to right.
Books in each simulation will be identified by a unique, positive integer, 0 < I <= 100. There are three
types of events in the simulation:
Add: A new book is pushed on the left end of the shelf, pushing other books to the right as
needed. No book moves to the right unless it is pushed by an adjacent (touching) book on its left.
Any book that is not entirely on the shelf falls off the right edge. No single book will ever be
wider than the given shelf. No book that is currently on the shelf will be added again.
Remove: If the book is on the shelf, then the book is removed from the shelf, leaving a hole. If
the book isnt on the shelf, the operation is ignored.
End: End the simulation for this case and print the contents of the shelf.

Input
The input file will contain data for one or more simulations. The end of the input is signalled by a line
containing -1. Each simulation will begin with the integer width of the shelf, s, 5 <= s <= 100,
followed by a series of add and remove events. An add event is a single line beginning with an upper
case A followed by the book ID, followed by the integer width of the book, w, 0 < w <= s. A remove
event is a single line beginning with an upper case R followed by the the book ID. Finally, the end
event is a line containing only a single upper case E. Each number in an event is preceded by a single
blank.

Output
For each simulation case, print a single line containing a label (as shown in the output sample),
followed by the list of IDs of books remaining on the shelf, in order from left to right.
Input:
10
R 3
A 6 5
A 42 3
A 3 5
A 16 2
A 15 1

R 16
E
7
A 49 6
A 48 2
R 48
E
5
A 1 1
A 2 1
A 3 1
R 2
A 4 1
A 5 1
R 5
R 4
A 6 1
A 7 4
E
-1
Output:
PROBLEM 1: 15 3
PROBLEM 2:
PROBLEM 3: 7 6

Added by: Nikola P Borisov


Date:
2008-10-01
Time limit: 1s
Source limit:50000B
Languages: All
Resource: ICPC North America Mid-Central Regional Contest 2005

SPOJ Problem Set (partial)

3097. Flow Layout


Problem code: FLOWLAY
A flow layout manager takes rectangular objects and places them in a rectangular window from left to
right. If there isnt enough room in one row for an object, it is placed completely below all the objects
in the first row at the left edge, where the order continues from left to right again. Given a set of
rectangular dimensions and a maximum window width, you are to write a program that computes the
dimensions of the final window after all the rectangles have been placed in it.
For example, given a window that can be at most 35 units wide, and three rectangles with dimensions
10 x 5, 20 x 12, and 8 x 13, the flow layout manager would create a window that looked like the
figures below after each rectangle was added.
insert 10x5 rectangle insert 20x12 rectangle insert 8x13 rectangle
The final dimensions of the resulting window are 30 x 25, since the width of the first row is 10+20 =
30 and the combined height of the first and second rows is 12+13 = 25.

Input
The input consists of one or more sets of data, followed by a final line containing only the value 0.
Each data set starts with a line containing an integer, m, 1 <= m <= 80, which is the maximum width
of the resulting window. This is followed by at least one and at most 15 lines, each containing the
dimensions of one rectangle, width first, then height. The end of the list of rectangles is signaled by the
pair -1 -1, which is not counted as the dimensions of an actual rectangle. Each rectangle is between 1
and 80 units wide (inclusive) and between 1 and 100 units high (inclusive).

Output
For each input set print the width of the resulting window, followed by a space, then the lowercase
letter "x", followed by a space, then the height of the resulting window.

Example
Input:
35
10 5
20 12
8 13
-1 -1
25
10 5
20 13
3 12
-1 -1
15
5 17
5 17

5 17
7 9
7 20
2 10
-1 -1
0
Output:
30 x 25
23 x 18
15 x 47

Added by: Nikola P Borisov


Date:
2008-10-01
Time limit: 1s
Source limit:50000B
Languages: All
Resource: ICPC North America Mid-Central Regional Contest 2004

SPOJ Problem Set (partial)

3098. Tree Grafting


Problem code: GRAFT
Trees have many applications in computer science. Perhaps the most commonly used trees are rooted
binary trees, but there are other types of rooted trees that may be useful as well. One example is
ordered trees, in which the subtrees for any given node are ordered. The number of children of each
node is variable, and there is no limit on the number. Formally, an ordered tree consists of a finite set
of nodes T such that
there is one node designated as the root, denoted root(T);
the remaining nodes are partitioned into subsets T1, T2, ..., Tm, each of which is also a tree
(subtrees).
Also, define root(T1), ..., root(Tm) to be the children of root(T), with root(Ti) being the i-th child. The
nodes root(T1), ..., root(Tm) are siblings.
It is often more convenient to represent an ordered tree as a rooted binary tree, so that each node can
be stored in the same amount of memory. The conversion is performed by the following steps:
1. remove all edges from each node to its children;
2. for each node, add an edge to its first child in T (if any) as the left child;
3. for each node, add an edge to its next sibling in T (if any) as the right child.
This is illustrated by the following:
0
/ | \
1 2 3
/ \
4
5

0
/
===>

1
\
2
/ \
4

3
\
5

In most cases, the height of the tree (the number of edges in the longest root-to-leaf path) increases
after the conversion. This is undesirable because the complexity of many algorithms on trees depends
on its height.
You are asked to write a program that computes the height of the tree before and after the conversion.

Input
The input is given by a number of lines giving the directions taken in a depth-first traversal of the
trees. There is one line for each tree. For example, the tree above would give dudduduudu, meaning 0
down to 1, 1 up to 0, 0 down to 2, etc. The input is terminated by a line whose first character is #. You
may assume that each tree has at least 2 and no more than 10000 nodes.

Output
For each tree, print the heights of the tree before and after the conversion specified above. Use the
format:
Tree t: h1 => h2

where t is the case number (starting from 1), h1 is the height of the tree before the conversion, and h2
is the height of the tree after the conversion.

Example
Input:
dudduduudu
ddddduuuuu
dddduduuuu
dddduuduuu
#

Output:
Tree 1:
Tree 2:
Tree 3:
Tree 4:

2
5
4
4

=>
=>
=>
=>

4
5
5
4

Added by: Nikola P Borisov


Date:
2008-10-01
Time limit: 3s
Source limit:50000B
Languages: All
Resource: ICPC North America Rocky Mountain Regional Contest 2007

SPOJ Problem Set (partial)

3132. Server Relocation


Problem code: UPTIME
Michael has a powerful computer server that has hundreds of parallel processors and terabytes of main
memory and disk space. Many important computations run continuously on this server, and power
must be supplied to the server without interruption.
Michaels server must be moved to accommodate new servers that have been purchased recently.
Fortunately, Michaels server has two redundant power supplies---as long as at least one of the two
power supplies is connected to an electrical outlet, the server can continue to run. When the server is
connected to an electrical outlet, it can be moved to any location which is not further away from the
outlet than the length of the cord used to connect to the outlet.
Given which outlet Michaels server is plugged into initially and finally, and the locations of outlets in
the server room, you should determine the smallest number of times you need to plug a cord into an
electrical outlet in order to move the server while keeping the server running at all times. Note that, in
the initial and final configuration, only one cord is connected to the power outlet.

Input
The first line of input is an integer giving the number of cases to follow. For each case, the first line is
of the form
OUTLETS OUTLET_INITIAL OUTLET_FINAL LENGTH1 LENGTH2
where
OUTLETS is the number of outlets in the server room (2 <= OUTLETS <= 1000).
OUTLET_INITIAL is the index (starting from 1) of the outlet the server is initially connected to.
OUTLET_FINAL is the index (starting from 1) of the outlet the server is finally connected to.
LENGTH1 and LENGTH2 are the positive lengths of the two power cords, with at most three
digits of precision after the decimal point (0 < LENGTH1, LENGTH2 <= 30000).
These are followed by OUTLETS lines giving the integer coordinates of the wall outlets, one per line,
with the k-th line giving the location of the k-th outlet. All coordinates are specified as two integers (xand y-coordinates) separated by a space, with absolute values at most 30000. You may assume that all
coordinates are distinct, and that the initial outlet and the final outlet are different.

Output
For each case, print the minimum number of times you need to plug a cord into an electrical outlet in
order to move the server to the final location while keeping the server running at all times. If this is not
possible, print "Impossible".

Example
Input:
2
4 1 4 2.000 1.000
0 0
0 4
4 0
4 4
9 1 4 2.000 3.000
0 7
-6 2
-3 3
6 2
-6 -3
3 -3
6 -3
-3 -7
0 -7
Output:
Impossible
8

Added by: Nikola P Borisov


Date:
2008-10-11
Time limit: 5s-15s
Source limit:50000B
Languages: All
Resource: Rocky Mountain Regional ACM-ICPC Contest 2007

SPOJ Problem Set (partial)

3185. Linear Pachinko


Problem code: LINEARPA
This problem is inspired by Pachinko, a popular game in Japan. A traditional Pachinko machine is a
cross between a vertical pinball machine and a slot machine. The player launches small steel balls to
the top of the machine using a plunger as in pinball. A ball drops through a maze of pins that deflect
the ball, and eventually the ball either exits at a hole in the bottom and is lost, or lands in one of many
gates scattered throughout the machine which reward the player with more balls in varying amounts.
Players who collect enough balls can trade them in for prizes.
For the purposes of this problem, a linear Pachinko machine is a sequence of one or more of the
following: holes (."), floor tiles (_"), walls (|"), and mountains (/\"). A wall or mountain will
never be adjacent to another wall or mountain. To play the game, a ball is dropped at random over
some character within a machine. A ball dropped into a hole falls through. A ball dropped onto a floor
tile stops immediately. A ball dropped onto the left side of a mountain rolls to the left across any
number of consecutive floor tiles until it falls into a hole, falls off the left end of the machine, or stops
by hitting a wall or mountain. A ball dropped onto the right side of a mountain behaves similarly. A
ball dropped onto a wall behaves as if it were dropped onto the left or right side of a mountain, with a
50% chance for each. If a ball is dropped at random over the machine, with all starting positions being
equally likely, what is the probability that the ball will fall either through a hole or off an end? For
example, consider the following machine, where the numbers just indicate character positions and are
not part of the machine itself:
123456789
/\.|__/\.

The probabilities that a ball will fall through a hole or off the end of the machine are as follows, by
position: 1 = 100%, 2 = 100%, 3 = 100%, 4 = 50%, 5 = 0%, 6 = 0%, 7 = 0%, 8 = 100%, 9 = 100%.
The combined probability for the whole machine is just the average, which is approximately 61.111%.

Input
The input consists of one or more linear Pachinko machines, each 1Euro"79 characters long and on a
line by itself, followed by a line containing only "#" that signals the end of the input.

Output
For each machine, compute as accurately as possible the probability that a ball will fall through a hole
or off the end when dropped at random, then output a single line containing that percentage truncated
to an integer by dropping any fractional part.

Example
Input:
/\.|__/\.
_._/\_|.__/\./\_
...
___
./\.
_/\_
_|.|_|.|_|.|_
____|_____
#
Output:
61
53
100
0
100
50
53
10

Added by: Nikola P Borisov


Date:
2008-10-20
Time limit: 5s
Source limit:50000B
Languages: All
Resource: Mid-Central Regional ACM-ICPC Contest 2006

SPOJ Problem Set (partial)

3186. Frugal Search


Problem code: FRSEARCH
For this problem you will write a search engine that takes a query, searches a collection of words, and
finds the lexicographically smallest word that matches the query (i.e., the matching word that would
appear first in an English dictionary). A query is a sequence of one or more terms separated by single
vertical bars (|"). A term is one or more letters followed by zero or more signed letters. A signed
letter is either +s (positive" s) or -s (negative" s), where s is a single letter. All letters are lowercase,
and no letter will appear more than once within a term. A query will not contain spaces. A term
matches a word if the word contains at least one of the unsigned letters, all of the positive letters, and
none of the negative letters; a query matches a word if at least one of its terms matches the word.

Input
The input consists of one or more test cases followed by a line containing only #" that signals the
end of the input. Each test case consists of 1Euro"100 words, each on a line by itself, followed by a
line containing only *" that marks the end of the word list, followed by one or more queries, each on
a line by itself, followed by a line containing only * *" that marks the end of the test case. Each
word will consist of 1-20 lowercase letters. All words within a test case will be unique. Each query
will be as defined above and will be 1-79 characters long.

Output
For each query, output a single line containing the lexicographically smallest word within that test case
that matches the query, or the word NONE if there is no matching word. At the end of each test case,
output a dollar sign on a line by itself.

Example
Input:
elk
cow
bat
*
ea
acm+e
nm+o|jk+l
**
debian
slackware
gentoo
ubuntu
suse
fedora
mepis
*
yts
cab-e+n
r-e|zjq|i+t|vs-p+e-u-c

**
#
Output:
bat
NONE
elk
$
gentoo
ubuntu
NONE
$

Added by: Nikola P Borisov


Date:
2008-10-20
Time limit: 5s
Source limit:50000B
Languages: All
Resource: Mid-Central Regional ACM-ICPC Contest 2006

SPOJ Problem Set (partial)

3187. Go Go Gorelians
Problem code: GOGOGORE
The Gorelians travel through space using warp links. Travel through a warp link is instantaneous, but
for safety reasons, an individual can only warp once every 10 hours. Also, the cost of creating a warp
link increases directly with the linear distance between the link endpoints.
The Gorelians, being the dominant force in the known universe, are often bored, so they frequently
conquer new regions of space in the following manner.
1. The initial invasion force finds a suitable planet and conquers it, establishing a Regional Gorelian
Galactic Government, hereafter referred to as the RGGG, that will govern all Gorelian matters in
this region of space.
2. When the next planet is conquered, a single warp link is constructed between the new planet and
the RGGG planet. Planets connected via warp links in this manner are said to be part of the
Regional Gorelian Planetary Network, that is, the RGPN.
3. As additional planets are conquered, each new planet is connected with a single warp link to the
nearest planet already in the RGPN, thus keeping the cost of connecting new planets to the
network to a minimum. If two or more planets are equidistant from the new planet, the new planet
is connected to whichever of them was conquered first.
This causes a problem however. Since planets are conquered in a more-or-less random fashion, after a
while, the RGGG will probably not be in an ideal location. Some Gorelians needing to consult with the
RGGG might only have to make one or two warps, but others might require dozens--very inconvenient
when one considers the 10-hour waiting period between warps.
So, once each Gorelian year, the RGGG analyzes the RGPN and relocates itself to an optimal location.
The optimal location is defined as a planet that minimizes the maximum number of warps required to
reach the RGGG from any planet in the RGPN. As it turns out, there is always exactly one or two such
planets. When there are two, they are always directly adjacent via a warp link, and the RGGG divides
itself evenly between the two planets.
Your job is to write a program that finds the optimal planets for the RGGG. For the purposes of this
problem, the region of space conquered by the Gorelians is defined as a cube that ranges from (0,0,0)
to (1000,1000,1000).

Input
The input consists of a set of scenarios where the Gorelians conquer a region of space. Each scenario
is independent. The first line of the scenario is an integer N that specifies the total number of planets
conquered by the Gorelians. The next N lines of the input specify, in the order conquered, the IDs and
coordinates of the conquered planets to be added to the RGPN, in the format IDXYZ. An ID is an
integer from 1 to 1000. X, Y, and Z are integers from 0 to 1000. A single space separates the numbers.
A value of N = 0 marks the end of the input.

Output
For each input scenario, output the IDs of the optimal planet or planets where the RGGG should
relocate. For a single planet, simply output the planet ID. For two planets, output the planet IDs,
smallest ID first, separated by a single space.

Example
Input:
5
1 0 0 0
2 0 0 1
3 0 0 2
4 0 0 3
5 0 0 4
5
1 0 0 0
2 1 1 0
3 3 2 0
4 2 1 0
5 3 0 0
10
21 71 76 4
97 32 5 69
70 33 19 35
3 79 81 8
31 91 17 67
52 31 48 75
48 90 14 4
41 73 2 21
83 74 41 69
26 32 30 24
0
Output:
3
2 4
31 97

Added by: Nikola P Borisov


Date:
2008-10-20
Time limit: 10s
Source limit:50000B
Languages: All
Resource: Mid-Central Regional ACM-ICPC Contest 2006

SPOJ Problem Set (partial)

3188. Minimum Spanning Tree


Problem code: MST
Find the minimum spanning tree of the graph.

Input
On the first line there will be two integers N - the number of nodes and M - the number of edges. (1 <=
N <= 10000), (1 <= M <= 100000)
> M lines follow with three integers i j k on each line representing an edge between node i and j with
weight k. The IDs of the nodes are between 1 and n inclusive. The weight of each edge will be <=
1000000.

Output<h3>
Single number representing the total weight of the minimum spanning
tree on this graph. There will be only one possible MST.
Example
Input:
4 5
1 2 10
2 3 15
1 3 5
4 2 2
4 3 40
Output:
17
Nikola P
Borisov
Date:
2008-10-20
Time limit: 5s-10s
Source
50000B
limit:
Languages: All
Added by:

SPOJ Problem Set (partial)

3448. Connect
Problem code: CONNECT2
Your task is to decide if a specified sequence of moves in the board game Connect ends with a
winning move.
\epsfbox{p3381.eps}
In this version of the game, different board sizes may be specified. Pegs are placed on a board at
integer coordinates in the range [0, N ]. Players Black and White use pegs of their own color. Black
always starts and then alternates with White, placing a peg at one unoccupied position (x, y) . Blacks
endzones are where x equals 0 or N , and Whites endzones are where y equals 0 or N . Neither player
may place a peg in the other players endzones. After each play, the latest position is connected by a
segment to every position with a peg of the same color that is a chess knights move away (2 away in
one coordinate and 1 away in the other), provided that a new segment will touch no segment already
added, except at an endpoint. Play stops after a winning move, which is when a players segments
complete a connected path between the players endzones.
For example, Figure 1 shows a board with N = 4 after the moves (0,2), (2,4), and (4,2). Figure 2 adds
the next move (3,2). Figure 3a shows a poor next move of Black to (2,3). Figure 3b shows an alternate
move for Black to (2,1) which would win the game.
Figure 4 shows the board with N = 7 after Black wins in 11 moves:
(0, 3), (6, 5), (3, 2), (5, 7), (7, 2), (4, 4), (5, 3), (5, 2), (4, 5), (4, 0), (2, 4)

Input
The input contains from 1 to 20 datasets followed by a line containing only two zeroes, 0 0. The
first line of each dataset contains the maximum coordinate N (3 < N < 21) and the number of total
moves, M (4 < M < 250) , with M odd, so Black will always be the last player. The dataset ends with
one or more lines each containing two or more coordinate pairs, with a total of M coordinate pairs. All
numbers on any line will be separated by blanks. All data will be legal. There will never be a winning
move before the last move.

Output
The output contains one line for each data set: yes if the last move is a winning move and no
otherwise.

Example
Input:
4 5
0 2 2 4 4 2 3 2 2 3
4 5
0 2 2 4 4 2 3 2 2 1

7
0
5
0

11
3 6 5 3 2 5 7 7 2 4 4
3 5 2 4 5 4 0 2 4
0

Output:
no
yes
yes

Added by: Nikola P Borisov


Date:
2008-12-04
Time limit: 2s
Source limit:50000B
Languages: All
Resource: ICPC North America Pacific Northwest Region

SPOJ Problem Set (partial)

3449. Sum of Squares


Problem code: SUMSQ
We are interested in how many different sequences of N non negative integers there are that have the
sum of their squares less than S. Note that the squence (1, 2) is different from the sequence (2, 1).

Input
The input consists of only one line with two integers N (0 < N < 30) and S ( S < 100 ).

Output
A single integer representing the number of different sequences that have the sum of their squares less
than S.

Example
Input:
1 4
Output:
2

Added by: Nikola P Borisov


Date:
2008-12-04
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Bulgarian Winter Competition 2003

SPOJ Problem Set (partial)

3450. Fast Width


Problem code: FASTW
When you want to get quick to some place in the city you dont often look for the shortest distance to
there. Sometimes what is important is how width the street is. We will say that a route in the city had
width is the width of the smallest street you will have to pass through. Now you are give the city
network of streets and intersections and the width of each street and you are asked to provide the width
of the widest path between intersection with number 1 and intersection with number N.

Input
On the first line of the input you will find two integers N (2 < N < 10000) the number of intersections
in the city and M (1 < M < 100000) the number of streets in the city. On each of the next M lines you
will get information about one street in the form of 3 integers I, J, W (1 < W < 65000) which will
mean that intersections I and J are connected via street with width W.

Output
A single integer representing the width of the path between 1 and N with maximum width. If no path
exists between 1 and N output 0

Example
Input:
5 6
1 2 1
1 3 3
1 4 9
2 5 10
3 5 4
4 5 2
Output:
3

Added by: Nikola P Borisov


Date:
2008-12-04
Time limit: 20s
Source limit:50000B
Languages: All
Resource: Bulgarian National Olympiad Round 2 2004 Group A

SPOJ Problem Set (main)

3610. BOI 97 - Factorial


Problem code: BOIFAC
For a positive integer number N, find all positive integer numbers X (if any such number exists) with
the property that the number 1*2*3*...*X has exactly N decimal digits. Assume that N is at most
150,000.

Input
A single line which contains a positive integer number denoting the number N.

Output
The first line should contain the string "NO", if such a number does not exist. Otherwise, the first line
should contain a positive integer denoting how many X numbers exist. Then print all the X numbers,
one number per line.

Example
Input:
5
Output:
1
8

Added by: Mir Wasi Ahmed


Date:
2008-12-31
Time limit: 1s
Source limit:50000B
Languages: C C99 strict C++ PAS gpc PAS fpc JAVA
Resource: Balkan Olympiad of Informatics 1997

SPOJ Problem Set (main)

4108. BOI 97 - Street Network


Problem code: BOI97SN
The street network of a city is composed of streets and nodes. In a node, two or more streets can meet.
All streets are one-way streets. Note also that, two nodes can be connected directly by more than one
street, and one node can have a street that loops back to itself. Write a computer program in order to
address the following issues: 1. Is it possible to start from at least one node A and visit ALL streets
exactly once ? 2. How many nodes can serve as starting points in order to satisfy the property of the
previous case ? 3. For each node X, how many paths of length S exist starting from X and ending to X,
where any street or node can be visited more than once ?

Input
In the first line in the input is a positive integer number N (N<=50), denoting the number of nodes in
the city street network. The second line contains a positive integer number S (S<=3) denoting the path
length. The next N lines contain the network description in matrix form. More precisely, the element
in row I and column J is the number of streets from node I to node J.

Output
The first line contains the string "YES" if you can start from a node, travel through all streets exactly
once, and arrive either at the starting point, or at another node. Otherwise, the string "NO" should
appear in the output. If the answer is "YES", the next line of the output file should contain a positive
integer number denoting how many nodes can serve as starting points. Finally, the last line of the
output file should contain N positive integers (separated by a space) that show for each node how
many different paths with length S exist such that each path leads from the node back to itself. These
numbers should be sorted in increasing order.

Example
Input 1:
3
2
1 1 0
1 1 1
0 1 1

Output:
YES
3
2 2 3
Input 2:
3
2
1 1 0
1 1 2
0 0 1

Output:
NO
1 2 2

Added by: Mir Wasi Ahmed


Date:
2009-03-24
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Balkan Olympiad of Informatics 1997

SPOJ Problem Set (partial)

5167. Quadratics
Problem code: BRHQUADR
Butch needs help with checking his math homework. He is studying quadratic equations, which are in
the form
y = ax 2 +bx+c
He wants to give you a, b, c, and x (1 <= a, b, c, x <= 10), and asks you to find y.

Input
Line 1: Three space-separated integers, a, b, and c.
Line 2: A single integer, x.

Output
Line 1: A single integer, y

Example
Input:2 5 3-4Output:
15

Added by: Damon Doucet


Date:
2009-11-02
Time limit: 5s
Source limit:50000B
Languages: All

SPOJ Problem Set (partial)

5201. Stacks of Bricks


Problem code: SBRICKS
Problem statement
You are given a sequence of n (n < 100) integers. Each number denotes the height of a stack of bricks.
If we put the stacks in a line as in the illustration below, we would see stacks of uneven heights.
Suppose a "move" is made by picking up one brick from one stack and putting it on another, compute
the minimum number of moves to rearrange the bricks such that all stacks have the same height.
Read the input from standard input. The first line of the input is the integer n, followed by n lines of
integers denoting the height of the n stacks. The total number of bricks will be divisible by the number
of stacks. Thus, it is always possible to rearrange the bricks such that all stacks have the same height.
Your output to standard output should consist of exactly one integer denoting the minimum number of
moves.

Sample input
6524175

Sample output
5
Added by: Zhang Zhiyong Melvin
Date:
2009-11-04
Time limit: 1s
Source limit:50000B
Languages: All

SPOJ Problem Set (partial)

5202. Stacks of Bricks 2


Problem code: SBRICKS2
Summary
This is similar to "Stacks of Bricks" except that for each move you are only allowed to move a brick to
a stack on its immediate left or right.

Problem statement
You are given a sequence of n (n < 100) integers. Each number denotes the height of a stack of bricks.
If we put the stacks in a line as in the illustration below, we would see stacks of uneven heights.
Suppose a "move" is made by picking up one brick from one stack and putting it on stack to its
immediate left or right, compute the minimum number of moves to rearrange the bricks such that all
stacks have the same height.
Read the input from standard input. The first line of the input is the integer n, followed by n lines of
integers denoting the height of the n stacks. The total number of bricks will be divisible by the number
of stacks. Thus, it is always possible to rearrange the bricks such that all stacks have the same height.
Your output to standard output should consist of exactly one integer denoting the minimum number of
moves.

Sample input
6
5
2
4
1
7
5

Sample output
8
Added by: Zhang Zhiyong Melvin
Date:
2009-11-04
Time limit: 1s
Source limit:50000B
Languages: All

SPOJ Problem Set (partial)

6409. Suffix Array


Problem code: SARRAY
Given a string of length at most 100,000 consist of alphabets and numbers. Output the suffix array of
the string.
A suffix array is an array of integers giving the starting positions (0-based) of suffixes of a string in
lexicographical order. Consider a string "abracadabra0AbRa4Cad14abra". The size of the suffix array
is equal to the length of the string. Below is the list of 26 suffixes of the string along with its starting
position sorted in lexicographical order:
POS
20
16
21
12
17
14
25
10
15
22
7
0
3
18
5
13
23
8
1
4
19
6
24
9
2

SUFFIX 11 0AbRa4Cad14abra
14abra
4Cad14abra
4abra
AbRa4Cad14abra
Cad14abra
Ra4Cad14abra
a
a0AbRa4Cad14abra
a4Cad14abra
abra
abra0AbRa4Cad14abra
abracadabra0AbRa4Cad14abra
acadabra0AbRa4Cad14abra
ad14abra
adabra0AbRa4Cad14abra
bRa4Cad14abra
bra
bra0AbRa4Cad14abra
bracadabra0AbRa4Cad14abra
cadabra0AbRa4Cad14abra
d14abra
dabra0AbRa4Cad14abra
ra
ra0AbRa4Cad14abra
racadabra0AbRa4Cad14abra

Note: this is a partial score problem.


O(n 2 log(n)) is expected to score about 20-30. (Naive sorting all suffixes)
O(n log 2 (n)) is expected to score about 40. (OK for most programming contest problems)
O(n log n) is expected to score about 60-70. (Use counting sort for small alphabet size)
O(n) without tweaks is expected to score about 80-90.
O(n) with tweaks is expected to score 100. (This is meant for fun only :)

Input
A single line containing the string.

Output
The suffix array of the string.

Example
Input:
abracadabra0AbRa4Cad14abra
Output:
11
20
16
21
12
17
14
25
10
15
22
7
0
3
18
5
13
23
8
1
4
19
6
24
9
2

Added by: Felix Halim


Date:
2010-03-26
Time limit: 0.25s
Source limit:50000B
Languages: All except: PERL 6

SPOJ Problem Set (oi)

6610. Ct ba?ng
Problem code: CUTBOARD
SNAD mun ct mt ba?ng hinh chu+~ nht kch thu+o+c M x N thanh cc hinh chu+~ nht con
chie^u dai hoc chie^u rng la 1. Mi ln ct nhu+ vy SNAD chi? c the^? ct tren ria cu?a ba?ng
hinh chu+~ nht , c nghia la c the^? cho.n 1 trong 4 phu+o+ng n: ct dong u tien, ct dong
cui cung, ct ct u tien, ct ct cui cung. Tuy nhien tng cc s trong hinh chu+~ nht con nhu+
vy khng u+o+.c vu+o+t qu P. Ba.n hay gip SNAD tim cch ct ba?ng ban u thanh t hinh
chu+~ nht con nht c the^?

Input
Dong u gm 3 s P, N, M (P < 200000000, 0 < M, N < 2001)
M dong sau m ta? ma trn hinh chu+~ nht kch thu+o+c M x N, cc s tren ma trn nho? ho+n
100000

Output
Ghi s duy nht la ke^t qua? nho? nht c the^?

Example
Input:12 6 46 0 4 8 0 50 4 5 4 6 00 5 6 5 6 05 4 0 0 5 4Output:8

Added by: Tran Hai Dang


Date:
2010-05-04
Time limit: 5s
Source limit:50000B
Languages: All except: TCL SCALA ERL TECS JS
Resource: POI 2005

SPOJ Problem Set (oi)

6671. Xe but
Problem code: MBUS
Tren mt phng to.a cho N ie^?m la N tra.m xe but, o+? tra.m thu+ i c to.a (xi, yi) va c zi
ngu+o+i ang cho+ o+? . Cn i xe but tu+ (1, 1) e^n (X, Y) sao cho n u+o+.c nhie^u
ngu+o+i nht c the^?, bie^t rng xe but chi? c the^? i len tren hoc sang pha?i.

Du+~ lie^.u
Dong u ghi 3 s nguyen du+o+ng X, Y, N (X, Y < 1000000001, N < 100001)
N dong sau mi dong ghi 3 s xi, yi, zi (xi <= X, yi <= Y, zi < 1000001).

Ke^t qu?a
Ghi tren mt dong s duy nht la s khch lo+n nht c the^? n u+o+.c.

V du.
Du+~ lie^.u:
8 7 11
4 3 4
6 2 4
2 3 2
5 6 1
2 5 2
1 5 5
2 1 1
3 1 1
7 7 1
7 4 2
8 6 2Ke^t qu?a
11

Added by: Tran Hai Dang


Date:
2010-05-21
Time limit: 1s
Source limit:50000B
Languages: All except: TCL SCALA ERL TECS JS
Resource: POI 2005

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

8601. Brainfuck Geek!!! (Bonus Question)


Problem code: BGEEK
Write the following words in brainfuck programming language
"GEEK-O-CODE" (Quotes not included)
Note: Points awarded will be based on your sourcecode length
Added by: Infinity
Date:
2011-03-21
Time limit: 1s
Source limit:50000B
Cluster:
Pyramid (Intel Pentium III 733 MHz)
Languages: BF

SPOJ Problem Set (partial)

8760. Salesman
Problem code: SALESMAN
Mt thu+o+ng nhn vu+a quye^t i.nh mua mt con tau mo+i phu.c vu. cho cc cuc trao i hang
ha do.c bo+ sng Danube. Con tau cu?a anh ta c tc rt tuye^.t vo+i, n c the^? u+a anh ta
e^n bt ki vi. tr nao tren sng trong khng qu mt tch tc, nhu+ng, la.i la mt con tau rt tn
nhien lie^.u. Con tau tn U dollar cho 1 mt i ngu+o+.c dong, va mt D dollar cho 1 mt i xui
dong.
C tt ca? N hi cho+. sp su+?a die^~n ra tren khp bo+ sng Danube. Mi hi cho+. chi? die^~n ra
trong 1 ngay. Vo+i mi hi cho+. x, thu+o+ng nhn bie^t hi cho+. bt u vao ngay T[x] (tnh tu+
khi mua tau), ta.i vi. tr cch thu+o+.ng ngun L[x] mt, va ne^u tham gia, thu+o+ng nhn se~ kie^m
u+o+.c M[x] dollar. Anh ta se~ pha?i bt u va ke^t thc chuye^n i cu?a minh ta.i mt vi. tr cch
thu+o+.ng ngun S mt.
Lu+u rng, cc hi cho+. bt u theo thu+ tu+. tho+i gian, nen ne^u nhu+ hi cho+. A u+o+.c
bt u so+m ho+n hi cho+. B, thu+o+ng nhn khng the^? tham gia hi cho+. B tru+o+c hi cho+.
A. Tuy nhien, ne^u nhu+ c nhie^u hi cho+. die^~n ra trong cung 1 ngay, thu+o+ng nhn c the^?
tham gia bt ki hi cho+. nao theo bt ki thu+ tu+. nao anh ta mun. Thu+o+ng nhn c the^? i qua
1 hi cho+. nhie^u ln trong ngay, nhu+ng di nhien, anh ta se~ chi? kie^m u+o+.c tie^n trong ln
u tien gh qua hi cho+. .
Nhie^.m vu. cu?a ba.n, la hay vie^t chu+o+ng trinh gip thu+o+ng nhn tnh u+o+.c s tie^n
nhie^u nht thu u+o+.c, khi tham gia cc hi cho+. theo phu+o+ng n ti u+u. S tie^n kie^m
u+o+.c, bng tng lo+.i nhun a.t u+o+.c tu+ nhu+~ng hi cho+. anh ta tham gia, tru+ i chi ph
di chuye^?n tren sng.
Input:
- Dong u tien gm 4 s nguyen N,U,D,S
- N dong tie^p theo, mi gm 3 s T[k], L[k], M[k] m ta? hi cho+. k: hi cho+. bt u vao ngay
T[k], cch thu+o+.ng ngun L[k] mt, va lo+.i nhun a.t u+o+.c ne^u tham gia la M[k]
- Cc s tren cung 1 dong cch nhau bo+?i t nht 1 du cch
Output
- Gm 1 s nguyen duy nht, la s tie^n lo+n nht ma thu+o+ng nhn c the^? kie^m u+o+.c (gi
tri. nay c the^? bng 0).
Gio+i ha.n:
- 1 <= N <= 500000, s hi cho+.
- 1 <= D <= U <= 10, chi ph di chuye^?n 1 mt ngu+o+.c dong (U), va xui dong (D)
- 1 <= S <= 500001, vi. tr xut pht cu?a thu+o+ng nhn
- 1 <= T[k] <= 500000, ngay die^~n ra hi cho+. thu+ k
- 1 <= L[k] <= 500001, vi. tr cu?a hi cho+. thu+ k
- 1 <= M[k] <= 4000, s tie^n thu+o+ng nhn c the^? kie^m u+o+.c ne^u tham gia hi cho+.
thu+ k
- Khng c hai hi cho+. nao u+o+.c mo+? o+? cung vi. tr, cung nhu+ khng c hi cho+. nao
u+o+.c mo+? ta.i nha cu?a thu+o+ng nhn
Example:
Input
4 5 3 100
2 80 100

20 125 130
10 75 150
5 120 110
Output
50
Gia?i thch:
Phu+o+ng n ti u+u cu?a thu+o+ng nhn se~ la tham gia hi cho+. 1 va 3, theo thu+ tu+. nhu+ sau
- i ngu+o+.c dong 20 mt, chi ph 100 dollar. Lo+.i nhun hie^.n ta.i: -100
- Tham gia hi cho+. 1, kie^m u+o+.c 100 dollar. Lo+.i nhun hie^.n ta.i: 0
- i ngu+o+.c dong 5 mt, chi ph 25 dollar. Lo+.i nhun hie^.n ta.i: -25
- Tham gia hi cho+. 3, kie^m u+o+.c 150 dollar. Lo+.i nhun hie^.n ta.i: 125
- i xui dong 25 mt va tro+? ve^ nha, chi ph 75 dollar. Lo+.i nhun cui cung: 50 dollar
Added by: sieunhan
Date:
2011-04-21
Time limit: 12s
Source limit:50000B
Languages: All
Resource: IOI 2009, day 2

SPOJ Problem Set (oi)

9027. KAMION
Problem code: KAMION
Mirko la tai xe^ xe ta?i. Cng vie^.c hang ngay cu?a anh la chuyen cho+? hang ho dhi cc thanh
ph. Chie^c xe ta?i cu?a anh c the^? cho+? dhu+o+.c mt lu+o+.ng khi hang tuy , tuy nhien, n
chi? cho php Mirko mi ln dhu+o+.c do+~ ra khi hang nm tren cung (c the^? coi xe ta?i cu?a
Mirko nhu+ 1 stack). C 26 loa.i hang ho khc nhau, chng dhu+o+.c k hie^.u bng cc chu+~ ci
trong ba?ng k tu+. alphabet.
Thanh ph cu?a Mirko gm cc con dhu+o+ng 1 chie^u, vo+i dh dai mi con dhu+o+ng la 1km.
O+? thanh ph nay, MIrko chi? di chuye^?n tren 3 loa.i dhu+o+ng sau:
- Loa.i 1: mi ln Mirko li xe qua con dhu+o+ng nay, anh ta pha?i cht them dhng 1 khi hang
u+ng vo+i con dhu+o+ng dh
- Loa.i 2: mi ln Mirko li xe qua con dhu+o+ng nay, anh ta pha?i do+~ xung khi hang tren cung
cu?a xe, va pha?i dhng vo+i yeu cu tren dhu+o+ng nay
- Loa.i 3: mi ln Mirko li xe qua con dhu+o+ng nay, anh ta khng cn cht them/do+~ dhi bt ki
khi hang nao
Lu+u , ngoai cc thao tc tren, Mirko khng dhu+o+.c php ly them hang o+? bt ki ch nao khc,
cung nhu+ khng dhu+o+.c do+~ bo? hang o+? do.c dhu+o+ng.
Hang ngay, Mirko se~ xut pht o+? thanh ph 1, di chuye^?n qua cc con dhu+o+ng, va ke^t thc
chuye^n dhi o+? thanh ph N. Ban dhu, xe Mirko khng cho+? hang, va khi ke^t thc, cc khi
hang c the^? vn con o+? tren xe cu?a Mirko.
Yeu cu: cho bie^t ma.ng lu+o+i cc con dhu+o+ng trong thanh ph, hay vie^t chu+o+ng trinh
dhe^m s cch Mirko c the^? li xe ta?i tren chng dhu+o+ng khng qu K km. Mirko c the^? dhi
qua 1 thanh ph nhie^u ln, mie^~n sao thoa? man dhu+o+.c cc yeu cu dha cho.
Input
- Dong dhu tien cu?a input gm 3 s nguyen N,M,K (2 <= N <= 50, 0 < M < 2450, 0 < K <= 50)
- M dong tie^p theo m ta? cc con dhu+o+ng trong thanh ph. Mi dong se~ c da.ng nhu+ sau:
+ Loa.i 1: "x y C", vo+i 1 <= x,y <= N va C la 1 k tu+. in hoa (tu+ A..Z) m ta? c 1 con
dhu+o+ng tu+ x dhe^n y, va Mirko cn cht them 1 khi hang C len xe
+ Loa.i 2: "x y c", vo+i 1 <= x,y <= N va c la 1 k tu+. in thu+o+ng (tu+ a..z) m ta? c 1 con
dhu+o+ng tu+ x dhe^n y, va Mirko cn do+~ bo? 1 khi hang c ra kho?i xe
+ Loa.i 3: "x y", vo+i 1 <= x,y <= N, m ta? c 1 con dhu+o+ng tu+ x dhe^n y.
- Du+~ lie^.u dha?m ba?o vo+i mi con dhu+o+ng, x khc y, va khng c 2 con dhu+o+ng nao ni
cung 1 cp thanh ph theo chung 1 hu+o+ng
Output:
- Tren dong duy nht, in ra s cch Mirko c the^? thu+.c hie^.n dhu+o+.c chuye^n dhi cu?a minh,
ly modulo 10007
Example:
Input
2 1 10
12a
Output
0
Input
795

12A
23B
25
53C
34b
36c
37
47a
67a
Output
4
Added by: sieunhan
Date:
2011-06-13
Time limit: 5s-20s
Source limit:50000B
Languages: All except: CLOJ ERL F# GO PERL 6 PYTH 3.1.2 SCALA TCL
Resource: Croatian Olympiad in Informatics 2011

SPOJ Problem Set ()

9028. DIEULINH
Problem code: NTKM
Minh has n piles of pebbles. The i-th pile has a[i] pebbles. The cost to merge 2 piles is the total of
pebbles in this 2 piles. Calculate the cost to merge all these piles so that the cost is lowest.
Input
_ The first line is number N.
_ Next are n integers which is the number of pebbles in N piles.

Output
Result: write down the lowest cost

Example
Input:
5
4 1 2 7 5
Output:
41
n < 1000, a[i] < 1000000000
Note: sorry about my english ^^

Added by: cao thu?_bun ngu?[C11]


Date:
2011-06-13
Time limit: 0.5s-2.5s
Source limit:50000B
Languages: All except: CLOJ ERL F# GO PERL 6 PYTH 3.1.2 SCALA TCL
Resource: [C11]

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

11131. Palindrome or not


Problem code: PALINCOD
A palindrome is a word, phrase, number, or other sequence of units that can be read the same way in
either direction, with general allowances for adjustments to punctuatiom and word dividers
for eg., HELLOLLEH is a Palindrome string,
and 123456789 is not a Palindrome number.
Input
t - number of testcases [ t < 1000 ].
On each of the next t lines given string.

Output
For each next t lines output the dataset number as a decimal integer (start counting at one), a space and
"YES" if the given input is palindrome, or "NO" if the input is not.
Example
Input:
2
HELloolLEH
ILOVEyou
Output:
1 "YES"
2 "NO"
CHAALLENGE:- minimum size of the code
Added by: avinash
Date:
2012-03-18
Time limit: 1s
Source limit:250B
Languages: All
Resource: Resource

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (classical)

11400. Redoks
Problem code: REDOKS
Luka is not paying attention in class again, while the teacher is explaining redox reactions. Instead of
paying attention, he is playing with analog dials.
An analog dial is a small device which always shows one digit between 0 and 9. It also contains a
small button which increases the number by 1 (unless it is 9, in which case it is changed to 0).
Luka has N such dials on his desk, numbered 1 to N left to right, and two sheets of paper for him to
write on.
Lukas game starts with him setting the dials in some starting configuration, which he then writes onto
the first sheet. Luka then does the following M times:
Choose two integers A and B (1 <= A <= B <= N) and write them down on the first sheet.
Calculate the sum of numbers on dials numbered between A and B (inclusive), and write the sum
down on the second sheet.
Press the button once on all dials numbered between A and B.

Just as he had finished his game, the teacher noticed him, and took away all his dials and the second
sheet of paper.
Given the contents of the first sheet, help him calculate the numbers on the second sheet.

Input
The first line contains two integers N and M (1 <= N <= 250000, 1 <= M <= 100000).
The second line contains the initial configuration of the dials, N decimal digits with no spaces. The
first digit is the number initially on dial 1, the second digit the number on dial 2 and so on.
Each of the following M lines contains two integers A and B (1 <= A <= B <= N).

Output
Output M lines, the sums calculated by Luka, in order in which he calculated them.

Scoring
In 30% of all test cases, the numbers N and M will be less than 1000.

Sample #1
Input:
4 3
1234
1 4
1 4
1 4

Output:
10
14
18

Sample #2
Input:
4 4
1234
1 1
1 2
1 3
1 4

Output:
1
4
9
16

Sample #3
Input:
7 5
9081337
1 3
3 7
1 3
3 7
1 3

Output:
17
23
1
19
5

Added by: Andrs Meja-Posada


Date:
2012-04-18
Time limit: 5s
Source limit:50000B
Languages: All
Resource: COCI 2007/2008 Contest #3

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

11733. Find our next planet!


Problem code: RPL_T1
Andreina the hobbit, a famous scientist from Rainbowland is trying to make communication with
other planets through a very rare object, Andreina receives the signal by her headphones connected to
the object, if she hears at least N signals on an interval of K consecutive minutes (each minute the
object makes a turn and points out to another direction in the space slightly different from the last one)
then she could have find another living planet.

Sometimes the signal can be weak, sometimes the signal can be strong, and sometimes the signal can
be static (this will be represented by a negative integer). they will variate every minute, as the object
points to another direction slightly different from the last one.

Your task is simple, given the N signals Andreina needs to discover and the maximum interval of K
minutes to do it, output if she found or not a planet.

INPUT:
The first line of the test data will start with an integer T representing the T test cases, then, T cases will
follow, each of the cases starts with three integers N, K and C denoting the number of signals to find a
planet, the maximum minutes that Andreina can use to find the planet and C signals test that were
evaluated.

OUTPUT:
You must output the string "Scenario #i: ", where i is the test case you are evaluating, followed by the
string "We are not alone" if Andreina finds another planet, otherwise print "Rainbowland is our home"

SAMPLE DATA:

INPUT

OUTPUT

Scenario #1: Rainbowland is our home

626

Scenario #2: We are not alone

123123

Scenario #3: We are not alone

636
123321
326
111211

CONSTRAINTS:

1 <= T <= 10

Small input (30%):


1 <= C <= 1000
1 <= K <= C
-1000 <= N <= 1000
-1000 <= Ni <= 1000

Large input (70%):


1 <= C <= 10^6
1 <= K <= C
-10^9 <= N <= 10^9
-10^9 <= Ni <= 10^9

Added by: David Moran


Date:
2012-06-19
Time limit: 1s-5s
Source limit:50000B
Cluster:
Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: Own Problem used for the RPL Warm-up session

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

11734. Take & Run


Problem code: RPL_T2

Take & Run is an important game of the Rainbowland Olympiads, consists in a large rectangle, in
each grid of the rectangle there is a single natural number, every athlete takes their position and then
the referee announces a random number (that is written on some grid of the large rectangle), all the
athletes must search the number and when some of them find it, the athlete must return at full speed to
the line to win.

Marge is questioning this game, she says that a pattern can be discovered as all the numbers are sorted
along the rectangle grids, Marge wants to win the Olympiads, and the help of third persons is allowed
in Rainbowland, she requests your help and she will give you all the numbers written on the grid of the
rectangle, it is known that the number at [0,0] < [0,1] < ... < [0,M] < [1,M] < ... < [N,M]. Where the
left number stands for the rows and the right one for the columns (the format is [R,C]).

INPUT:
The first line of the test data will start with an integer T representing the T test cases, then, an integer
N and M will come, then, NxM numbers will follow, meaning that in the next N lines there will be M
numbers representing the number located on the grid, after that, Q requests will come, each requests
consist on a natural number P that exists somewhere over the rectangle.

OUTPUT:
You must output the string "Scenario #i:", where i is the test case you are evaluating, a blank line, and
then, the position [R,C] where the natural number given in the request is located.

Print a blank line between test cases

SAMPLE DATA:

INPUT

OUTPUT

Scenario #1:

33

22

123

21

456

789

Scenario #2:

34

22

4
34
298 388 641 642
643 644 645 646
777 888 998 999
2
999
644

CONSTRAINTS:

1 <= T <= 10

Small input (30%):


1 <= {N,M} <= 100
1 <= Number on the grid <= 10^9

1 <= Q <= 100

Large input (70%):


101 <= {N,M} <= 2000
1 <= Number on the grid <= 10^9
1 <= Q <= 10000

It is guaranteed that every number on the grid will be different from each other.
Added by: David Moran
Date:
2012-06-19
Time limit: 0.349s-2s
Source limit:50000B
Cluster:
Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: Own Problem used for the RPL Warm-up session

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

12054. Cipher
Problem code: OPC2408B
Because having a problem statement is too mainstream...:P
Hint: Observe the sample input and output

Input
Contains few test cases with each test case containing a string in a seperate line.String will consist of
lowercase alphabets. (a-z) only and strlen(string) <=500
For taking input read till EOF.
An example of how to read strings till EOF:
while(gets(string))
{
/*process string*/
}

Score is the length of your code. (Smaller the code length,better the score)

Output
For each test case output a single string containing the answer

Example
Input:
lolo
whoami
Output:
orororor
zkrdpl

Added by: bashrc is back


Date:
2012-08-24
Time limit: 1s
Source limit:50000B
Languages: All

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

12189. Tropical Garden


Problem code: IOI11GRD
http://www.ioi2011.or.th/hsc/tasks/EN/garden.pdf

Input
Input description...

Output
Output description...

Example
Input:
etc.
Output:
etc.

Added by: Ziad Ouf


Date:
2012-09-04
Time limit: 1s
Source limit:50000B
Languages: All
Resource: IOI 2011

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

12263. GELO
Problem code: T8GELO

Deskripsi
Budi mempunyai seorang adik perempuan. Ternyata dia suka bermain bongkar pasang. Merek bongkar
pasang yang terkenal sampai sekarang adalah "gelo". Dia mempunyai buah gelo, di mana gelo ke-i
berukuran . Gelo seperti ini mempunyai buah "kancing" pada permukaan dan buah lubang pada dasar
gelo. Kancing dan lubang ini yang akan dapat membuat dua buah gelo saling "menempel". Dua buah
gelo dikatakan "menempel" jika minimal salah satu kancing gelo yang satu masuk ke lubang-lubang
gelo yang lain. Selain itu, dua buah gelo yang menempel harus berorientasi sejajar atau tegak lurus
satu sama lain. Sebagai contoh, jika , gelo ke- akan berbentuk seperti:

Dia ingin membangun sebuah bangunan dengan seluruh gelo tersebut. Gelo-gelo yang membentuk
bangunan tersebut haruslah saling terhubung satu sama lain. Dua buah gelo dan dikatakan terhubung
jika terdapat barisan gelo sehingga untuk setiap , gelo menempel dengan gelo .
Sayangnya, karena adik Budi masih kecil, dia tidak bisa mencapai tempat-tempat yang tinggi. Jadi,
adik Budi harus menyusun gelo-gelonya sedemikian sehingga tinggi bangunan yang dibentuk adalah
sekecil mungkin. Diberikan ukuran-ukuran gelo yang ada, tugas Anda adalah membantu adik Budi
mencari tahu berapa tinggi bangunan minimal yang mungkin dibentuk. Dalam hal ini Anda dapat
mengasumsikan ruang bermain adik Budi sangat luas, sehingga kita tidak peduli berapa lebar

bangunan yang dibentuk.

Format Masukan
Baris pertama berisi sebuah bilangan bulat , yang menyatakan jumlah kasus uji.
Tiap kasus terdiri dari dua baris. Baris pertama berisi , yang menyatakan jumlah gelo yang tersedia.
Baris kedua berisi buah bilangan bulat, , yang menyatakan ukuran dari tiap gelo yang telah dijelaskan
di atas.

Credit to http://lego.wikia.com for the picture above

Format Keluaran
Keluaran terdiri dari satu baris tiap kasus uji, yaitu berisi tinggi minimal bangunan yang mungkin
dibentuk.

Contoh Masukan Contoh Keluaran


2

10
4
1224

Penjelasan

Gambar di atas menjelaskan bagaimana bangunan dengan tinggi 2 dapat dibentuk untuk kasus uji
kedua (warna dibedakan agar batas antara gelo jelas).

Batasan
1 <= T <= 30.
1 <= N <= 100000 (10^5).
1 <= a_i <= 100000 (10^5).

Batasan waktu adalah 1 detik, dan batasan memori adalah 16 MB.


Added by: Aufar Gilbran
Date:
2012-09-22
Time limit: 2s
Source limit:50000B
Languages: All

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

12264. Mobil Ajaib


Problem code: T8MOBIL

Deskripsi
Budi mempunyai sebuah mobil ajaib. Mobil tersebut tidak membutuhkan bensin untuk berjalan.
Sebaliknya, untuk setiap kilometer yang ditempuh, bensin di mobil tersebut akan bertambah satu liter
secara otomatis. Sayangnya tangki bensinnya hanya dapat menampung liter bensin, sehingga jika
bensin di tangki sudah mencapai liter, bensinnya tidak akan bertambah lagi sampai bensinnya
dikurangi.
Suatu hari, Budi harus pergi ke kota yang berjarak kilometer dari rumahnya. Budi pergi dengan tangki
yang tidak terisi sama sekali (tentunya dia tidak perlu khawatir). Di sepanjang perjalanan, Budi akan
bertemu dengan orang yang sedang membutuhkan bensin. Namun, mereka memberi persyaratan
kepada Budi. Setiap orang tersebut ingin membeli seluruh bensin yang ada pada tangki. Jika tangki
tersebut penuh (berisi liter), maka orang ke- akan membayar sebanyak . Sebaliknya, jika tangki
tersebut tidak penuh, walaupun berisi liter, orang tersebut hanya mau membayar sebanyak . Lucunya,
orang ini akan tetap membayar sebanyak walaupun hanya ada satu liter di tangki bensin Budi (tapi
tidak jika tangkinya kosong). Tentunya, untuk semua .
Perlu diingat bahwa medan yang akan ditempuh Budi sangatlah berat. Jadi selama perjalanannya, Budi
tidak bisa memutar balik arah mobil ajaibnya, walaupun dengan begitu, Budi akan mendapatkan
bensin lebih. Selain itu, Budi tidak dapat mengurangi bensinnya dengan cara apapun, kecuali dengan
menjualnya kepada orang tersebut.
Karena Budi telah mempersiapkan perjalanan ini jauh-jauh hari sebelumnya, dia tahu persis tentang
segala medan yang akan ditempuhnya. Bahkan dia telah mengetahui nama-nama dari orang yang akan
dia temui, posisi di mana Budi akan bertemu dengannya, serta nilai dari dan .
Berbekal data yang akan diberikan oleh Budi, tugas Anda sekarang adalah untuk membantu Budi
untuk mencari tahu berapa uang paling banyak yang akan Budi peroleh dari hasil penjualan bensin.

Format Masukan
Baris pertama berisi tiga buah bilangan bulat, yaitu , , dan , yang berturut-turut menyatakan banyaknya
orang, jarak yang harus Budi tempuh, dan kapasitas dari tangki bensin mobil Budi.
Kemudian input akan diikuti oleh baris yang masing-masing berisi tiga buah bilangan bulat, , , dan .
menyatakan posisi bertemu Budi dengan orang ke-, dihitung dari rumah Budi; dan menyatakan harga
yang ditawarkan orang ke-, seperti yang telah dijelaskan di atas.

Input akan diurutkan berdasarkan dari yang terkecil ke yang terbesar.

Format Keluaran
Tuliskan uang paling banyak yang dapat Budi peroleh dari hasil penjualan bensin.

Contoh Masukan Contoh Keluaran


2 10 5

100

5 20 10
8 100 1

Penjelasan
Karena harga yang ditawarkan oleh orang kedua lebih tinggi, maka Budi tidak akan menjual bensinnya
kepada orang pertama, melainkan hanya kepada orang kedua.

Batasan
1 <= N <= 100000 (10^5 ).
2 <= X <= 1000000000 (10^9 ).
1 <= L <= 1000000000 (10^9 ).
0 < P_i < X.
0 <= B_i < A_i <= 1000000 (10^6 )

Batasan waktu adalah 1 detik, dan batasan memori adalah 64 MB.


Added by: Aufar Gilbran
Date:
2012-09-22
Time limit: 1s
Source limit:50000B
Languages: All

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

12265. Piano
Problem code: T8PIANO

Deskripsi
Diam-diam, ternyata dulunya Budi adalah seorang pianis handal. Dia mulai belajar secara otodidak
sejak umurnya masih tiga tahun, dan sudah melaksanakan resital pada umur 7 tahun! Namun sayang
sekali kesibukannya membuat dia tidak bermain piano untuk waktu yang lama, sehingga dia sudah
agak lupa caranya sekarang.
Namun, hari ini Budi ingin mencoba lagi keahliannya yang satu itu. Dia ingin memainkan sebuah lagu
sepanjang nada. Sayang sekali, dia sudah lupa sebagian besar dari lagu tersebut. Tapi dia ingat, untuk
setiap dua nada yang berurutan, nada manakah yang lebih tinggi di antara kedua nada tersebut; apakah
nada pertama, kedua, atau keduanya sama. Berdasarkan ingatannya ini, bantulah Budi untuk kembali
mengingat lagu tersebut.
Meskipun bisa banyak sekali kemungkinan lagu yang mungkin dibentuk dengan informasi tersebut,
tugas Anda sangatlah mudah. Anda hanya harus menentukan berapa nada berbeda minimal yang harus
dimainkan. Dengan kata lain, Anda harus mencari sebuah bilangan bulat terkecil, sehingga terdapat
sebuah lagu yang cocok dengan ingatan Budi tersebut, dan lagu tersebut memiliki tepat nada yang
berbeda. Dalam hal ini, "lagu" adalah rangkaian barisan buah nada, dan dapat diasumsikan di sini
bahwa "nada" adalah sebuah bilangan bulat.
Anda akan diberikan sebuah string dengan panjang yang hanya berisi karakter <, =, atau >.
Karakter ke- pada string tersebut menunjukkan hubungan antara nada ke- dan nada ke-. Jika
karakternya <, berarti nada ke- lebih rendah dari nada ke-. Jika karakternya =, maka kedua tersebut
sama, dan jika karakternya >, nada ke- lebih tinggi daripada nada ke-i. Sebagai contoh, string yang
sesuai dengan lagu 1.1.5.5.6.6.5... adalah "=>=>=<".

Format Masukan
Baris pertama berisi bilangan bulat , yang menyatakan banyaknya kasus uji.
Tiap kasus uji akan terdiri dari dua baris. Baris pertama berisi bilangan bulat , dan baris kedua berisi
sebuah string dengan panjang yang menyatakan hubungan antar nada seperti yang telah dijelaskan di
atas.

Format Keluaran
Untuk tiap kasus uji, tuliskan sebuah bilangan bulat yang menyatakan banyak nada berbeda minimal
yang harus dimainkan.

Contoh Masukan Contoh Keluaran


1

14

=>=>=<<=<=<=<
8
=><><<>

Penjelasan
Lagu 1.1.5.5.6.6.5...4.4.3.3.2.2.1... adalah salah satu contoh lagu yang cocok dengan string pada kasus
uji pertama, dan membutuhkan 6 nada berbeda. 6 adalah bilangan terkecil yang memenuhi.
Sementara itu, pada kasus uji kedua, lagu 1...1...4...1...4...1...5?...1... cocok dengan string tersebut (5?
adalah nada 5 rendah).

Batasan
1 <= T <= 10.
1 <= N <= 300000.

Batasan waktu adalah 1 detik, dan batasan memori adalah 16 MB.


Added by: Aufar Gilbran
Date:
2012-09-22
Time limit: 1s
Source limit:50000B
Languages: All

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

12266. String Periodik


Problem code: T8STPD

String Periodik
Deskripsi
Sebuah string dikatakan "periodik" jika terdapat sebuah string lain yang berulang-ulang secara teratur
pada string tersebut lebih dari satu kali. Secara formal, sebuah string disebut periodik jika terdapat
string dan sebuah bilangan asli m>1 sehingga
s= t+t+...+t (m kali).
Sebagai contoh, string "ababab" adalah string periodik, karena kita dapat memilih dan sehingga syarat
di atas terpenuhi; string "xyzxyz" juga periodik dengan dan . Namun, string "abcabcd" dan "pqrpqrpq"
keduanya bukan merupakan string periodik.
Tentukan banyaknya string yang periodik, jika diketahui bahwa panjang string tersebut adalah dan
terdapat pilihan karakter yang dapat digunakan.

Format Masukan
Masukan berisi dua buah bilangan bulat, dan , yang berturut-turut menyatakan panjang string dan
banyak pilihan karakter yang dapat digunakan.

Format Keluaran
Tuliskan banyaknya string yang memenuhi deskripsi di atas, modulo 1000000007 .

Contoh Masukan Contoh Keluaran


62

10

999999999 99

559079884

Penjelasan
Untuk kasus uji pertama, misalkan karakter yang diperbolehkan adalah a dan b. Maka, string
periodik yang memenuhi ada 10 buah, yaitu "aaaaaa", "ababab", "aabaab", "abaaba", "abbabb",
"baabaa", "babbab", "bbabba", "bababa", "bbbbbb".

Batasan
1 <= N <= 1000000000 (10^9).
1 <= K <= 100.

Batasan waktu adalah 1 detik, dan batasan memori adalah 32 MB.


Added by: Aufar Gilbran
Date:
2012-09-22
Time limit: 1s
Source limit:50000B
Languages: All

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

12267. Shadow
Problem code: T8SHADOW

Shadow
Deskripsi
Budi akhirnya memutuskan untuk pindah rumah! Dia telah menemukan pekerjaan yang cocok di sana
dan memutuskan untuk tinggal di kota itu. Rumah Budi yang baru ini berbentuk persegi panjang.
Untuk lebih jelasnya, rumah Budi adalah persegi panjang dengan titik-titik (0,0), (w,0), (w,h), dan
(0,h). Budi memiliki banyak sekali perabotan, namun yang telah dia pindahkan hanyalah sebuah lampu
dan N buah lemari. Lampu tersebut dapat dianggap sebagai sebuah titik, sedangkan lemari-lemari Budi
dapat dianggap sebagai sebuah segmen garis. Karena proses pindah rumah Budi belum selesai, tentu
saja barang-barang Budi masih berantakan. Lampunya ia letakkan di titik (xl,yl), dan lemari ke-i
adalah sebuah segmen yang menghubungkan titik (x1i,y1i) dan (x2i,y2i).

Ketika Budi menyalakan lampu, tentunya pada dinding rumah Budi akan terbentuk bayangan karena
cahaya lampu terhalang oleh lemari. Lebih jelasnya, sebuah titik pada dinding akan terbentuk
bayangan jika dan hanya jika segmen garis yang menghubungkan titik tersebut dengan lampu,
memotong minimal satu dari N buah lemari yang ada. Dua segmen garis dikatakan berpotongan jika
dan hanya jika ada minimal satu titik yang termasuk pada kedua segmen garis tersebut.

Melihat hal ini, tiba-tiba Budi penasaran untuk menghitung berapa panjang tembok yang terbentuk
bayangan. Namun, seperti yang Anda ketahui, Budi sedang sangat sibuk mengurusi pindahan
rumahnya karena masih banyak sekali barang-barang yang harus dipindahkan. Untung saja ada Budi
tahu bahwa Anda akan dengan senang hati membuatkan Budi sebuah program yang dapat menghitung
panjang bayangan yang terbentuk.

Format Masukan
Baris pertama akan berisi lima buah bilangan bulat, yaitu N, w, h, xl, dan yl seperti yang telah
dijelaskan di atas. Kemudian untuk i=1..N, baris ke-(i+1) akan berisi empat buah bilangan bulat, x1i,
y1i, x2i, y2i yang merupakan posisi dari lemari ke-i.

Format Keluaran
Keluarkan dalam sebuah baris, yaitu panjang bayangan yang akan terbentuk pada tembok-tembok
rumah Budi. Bulatkan jawaban ini hingga tiga angka di belakang koma.

Contoh Masukan Contoh Keluaran


26442

6.000

2223

5241

Penjelasan

Daerah berwarna hitam adalah bayangan yang terbentuk, daerah kuning adalah cahaya yang
membentuk bayangan,titik berwarna merah adalah lampu, dan garis berwarna coklat adalah lemari.

Batasan
1 <= N <= 1000.
1 <= w,h <= 1000000.

0 <= x <= w; 0 <= y <= h; untuk semua titik (x,y) yang muncul pada masukan

Tidak akan ada dua lemari yang saling berpotongan, dan lampu tidak akan ada pada salah satu
lemari.

Batasan waktu adalah 1 detik, dan batasan memori adalah 16 MB.

Added by: Aufar Gilbran


Date:
2012-09-22
Time limit: 1s
Source limit:50000B
Languages: All

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

12601. PiggybankRI
Problem code: WARAKOM
Ramy, a college tutor interested in algorithms decided to help out his students in problem solving by
giving them an easy problem to solve to practice for their algorithms exam. Below is the description of
the problem that Ramy is facing.
Ramy has a piggy bank with a certain capacity m and containing an amount q. He is going to use it for
saving money and paying his debts for n days. Each day he can either add an amount to it or remove
the same amount from it. Mr ramy can not exceed the maximum capacity of his piggy bank and
neither can he withraw an amount that is not there. He is now wondering what is the maximum amount
he can have in his piggy bank after n days. Can you help Ramy with his problem???
You will be given a list of the amounts he can add or withdraw and you are required to tell him the
maximum amount he can have . If its not possible for him to do the operations tell him that.

Input
The first line will start with a number t, the number of test cases (t <= 10).
Each test case will consist of 2 lines. The first line contain n, q, m (as explained in the problem) n <=
50,
0 <= q < m <= 1000.
The next line contains n space separated values ai 0 < i <= n, 0<= ai <= m.
Please note that in the test files there are no empty lines like the ones shown below.

Output
For each test case print 1 number in a separate line which is the maximum amount Mr. Ramy can have
in his piggy bank after n days or -1 if he cant do it.
Please note that you should output the results without any empty lines, unlike the format given in the
output. No seperate empty lines should be present in your output.

Example
Input:

2
3 5 10
5 3 7
4 8 20
15 2 9 10
Output:
10
-1

Added by: Ramy


Date:
2012-10-31
Time limit: 1s
Source limit:50000B
Cluster:
Pyramid (Intel Pentium III 733 MHz)
Languages: All

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (oi)

12879. INFORMACIJE
Problem code: INFORMAC
Mirko was bored, so he took a piece of paper and wrote down a sequence A of length N, which
contains each positive integer between 1 and N, inclusive, exactly once. After that, he took another
piece of paper and wrote down M descriptions of the sequence A.

Each description has one of the following formats:


1 x y v - the largest number in positions between x and y (inclusive) equals v
2 x y v - the smallest number in positions between x and y (inclusive) equals v

Then Slavko came, saw, and stole the first paper. Mirko is desperate and has asked you to find
some sequence matching the descriptions, not necessarily equal to the original sequence.

INPUT:
The first line of input contains two positive integers, N (1 <= N <= 200), the length of the
sequence, and M (0 <= M <= 40 000), the number of descriptions.
Each of the following M lines contains a description as described above.

OUTPUT:
The first and only line of output must contain a sequence of N space-separated positive integers
(matching the descriptions and containing all positive integers from 1 to N), or -1 if no such sequence
exists.

SAMPLE TESTS:

Input Output
32
123
1111
2222

42

-1

1111
2341

52

12345

1233
2454

Added by:
Date:
Time limit:
Source
limit:
Cluster:

Alex & Friends


2012-12-02
1s
50000B

Pyramid (Intel Pentium III 733 MHz)


All except: AWK CLOJ ERL F# GO NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n
Languages:
SCALA SED TCL
Resource: COCI 2012-2013

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

12942. Spy Office


Problem code: RIOI_3_3

Tyrion Lannister is very smart man, and he knows importance of being informed, especially when you
are important man behind the throne. So Tyrion placed one spy in every major city of Seven
Kingdoms.
But long before there internet existed, information was carried by foot, so it was very important to
organise your spies correctly.
Seven Kingdoms can be imagined as straight road with N cities on it. Cities are numbered from 1 to N
inclusive. Tyrion is located in city 1. We know distance between 2 neighbouring cities, and it is given
in array D. Distance between city i and i+1 is D[i] kilometers.
After spy in city i hears something important he starts preparing for departure. He needs exactly T[i]
days to prepare. After that he starts traveling to city 1 with constant speed V[i] kilometers per day.
After he enters some city in between, he can either tell his news to spy located in that city, after which
that spy repeats same steps, or he can continue traveling.
Tyrion needs to know what is smallest amount of time needed for each spy to reach Kings Landing
(city 1 where Iron Throne is located).
Tyrion Lannister is very smart man, and he knows importance of being informed, especially when
you are important man behind the Iron Throne. So Tyrion placed one spy in every major city of Seven
Kingdoms.
But long before internet existed, information was carried by foot, so it was very important to
organise your spies optimally.
Seven Kingdoms can be imagined as straight road with N cities on it. Cities are numbered from 1 to
N inclusive, with cities i and i+1 being neighbouring. Tyrion is located in city numbered 1, called
Kings Landing. We know distance between two neighbouring cities, and it is given in array D.
Distance between city i and i+1 is D[i] kilometers.
After spy in city i hears something important he starts preparing for departure. He needs exactly T[i]
days to prepare. After that he starts traveling to Kings Landing with constant speed V[i] kilometers
per day. Spies never travel away from Kings landing, that is, at every point in time, they try to reduce
their distance to Kings Landing. After he enters some city in between, he can either tell his news to
spy located in that city, after which that spy repeats same steps, or he can continue traveling without
telling anything to that spy.
Tyrion needs to know what is smallest amount of time needed for information from every city to
reach Kings Landing (city 1 where Iron Throne is located).

N <= 100000 ( in 60% of tests N <= 1000 )


0 < D[i], T[i], V[i] <= 100

Input
In first line of the input, there is integerN(number of cities). Second line consists of N-1 integers
describing array D. N-1 lines follow each containing T[i] and V[i].

Output
Output N-1 numbers, smallest number of days for each city. Also note, that solutions are in fact
decimal numbers, but you just output integers.

Example
Input:
7
2 9 7 2 2 10
6 6
9 2
9 10
2 3
1 1
6 6
Output:
6
14
11
9
12
11
Note : Actual results are decimal numbers, like shown below. But to avoid precision errors, output rounded numbers with 0 decimal places.

Use printf("%.0lf") formatting to output your results


6.33333
14.50000
10.80000
8.66667
11.66667
11.33333

Added by: Buda IM


Date:
2012-12-07
Time limit: 1s
Source limit:50000B
Cluster:
Pyramid (Intel Pentium III 733 MHz)
Languages: All

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

12947. Cheaters
Problem code: RIOI_3_4

Mirko and Slakvo are known to play some games from time to time.
N numbers appear on the screen in one minute intervals. A[1] will appear in first minute, and A[N]
will appear in N-th minute. Screen has capacity of K numbers, that means that in each point in time, on
the screen can be at most K numbers. After new number appears, number that appeared K minutes
ago, if such exists, disappears.
Aim of the game is to tell minimal absolute difference 2 distinct numbers on the screen in every
minute. Slavko is very good at this game, can you help Mirko and tell him optimal results
Mirko and Slavko are known to play some games from time to time.
N numbers appear on the screen in one minute intervals. A[1] will appear in first minute, and A[N]
will appear in N-th minute. Screen has capacity of K numbers, that means that in each point in time,
on the screen can be at most K numbers. After new number appears, number that appeared K minutes
ago, if such exists, disappears.
Aim of the game is to tell minimal absolute difference 2 distinct numbers on the screen in every
minute. Slavko is very good at this game, help Mirko and tell him optimal results.

2 <= N <= 100 000


2 <= K <= 100 000
1 <= A[i] <= 100 000

Input
In the first line there are two numbers N and K, in the next line there are N integers describing array A.

Output
Output N-1 number, optimal result in each minute of the game.

Example
Input:
6 4
6 2 4 1 10 9
Output:
4 2 1 1 1
Explanation :
1st
2nd
3rd
4th
5th
6th

minute,
minute,
minute,
minute,
minute,
minute,

on
on
on
on
on
on

screen
screen
screen
screen
screen
screen

{6}
{6,
{6,
{6,
{2,
{4,

2}, |6-2| = 4
2, 4}, |6-4| = |4-2| = 2
2, 4, 1}, |2-1| = 1
4, 1, 10}, |2-1| = 1
1, 10, 9}, |10-9| = 1

Added by: Buda IM


Date:
2012-12-08
Time limit: 1s
Source limit:50000B
Cluster:
Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: Own problem

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

13025. Making the Grade


Problem code: NOINCDEC
A straight dirt road connects two fields on FJs farm, but it changes elevation more than FJ would like.
His cows do not mind climbing up or down a single slope, but they are not fond of an alternating
succession of hills and valleys. FJ would like to add and remove dirt from the road so that it becomes
one monotonic slope (either sloping up or down).
You are given N integers A 1 , ... , A N (1 <= N <= 2,000) describing the elevation (0 <= A i <=
1,000,000,000) at each of N equally-spaced positions along the road, starting at the first field and
ending at the other. FJ would like to adjust these elevations to a new sequence B 1 , . ... , B N that is
either nonincreasing or nondecreasing. Since it costs the same amount of money to add or remove dirt
at any position along the road, the total cost of modifying the road is
|A 1 - B 1 | + |A 2 - B 2 | + ... + |A N - B N |
Please compute the minimum cost of grading his road so it becomes a continuous slope. FJ happily
informs you that signed 32-bit integers can certainly be used to compute the answer.
Input
* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains a single integer elevation: A i
Output
* Line 1: A single integer that is the minimum cost for FJ to grade his dirt road so it becomes
nonincreasing or nondecreasing in elevation.
Sample Input
7
1
3
2
4

5
3
9
Sample Output
3

Added by: SPb ITMO


Date:
2012-12-19
Time limit: 1s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: Usaco FEB08

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

13561. Kart
Problem code: V_AYP1_A
Pepe is a famous karting racer, but he forgot to tell his brother, Yonkleiderson, the number of his car
so that could register in the competition, if Yonkleiderson fails to register his brother in the
competition, his brother will be automatically disqualified. In a desperate moment, Yonkleiderson
remembered that the number of the racers car is given according to the starting position in the race,
and he knows the position (i,j) where his brothers car is, the problem, then, is pretty simple, given N
and M, that would be the size in a matrix and two values i,j that are the position at the matrix, Pepe
wish to know what value could be in that position if the matrix is filled row by row starting from 1
until N*M.
Example
N= 3, M=4
1234
5678
9 10 11 12
i=0 , j=3 the number is 4
i=2 , j=2 the number is 11
i=1, j=0 the number is 5
Input details:
Four integers N,M,I,J representing the size of the matrix and the indexes i,j to search the car

Output details:
The number of the car as previously described in the statement.

INPUT

OUTPUT

3403

Constraints
0 < N,M < 10000
0 <= i < N
0 <= j < M

Added by: Venezuelan Programming League


Date:
2013-02-02
Time limit: 5s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.3.2 C++ 4.0.0-8

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

13562. Knight Circuit


Problem code: V_AYP1_B
Luis is a great chess player and as such, he likes to test any kind of game that he imagines with the
chess pieces, he just created a game pretty interesting consisting in the moves of a knight over all the
possible cell whenever he can in a matrix sized board WxH, being in the position (x,y) of the matrix,
the knight can move to (x+2,y+1), (x+1,y+2), (x-2,y+1), (x+2,y-1), (x-1,y+2), (x-1,y-2), (x-2,y-1),
(x+1,y-2).

The knight can start from any cell in the matrix WxH, the knight may never leave the matrix and it can
step an arbitrarily number of times the same cell visited, however, you shouldnt count the repeated
step.

Input details:
T as an integer representing the number of cases, then, in the next T lines, two integers W and H
representing the width and the height of the matrix.

Output details:
A single number representing the number of cells visited by the knight in the matrix.

INPUT

OUTPUT

11

15 2

10000

100 100


Constraints:
1 <= W <= 100,000
1 <= H <= 100,000

Added by: Venezuelan Programming League


Date:
2013-02-02
Time limit: 5s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.3.2 C++ 4.0.0-8

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

13563. Iridium
Problem code: V_AYP1_C
A group of programmers from Iridium develops a multiplatform communications equipment that will
connect various offices of the Company for which they work. They want to calculate the time (in ms)
that a packet of information will need to travel from origin to destiny through their network, given the
size in Bytes of the packet and the means through which it will travel.
The network that interconnects the company is comprised of three different technologies. The first is
optic fiber (propagation speed: 0.0769 ms/m), Satellite link (0.033 ms/m) and copper wire (0.0109
ms/m). These values were estimated from the specifications of the hardware that comprises this system
and are considered correct. To represent each kind of connection a character will be used: Fiber optic
(F), Satellite (S) and Copper wire (T). The bandwidths of the links vary through the system. It is
necessary to calculate the time 1 bit will need for it to be transmitted through the links to its destiny.
After calculating the propagation time of 1 bit, according to the data introduced by the user of each
link, it will be necessary to calculate the propagation time of all the packet. As it is well known 1 Byte
= 8 bits, giving us the option of transforming the packet size given in Bytes to bits and multiplying the
propagation time by that amount of bits.
The program must be able to calculate several times, as the studies for the system may be many.
Input details:
The first line of each test case will contain an integer K, which will represent the size in bytes of each
packet that will be sent through the link. An undetermined amount of lines will follow, each containing
a single string (no spaces), formed by a character C and the distance D in meters of that link. Stopping
the input of such lines when C acquires the value *. The program ends when K=0.
Output details:
For each test case the output will be the time in ms (milliseconds) taken for the transmission of each
packet.

INPUT

OUTPUT

100

2153.2

F30
S10
T5
*
0

Constraints:
0<= K<100000000
C = {F, S, T, *}
0<D<100000000
Added by: Venezuelan Programming League
Date:
2013-02-02
Time limit: 15s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.3.2 C++ 4.0.0-8

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

13564. Time
Problem code: V_AYP1_D
Heidi has a discrete analog clock in the shape of a circle, as the one in the figure. Two hands rotate
around the center of the circle, indicating hours and minutes. The clock has 60 marks placed around its
perimeter, with the distance between consecutive marks being constant.

The minute hand moves from its current mark to the next exactly once every minute. The hour hand
moves from its current mark to the next exactly once every 12 minutes, so it advances five marks each
hour.

We consider that both hands move discretely and instantly, which means they are always positioned
exactly over one of the marks and never in between marks.

At midnight both hands reach simultaneously the top mark, which indicates zero hours and zero
minutes. After exactly 12 hours or 720 minutes, both hands reach the same position again, and this
process is repeated over and over again. Note that when the minute hand moves, the hour hand may
not move; however, when the hour hand moves, the minute hand also moves.

Heidi likes geometry, and she likes to measure the minimum angle between the two hands of the clock
at different times of the day. She has been writing some measures down, but after several years and a
long list, she noticed that some angles were repeated while some others never appeared. For instance,
Heidis list indicates that both at three oclock and at nine oclock the minimum angle between the two
hands is 90 degrees, while an angle of 65 degrees does not appear in the list. Heidi decided to check,
for any integer number A between 0 and 180, if there exists at least one time of the day such that the
minimum angle between the two hands of the clock is exactly A degrees. Help her with a program that
answers this question.

Input details:

An integer T representing the test cases, then, T lines will follow. Each test case is described using one
line. The line contains an integer A representing the angle to be checked.

Output details:
For each test case output a line containing a character. If there exists at least one time of the day such
that the minimum angle between the two hands of the clock is exactly A degrees, then write the
uppercase letter Y. Otherwise write the uppercase letter N.

INPUT

OUTPUT

90

65

66

67

128

180

Warning: There are no blank lines between numbers nor in the input or output.
Constraints:
0<=A<=180
Added by: Venezuelan Programming League
Date:
2013-02-02
Time limit: 5s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: All

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

13565. Secret
Problem code: V_AYP1_E
Petra Pobre wishes to open a secret room in her school, but the security system consists in a puzzle
that is formed by a matrix of size NxM, then, for each column you will have N numbers in any order,
to solve the puzzle, you must observe a particular number K that can be found besides the matrix size,
to open the door, Petra needs to shout the minimum moves that she needs to make so that every
observed number K found in every column is aligned at the first row.
Every column in the matrix can be moved up or down, by instance.
N=4 M=3 K=2;
123
312
284
335
In the first column the number K moves two units up, in the second column the number is in position
and in the last column it goes one unit up, therefore, the result is 3.

Input details:
There are three integers to read; N,M and K, everyone corresponding to the number of columns and
rows in the matrix with the number to move, the next N lines will contain M integers separated by a
single space representing the number in a position of the matrix (i,j)

Output details:
You should print the minimum moves so that the condition described previously is satisfied.

INPUT

OUTPUT

432

123
312
284
335

Constraints:
0 < N,M < 1500
0 < K < 2000
Added by: Venezuelan Programming League
Date:
2013-02-02
Time limit: 7s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.3.2 C++ 4.0.0-8

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

13566. A little help for Yon


Problem code: V_AYP1_F
Yonkleiderson is a very lazy student which really dislikes carrying his own books. He often asks his
friends for help, they carry a certain book, a certain distance for a Price. Yonkleiderson must take N
books and for each book the position and cost per meter will be given. He needs to calculate how
much it will cost him to take the books from one place to the other with Yonaikers help. Although he
can only use Yonaikers help once. Yonkleiderson has a limited amount of money and he is not always
able to pay Yonaiker to take all his books. Yonkleiderson must calculate what is the greatest amount of
books Yonaiker can carry.
Yonaiker once he picks up a book will carry it together with the rest he picks up along the way, until
the final destination where he will leave all the books.
Input details:
The first line will contain two integers N and V, N represents the number of books to be picked up, V
is the amount of money Yonkleiderson has. N lines will follow each with two integers B and C where
B represents the position of the books and C the cost per meter of each book.
Example;
N=4 V=20
20 2
22 5
30 8
32 1
For this test case the result is 1. Only one book can be taken by Yonaiker.
The book in position 20 cost until position 22 is 4: (22-20)*2= 2*2=4.
If you want help with the first until the third book we must remember that the second book will also be
taken: ((30-20)*2) +((30-22)*5) = 20 + 40 = 60.
The cost of taking the first book to the end: ((32-20)*2)+ ((32-22)*5) + ((32-30)*8) = 24+50+16=90

In the same way we start calculating from the second book, second to third: (30-22)*5=8*5=40,
second to fourth: ((32-22)*5)+((32-30)*8)= 50+16=66
Third to fourth: (32-30)*8= 16
We can observe the value of V is only 20 as such we can only pay Yonaiker for help in taking the first
book to the second or the book before last to the last.

Output details:
The output will consist of an integer which will show the maximum amount of books with which
Yonaiker can help Yonkleiderson.

INPUT

OUTPUT

4 20

20 2
22 5
30 8
32 1

Constraints:
0 < N < 100
0 < V < 5000000
0 < B < 300
0 < C < 20
Added by: Venezuelan Programming League
Date:
2013-02-02
Time limit: 5s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.3.2 C++ 4.0.0-8

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

13567. Very Triangular


Problem code: V_AYP2_A
Espanol
At school, Panchitos teacher has asked them to make a simple game that given the length of the sides
of a triangle, it can classify them as Isosceles, Scalene or Equilateral.
Help:
* Issceles: two sides of the same length.
* Scalene: all sides have different lengths.
* Equilateral: all sides are equal.
Input Details:
You should read three integers X, Y, Z be three lengths in the plane.
Output Details:
Only to print that kind of triangle is isosceles, scalene, or equilateral.

INPUT

OUTPUT

222

Equilateral

90 54 90

Isosceles

23 100 12

Scalene

Constraints:
0 <= X <= 10000000

0 <= Y <= 10000000


0 <= Z <= 10000000
Added by: Venezuelan Programming League
Date:
2013-02-02
Time limit: 3s-4s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.3.2 C++ 4.0.0-8

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

13568. Sub-matrix Average


Problem code: V_AYP2_B
EspanolDickie is learning the utilities of a matrix in the school, then the professor asked him to find the maximum submatrix in a matrix given, so that the average is maximum, we define the average in a sub...

3 2 3

4 9 8

1 8 9

The example matrix has 4 submatrix, these are { {0,0,1,1}. {0,1,1,2}, {1,0,2,1}, {1,1,2,2} } (The values given are the pair (row,column) for the leftmost top corner and the rightmost bottom corner), o...

For simplicity, we ask you to print the result with two decimal places, i.e. instead of printing 8.5 you should print 8.50, if there is any result with more than two, round it up, i.e. if the result i...

Input details:

You must read two integers N and M, representing, respectively, the matrix N and the submatrix M to take, after that, N lines with N integers separated by a space will come, each representing the posi...

Output details:

You should print the maximum average obtainable having in count that you should always form a submatrix of MxM in the bigger matrix N.

INPUT

OUTPUT

32

8.50

153
998
789

Constraints:

1 <= N <= 20

1 <= M <= N

Added by: Venezuelan Programming League


Date:
2013-02-02
Time limit: 4s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.3.2 C++ 4.0.0-8

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

13569. Magic
Problem code: V_AYP2_C
Espanol
A group of numbers which have the same value when added by row, column and diagonal are known
as magic groups. These groups are known to have the same amount of rows and columns. For
example:
|16|3 |2 |13|
|5 |10|11|8 |
|9 |6 |7 |12|
|4 |15|14|1 |
In this magic group the magical sum is 34 in rows, columns and diagonals. If the sum of one or two of
the diagonals don ?t match with the magical sum this group is considered semi-magical.
Following a much known practice, divide and conquer, we have developed a program that verifies that
the columns sum match, you will only have to verify the rows and both main diagonals sums match.

Input details:
The first line will contain an integer N indicating the size of the group. N lines follow with N integers
each having the numbers of the group. Groups will continue being read until N=0.

Output details:
The output line will indicate if the group (square) is magical (M), semi-magical(SM) or not magical
(NM).

INPUT

OUTPUT

SM

123

231
312
4
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
0

Constraints:
1 <= N <= 50

Added by: Venezuelan Programming League


Date:
2013-02-02
Time limit: 4s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.3.2 C++ 4.0.0-8

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

13570. Military
Problem code: V_AYP2_D
EspanolA military column of N soldiers, is training and marching, numbered as follows, when

six soldiers:

When an officer calls formation, they must act quickly to complete formation in K

columns indicated to them, for example if the officer indicates do training in 2 columns, would be as follows:

3 6

2 5

1 4

In the example above, soldier 5 when called to formation, would be in row 2 and

column 2.

Obviously the military must be very disciplined and always form in an orderly fashion,

Input details:

The first line will contain 2 integers, N,K, Followed by a X number of soldier. N will

always be exactly divisible by K.

Output details:

The row and column in which the soldier who was called to formation is in.

INPUT

OUTPUT

15 3

32

Constraints:

0<N<=1000000

0<K<=N

0<X<=N

the first soldiers w...

Added by: Venezuelan Programming League


Date:
2013-02-02
Time limit: 3s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.3.2 C++ 4.0.0-8

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

13571. Lazy Decision


Problem code: V_AYP2_E
EspanolSamuel is a pretty intelligent Young man. He recently completed high school and

His primary concern is not how good the university is but how close it is to his home

thanks to his high IQ he was given the opportunity of choosing which University he

as he really hates getting up early. Write a program that helps Samuel in this

wanted to continue his education in...

decision as it is a loss of his p...

Input details:

The first line of the input will have an integer T with the number of test cases, each

case will have an integer N indicating the number of universities that Samuel can choose. These universities wil...

Output details:

The output will contain three numbers X,Y,Z. X and Y represent the coordinates of

the closest university to Samuel ?s house, Z will represent the minimum distance to

the university. In case 2 univer...

INPUT

OUTPUT

112

2
00
11
22

Constraints:

0<T<10000

0<N<10000

0<xi<1000000

0<yi<1000000

Added by: Venezuelan Programming League


Date:
2013-02-02
Time limit: 4s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.3.2 C++ 4.0.0-8

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (main)

13572. Mirrors
Problem code: V_AYP2_F
EspanolDickie likes to play with mirrors on Sundays, and, as he gets bored very fast he decided to use a flash light in a room full of mirrors to see what happens, he saw a lot of lights crossing over the ro...

All the mirrors are located on the walls of the matrix

The direction will change according to the collision of mirrors, that is, if the direction is, by example, south-west and collides to the western wall, the light will change its direction to south-eas...

Input details:

You will read four integers H,W,I,J, corresponding, respectively, to the dimension of the matrix (HxW) and the initial position of the flashlight (I,J), after that, read a string S, the string S could...

Output details:

Output a pair of numbers (R,S), corresponding to the intersecting point of two light rays.

INPUT

OUTPUT

5 6 1 3 south-east 0 0

Explanation:

Beginning on (1,3) to the south-east, the light collides to (3,5), then, goes to the south-west when it collides in the southern wall (4,4), then it changes the direction to the north-west and then co...

Hint, answers for the other directions are:

south-west: 4 0

north-east: 1 3

north-west: 1 3

Constraints;

1 <= H,W <= 1000

0 <= I < H

0 <= J < W

S = { "south-east", "south-west", "north-east", "north-west" }

Added by: Venezuelan Programming League


Date:
2013-02-02
Time limit: 5s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.3.2 C++ 4.0.0-8

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

13737. Game of Life


Problem code: GMLIFE

Alice and Bob are playing a game of life, Alice is representing the evil character, and Bob is
representing the good character; the game requires the evil to make a ritual in order to rule the world;
Bob, being the good character, he tries to stop Alice from making this ritual.
The ritual consists of m gears, that can rotate in only one direction, that is clockwise, each with a
pointer pointing to one of its holes, and the ith gear containts n[i] holes; the configuration of the gears
was ready to make the ritual, but unfortunately for Alice, Bob then rotated the gears by some number
of pushes, precisely he pushed the i-th gear by a[i] holes, then he changed the system of the gears, and
made it with one global control for all the gears, so that the only move Alice can make is to push all
the gears at the same time, each by one hole. Since it will take too much time to complete the ritual,
Alice thought of bringing some workers to finish the task for her as soon as possible, given that they
all do the same amount of work.
Alice wants to know in how many ways can she do this.

Alice and Bob are playing a game of life, Alice is representing the evil character, and Bob is
representing the good character; the game requires the evil to make a ritual in order to rule the world;
Bob, being the good character, he tries to stop Alice from making this ritual.
The ritual consists of m gears that can rotate in only one direction, that is clockwise direction; each
gear has a pointer pointing to one of its holes; the i th gear containts n i holes; in order to make the
ritual, all the gears must be on their starting position. The configuration of the gears was ready to make
the ritual, but unfortunately for Alice, Bob rotated the gears by some number of pushes, precisely he
pushed the i th gear by a i holes, then he changed the system of the gears, and made it with one global
control for all the gears, so that the only move Alice can make is to push all the gears at the same time
by one hole for each gear. Since it will take too much time to complete the ritual, Alice thought of
bringing some workers to finish the task for her as soon as possible, given that they all do the same
amount of work. Alice wants to know in how many ways can she do this.
Its guaranteed that the minimum positive number of moves Alice can make, so it can restore the gears
from the current configuration to Bobs configuration again, will not exceed 10 14 ; and it is also
guaranteed that Bobs configuration isnt the original configuration.

Sample input 1, the first gear rotated clockwise by 2 pushes, and the second gear rotated clockwise by
5 pushes.

Input
For each input file, the first line contains a single integer m (1 <= m <= 10 3 ), the number of gears, and
each of the next m lines contains two integers, the i th line contain the two integers a i and n i space
separated (0 <= a i < n i < 10 14 ).
Output
For each test case, output a line containing a single integer, the number of ways to get an amount of
workers, such that each does the same amount of work so they can solve the ritual.
Example
Input:
2
2 3
5 7
Output:
5
Input:
2
2 6
3 4
Output:
0

In the first case, the ritual can be completed after 16 pushes, so Alice can bring 1, 2, 4, 8, or 16
workers. In the second case, the ritual cannot be completed.
Added by: Mostafa mahmoud
Date:
2013-02-13
Time limit: 1s-3s
Source limit:50000B
Cluster:
Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: Own Problem

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

13866. Discrete Roots


Problem code: DISCRT
In this problem, we try to compute discrete k th root modulo n; given n, k, a; find all the solutions for
x such that x k = a (mod n) and x is coprime with n.

Input
For each input file, there are 3 space seperated integers n, k, a.
n = p e for some odd prime p, integer e > 0; 0 <= a < n <= 10 9 , 0 <= k < phi(n), where phi is Eulers
totient function; the numbers n, a are coprimes.

Output
The first line of the output contains a single integer m, the number of solutions in the range [0, n - 1]
that are coprimes with n, followed by m lines that contain the m solutions in ascending order. It is
guranteed that m <= 10 4 .

Example
Input:
5 1 3
Output:
1
3

Added by: Mostafa mahmoud


Date:
2013-02-22
Time limit: 1s
Source limit:50000B
Cluster:
Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: http://acm.sgu.ru/problem.php?problem=261

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

14057. idet teg ?nts?gt


Problem code: HICHEEL1
* bolon #-aas b?rdsen n*m khemeetej teg ?nts?gt ?g?gds?n bol enekh?? teg ?nts?gtijg khamgijn
bagadaa kheden ?jldel khijgeed teg ?nts?gt bolgokh bolomtoj ve?
idet teg ?nts?gt: Al baganyn temdegt??d n b?gd iil bajkh.
?jldel: Al neg temdegtijg ??r temdegteer solikh.

Input
Ekhnij m?r?nd n,m (1<=n,m<=1000) toonuud ?g?gd?n?.
Daraagijn n m?r b?rt m irkheg * esvel # -aas b?rdsen m?rn??d ?g?gd?n?.

Output
KHamgijn bagadaa ?jldlijn too.

Example
Orolt
6 6##*#*#*###*####**##***##*##*#####**#
Garalt
9

Added by: Dulguun Batmunkh


Date:
2013-03-11
Time limit: 1s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict
Resource: arigato_dl

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

14059. idet gurvalin


Problem code: HICHEEL2
idet gurvalin
?g?gds?n 3 tseg neg uluun deer ori bajna uu?

Orolt:
Ekhnij m?r?nd x1,y1,x2,y2,x3,y3 toonuud bajrlana. (0<=x1,y1,x2,y2,x3,y3<=2147583647)

Garalt:
Bolokh bol YES, bolomg?j bol NO.
iee test:
Orolt
111233
Garalt
YES

Orolt
111213
Garalt
NO

Added by: Dulguun Batmunkh


Date:
2013-03-11
Time limit: 1s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: DOC C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict PDF PS TECS TEXT
Resource: arigato_dl

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

14060. idet ooir


Problem code: HICHEEL3
Ooirt nijt n irkheg kh?n zogso bajsan ba tedgeer n 1-ees n kh?rtel dugaarlagdsan ba b?gdeeree ??r ??rijn gesen nastaj bajv. (Nasny khzgaar bodit amdralaas khol z?r??tej.) Tedgeerijg nasaar n er...

Orolt:

Ekhnij m?r?nd n (1<=n<=100000) too ?g?gd?n?.

Daraagijn m?r?nd n irkheg Ai (1<=Ai<=1000) toonuud khooson zajgaar tusgaarlagdan ?g?gd?n?.

Garalt:

Nasaar n bagaas n ikhr?? erembelegdsenij daraakh bajrlal.

iee test:

Orolt

5 7 1 4 5 3

Garalt

2 5 3 4 1

Added by: Dulguun Batmunkh


Date:
2013-03-11
Time limit: 1s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict
Resource: arigato_dl

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

14061. idet toonuud


Problem code: HICHEEL4

?g?gds?n n irkheg toonuudyg khamgijn bagadaa kheden irkheg ?jldel khijn idet toonuud bolgo adakh ve? ?jldel: Duryn neg toog kh?ssen too bolgon ??rl?kh. idet toonuud: KHasakh toonuudaar ekhlen nemekh toonuudaar t?gs?n?. ??r??r khelbelt

Orolt:Ekhnij m?r?nd n (1<=n<=100000) too ?g?gd?n?.Daraagijn m?r?nd n irkheg Ai (1<=Ai<=1000000000) toonuud khooson zajgaar tusgaarlagdan ?g?gd?n?.Garalt:KHamgijn baga ?jldlijn too.iee test:Orolt4 -1 1 -2 1Garalt1Orolt5 0 -1 1 2 -5Garalt2

Added by: Dulguun Batmunkh


Date:
2013-03-11
Time limit: 1s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict
Resource: arigato_dl

< 0, t

< 0, ..., t

< 0ba t

k + 1

> 0, t

k + 2

> 0, ..., t

> 0 bajkh k too oldono. M?n 0 gedeg toog aguulaag?j bajna.

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

14062. idet ?segn??d


Problem code: HICHEEL5
?g?gds?n n urttaj [a..z] b?rdsen temdegt??dijn tsuvaand khamgijn ikh orson ?seg n kheden udaa orsnyg ol bine ??!
Orolt:
Ekhnij m?r?nd n (1<=n<=1000000) too ?g?gd?n?.
Daraagijn m?r?nd n irkheg ?segn??d daraallan bajrlana.

Garalt:
KHamgijn ikh orson ?sgijn too.
iee test:
Orolt
5
abbac
Garalt
2

Orolt
4
abcd
Garalt
1

Added by: Dulguun Batmunkh


Date:
2013-03-11
Time limit: 1s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict
Resource: arigato_dl

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

14440. Davy Joness Organ


Problem code: MFNNM

Two melodies dont go out of Davy Joness head. One of them or another sometimes emerge in his
mind. To get rid of annoying melodies, Davy Jones decided to play them on his organ. At first, he
wants consiquently perform first and second melodies. And then Davy Jones is going to play the same
notes as the first time but in the reverse order.
If the first and second compositions sound exactly the same, then, according to Davy Joness idea, the
melodies will no longer vary by his subconscious and finally will leave him alone.
Jones recorded the notes of both songs. He was sure in the songs duration, but not really in which
place every song begins. But it is not important, because they play cyclically in his mind and you can
choose any place as a start in each of them.

Input
In the first line of the input you are given a string of lengthn-- sequence of notes of the first melody.
In the second line there is a string of lengthm-- sequence of notes of the second melody (1
<=m<n <= 5.10 4 , m<=n ). Each note is represented by lowercase Latin letter. Order of notes in the
melody corresponds to their order in its playback accurate within start of the melody.

Output
If it is impossible to play compositions conceived by Davy Joness way, output "No". Otherwise, in
the first line write "Yes" and in the second-- a pair of integers-- numbers of notes in the first and
second tunes respectively, which you should choose as a start. Numbering of notes corresponds to a
record of melodiess in the input and starts from one. If there are several possible solutions choose the
one with the smallest possible tune index from the first note. If there are still many solutions print any.

Example
Input:
cdedab

bac
Output:
Yes
5 3

Input:
aaaa
bbb
Output:
No

Added by: islam


Date:
2013-04-05
Time limit: 1s-8s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: Open Ural FU Championship 2012

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

14460. Scavenger Hunt


Problem code: SHUNT
You are playing a scavenger hunt game organized by your school.
Assume the school is an infinite 2D field. The rules of the game are quite simple: There are n people
from the organization, numbered from 1 to n. Person i is located at position (x i , y i ). All you have to
do is go to (x i , y i ) and let the i-th person see you, for all 1 <= i <= n. You can run from a position
(x a , y a ) to a position (x b , y b ) in dist((x a ,y a ),(x b ,y b )) seconds, where dist(P,Q) is the euclidian
distance between points P and Q.
Initially, you are at the same position of person 1, who already saw you. Also, initially you only know
the position of person 1. To find out the position of some other person, you need to ask someone.
Every person knows the position of all the others. However, if you ask person i where person j is, it
will take him W i,j seconds to answer. Your task is to find a sequence of questions and runnings that let
you finish the game quickly. This is a partial problem - you do not need to find an optimal solution,
but your score will be proportional to the solution you find.

Input/Output
This is an iterative problem. Your program will "talk" to the judge directly via the standard input and
output.
There are no more than 20 test cases. For each test case, the judge will start by printing
START n
x1 y1
W 1,1 W 1,2 ... W 1,n
W 2,1 W 2,2 ... W 2,n
...
W n,1 W n,2 ... W n,n
(Assume 2<=n<=40 and 0<= x i ,y i ,W i,j <=10 4 ).

After reading that, your program should print commands. A command must be one of these:
ASK i ask the person that saw you last where the person i is. The judge will reply by printing
ANSWER x i y i . Youll get "Runtime Error" if (1 <= i <= n) doesnt hold.
GO i go to the position of the person i and let him see you. The judge will reply by printing
MOVED . Youll get "Runtime Error" if (1 <= i <= n) doesnt hold or if you dont know the
position of the person i yet.
FINISH finish the game. The judge will reply by printing OK length , where length is the total
time spent by you in the game of the test case in seconds, with exactly 3 fractional digits (this is
just a "bonus"; your program should be able to calculate length by itself). Youll get "Wrong
Answer" if you havent been to everyones position at least once.
Youll get "Runtime error" if your program prints something different from the commands
described above.
Imediatally after printing OK length , the judge will start another test case by printing START ... . If
there are no more test cases, the judge will print END instead. In this case, your program should
terminate.
Please notice that you are allowed to ask more than one question or to not ask any questions at all to a
person.
Attention: the program should clear the output buffer after printing each line. It can be done using
fflush(stdout) command or by setting the proper type of buffering at the beginning of the execution setlinebuf(stdout).
Also, while reading data from the judge in C/C++ using scanf, avoid hardcoding the commands you
known youll receive. For instance, prefer to use scanf("%s %d",start_string,&n) instead of
scanf("START %d",&n).

Score
For each test case, p i = min(1.0, length/greedy), where length is the total time spent by you, and
greedy is the length obtained by a program that prints ASK 2 GO 2 ASK 3 GO 3 ... ASK n GO n
FINISH.
Your final score will be equal to ceil[ (SUM (p i *n i )/SUM n i )*100 ], where n i is the value of n in the
i-th test case. The lower your score is, the better youre ranked.

Exemple
This is an exemple of the executation of a program that obtains greedy as the total spend time (and
thus gets the score 100):
Judge:
START 3
00

123
456
789
Program: ASK 2
Judge: ANSWER 2 2
Program: GO 2
Judge: MOVED
Program: ASK 3
Judge: ANSWER 1 1
Program: GO 3
Judge: MOVED
Program: FINISH
Judge:
OK 12.243
END
Program: <terminates>
Added by: Ricardo Oliveira [UFPR]
Date:
2013-04-08
Time limit: 2s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: Own problem

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

14702. Yet another range difference query!


Problem code: TREAP
Given an empty set S, you have to apply Q operations on this set while keeping the set sorted in
increasing order and elements have indices 0 <= i < size(S)
The operations are insert, delete, find min difference in a given range, find max difference in a given
range.

Input

Ik
Insert k into S, if k is not in S
Dk
Delete k from S, if k is in S
Nij
Print min{abs(S[x] - S[y]) | i <= x, y <= j} or -1 if the range has 1 element
Xij
Print max{abs(S[x] - S[y]) | i <= x, y <= j} or -1 if the range has 1 element

I k : Insert k into S, if k is not in S


D k : Delete k from S, if k is in S
N i j : Print min{abs(S[x] - S[y]) | i <= x, y <= j} or -1 if the range has 1 element
X i j : Print max{abs(S[x] - S[y]) | i <= x, y <= j} or -1 if the range has 1 element

limits: 0 < Q <= 200000 , 0 <= k <= 10^9 , 0 <= i,j < size(S)

Output
For each N and X operations, print an integer per line as described above.

Example
Input:
11
I 1
I 12
I 4
I 8
N 0 3
X 0 3
N 1 3
X 0 2
D 4
N 0 1
X 1 2
Output:
3
11
4
7
7
4

Added by: ahmed.abdrabo


Date:
2013-04-22
Time limit: 5s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: modified zeap from infoarena.ro

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

14756. Rice Hub - IOI


Problem code: RACEHUB

In the countryside, you can find a long straight road known as the Rice Way. Along this road
there are R rice fields. Each field is located at an integer coordinate between 1 and L, inclusive.
The rice fields will be presented in non-decreasing order of their coordinates. Formally, for
0 <= i < R, rice field i is at coordinate X[i]. You may assume that 1 <= X[0] <= ... <= X[R-1] <= L.
Please note that multiple rice fields may share the same coordinate.
We plan to construct a single rice hub as a common place to store as much of the harvest as possible.
As with the rice fields, the hub has to be at an integer coordinate between 1 and L, inclusive.
The rice hub can be at any location, including one that already contains one or more rice fields.
Each rice field produces exactly 1 truckload of rice every harvest season. To transport the rice to
the hub, the city has to hire a truck driver. The driver charges 1 Baht to transport a truckload of
rice per unit of distance towards the hub. In other words, the cost of transporting rice from a
given field to the rice hub is numerically equal to the difference between their coordinates.
Unfortunately, our budget for this season is tight: we may only spend at most B Baht on transportation.
Your task is to help us strategically place the hub to gather as much rice as possible.

In the countryside, you can find a long straight road known as the Rice Way. Along this road
there are R rice fields. Each field is located at an integer coordinate between 1 and L, inclusive.
The rice fields will be presented in non-decreasing order of their coordinates. Formally, for
0 <= i < R, rice field i is at coordinate X[i]. You may assume that 1 <= X[0] <= ... <= X[R-1] <= L.
Please note that multiple rice fields may share the same coordinate.
We plan to construct a single rice hub as a common place to store as much of the harvest as possible.
As with the rice fields, the hub has to be at an integer coordinate between 1 and L, inclusive.
The rice hub can be at any location, including one that already contains one or more rice fields.
Each rice field produces exactly 1 truckload of rice every harvest season. To transport the rice to
the hub, the city has to hire a truck driver. The driver charges 1 Baht to transport a truckload of

rice per unit of distance towards the hub. In other words, the cost of transporting rice from a
given field to the rice hub is numerically equal to the difference between their coordinates.
Unfortunately, our budget for this season is tight: we may only spend at most B Baht on transportation.
Your task is to help us strategically place the hub to gather as much rice as possible.

Task

Given integers R, L and B ( 1 <= R <=100 000, 1 <= L <=1 000 000 000 , 1 <= B <= 2 000 000
000 000 000 ) and an array X containing R positive integers:
* R - the number of rice fields. The fields are numbered 0 through R-1.
* L - the maximum coordinate.
* X - a one-dimensional array of integers sorted from smallest to largest.
For each 0 <= i < R, field i is located at X[i].
* B - the budget.
You must find an optimal location of the hub and return the maximum number of
truckloads of rice that can be transported to the hub within the budget.
Note that the total cost of transporting the rice can be very large. The budget is given as a 64-bit
integer, and we recommend that you use 64-bit integers in your computation. In C/C++, use the
type long long; in Pascal, use the type Int64.

Example
Input:
5 20 6
1
2
10
12
14
Output:
3

Added by: Mateus Dantas [ UFCG ]


Date:
2013-04-29
Time limit: 1s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: International Olympiad in Informatics 2011

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

14759. Yet another strings problem !!


Problem code: SKIPLIST
Frequent Substring Counting
Given a string S and integer N, your task is to compute the substring of length N that is repeated most
in the string.
If two substrings of length N have the same occurrence count in S, return the smallest
lexicographically.

Input
The first line contains the number of test cases T. T <= 10.
The following T lines hold the test cases, each line consisting of integer N followed by string S. N and
S are space seperated. N <= 100, |S| <= 100000 .

Output
Print T lines, each containing the substring of length N that is most frequent. If two substrings have the
same occurrence count, print the smallest lexicographically.

Example
Input:
2
2 efababefef
1 aabebb
Output:
ef
b

Added by: ahmed.abdrabo


Date:
2013-04-30
Time limit: 1s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: UVA

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

14859. Scrivener - IOI 2012


Problem code: SCRIVIOI
Crayfish scrivener
For a better understanding: http://www.ioi2012.org/wp-content/uploads/2011/12/Scrivener.pdf
Some people say that Leonardo was a great admirer of Johannes Gutenberg, the German blacksmith
who invented movable-type printing, and that he paid homage by designing a machine called the
crayfish scrivener -- il gambero scrivano -- a very simple typing device. It is somehow similar to a
simple modern typewriter and accepts only two commands: one to type the next character and one to
undo the most recent commands. The notable feature of the crayfish scrivener is that the undo
command is extremely powerful: an undo is also considered to be a command itself,
and can be undone.

Statement

Your task is to realize a software version of the crayfish scrivener: it starts with an integer representing
the number of queries and accepts a sequence of commands entered by the user, and queries for
specific positions of the current version of the text, as follows.

T L -- append to the end of the text a single lowercase letter L chosen from
a, ..., z.

U C -- undo the the last C commands, for a positive integer C.

P X -- return the letter at position X in the current text, for a non-negative index X. The first letter in
the text has index 0. (This query is not a command and thus is ignored by the undo command.)

It is guaranteed that C in query U will not exceed the number of previously received commands, and
that X in query P will be less than the current text length ( the number of letter in the current text ).

As for query U, it undoes the previous C commands in reverse order: if the command to be undone is
T L, then it removes L from the end of the current text; if the command to be undone is U X for some
value X, it re-does the previous X commands in their original order.

Example

Input Output
10 a
T c c
Tz
Tu
Ta
Ti
Th
Tf
Tz
P3
P0

Added by: Mateus Dantas [ UFCG ]


Date:
2013-05-08
Time limit: 1s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: International Olympiad in Informatics 2012

(function() { var po = document.createElement(script); po.type = text/javascript; po.async = true;


po.src = https://apis.google.com/js/plusone.js; var s =
document.getElementsByTagName(script)[0]; s.parentNode.insertBefore(po, s); })();

SPOJ Problem Set (partial)

15228. Swap (Original)


Problem code: TOKI1493
NyanCoder have a new hobby, that hobby is playing with string and He love sorted string. NyanCoder
want to make two strings a and b, both string have equal length N. At that both string, NyanCoder
want to swap some element (or none) on string awith element on string bthat located at same
position. More specifically, NyanCoder may choose integer i, and then swap a[i] with b[i].
NyanCoder want when he finished playing, both new string have non-decreasing element (e.g.
"aabbb", "cccdee" but not "bbaa" or "ebd"). Help NyanCoder to count number of possible initial string
a and bwith length Nthat meet the condition that NyanCoder want.

Input
First line there is an integer Tdenoting number of test cases, then Ttest cases follow.
For each test case, there is two integers N and M, separated by a space where Ndenoting length of
both string, andalphabet that can be used on that both string is Mfirst letters (lower case) on latin
alphabet (a,b,c, and so on). For example, if M=3, all character on both string is formed with only
first 3 lower case letters (a,b, and c).

Output
For each test case, output an integer which is the number of possible initial string aand bwith length
Nand meet all condition that have described before.

Example
Input:
1
2 2
Output:
11

Explanation
When N=2 and M=2, all pair of initial sring that meet the condition is:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

"aa",
"aa",
"aa",
"ab",
"ab",
"ab",
"bb",
"bb",
"bb",
"ba",
"ab",

"aa"
"ab"
"bb"
"aa"
"ab"
"bb"
"aa"
"ab"
"bb"
"ab"
"ba"

Subtask
Subtask 1 (10 points): 1<=N<=5, 1<=M<=26
Subtask 2 (20 points): 1<=N<=10, 1<=M<=26
Subtask 3 (30 points): 1<=N<=40, 1<=M<=26
Subtask 4 (40 points): 1<=N<=1000, 1<=M<=26
To get AC on this problem you need to solve at least one test data (min possible points on rank table
for this problem is 10).

Other Info
This is a copy of TOKI problem, with some small changes to become suitable with SPOJ server and
judge:
Language, because SPOJ is International Online Judge, so I must translate the problem statement
and other to English before publishing it.
I/O format, because SPOJ server is busy (too many submission per minute), to make it stable then
I should make number of input data as small as possible, so my solution is to put multiple test
case in one file.
Test Case, because I dont know official test case used on this problem, I build my own test case.
All possible case that meet the constraints will appear once on each test data.
Problem setter who created this problem is Risan Petrus. I only copy his problem that used on TOKI
open contest june 2013 to SPOJ because for me this problem is very interesting. I like it, and I want
every user on SPOJ can enjoy his problem too.

See also: Another problem added by Tjandra Satria Gunawan

Added by: (Tjandra Satria Gunawan)(???)


Date:
2013-06-19
Time limit: 1s
Source limit:50000B
Cluster:
Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: TOKI Open Contest, June 2013, Problem 03

You might also like