SPOJ Tutorial PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 708

 

Archives of the Sphere Online Judge


tutorial problemset
 

Editors:

1
cegprakash
Nikunj
mbt Jain initiald159
Rishi Kumar
MaheshMahmud
Iqram
osb Chandra Adrian Kosowski
Venezuelan Programming
SharmaRychcicki
Robert
Hemant Verma n0cturnal
League
Tomas. Bob
Coach UTN FRSF
Andrés Mejía-Posada
Swarnaprakash Ali Arous
tille
Nguye^~n Duy Khánh
Nikola Pinstitutes
Avinash
kawmia Borisov Manohar
Tomek Singh
Noiński
Filip Wielewski
mohamed
Daniel
problem Gómezgamal
setters Didier Ahmed Kamel
.::Baba [ahm.kam_92]
Ramdev::.
Edwin Guzman
Spooky
Chen Xiaohong
Dulguun Batmunkh Amlesh Jayakumar
Pandian
Anil Kishore
[Trichromatic]
Ranjith
Jakub Mudalaiyar
Šafin SimonHa?i
Trân GogĐăng
XeRoN!X
XilinXSchaposnik
Ankul
Fidel Garg Pritam Bhattacharya
Damon Doucet
Igneel Dragon
Roman Sol
jack(chakradarraju)
Rodolfo Miquilarena hanaa Dudzicz
Marek
hua
.:: Pratik
Walrus
Paulo Costa::. Rajeev Kumar.J
Alfonso2 Peterssen
Jimmy Tirtawangsa
Siddharth Kothari
pankaj
HWK Apoorv Gupta
Phyllipe César [UFCG]
abhijith reddy d
Adrian
Devil
IbrahimD Kuegel
Mesecan Frank RafaelKotb
Mohammad Arteaga
Ajay Somani
amit karmakar
Tii
Troika::Bytes Bartłomiej
MRS. BEAN Kowalski
on leave
Rofael Emil
Fabio Avellaneda
numerix
Srivatsan B Leandro Castillo
Sylwester HerberValdes
Ikhaduri
Omar ElAzazy
Devendra
Better lateAgarwal
than dqd
faculty of engineering at
Michał Małafiejski
dce coders
Prasanna
never !!! Ricardo OliveiraUniversity
shoubra_Benha [UFPR]
Radhakrishnan
Paul Draper
Alvaro
Mussab Javier
ElDash AhmedHie^’u
Trung Mohamed Emad
Ruslan Sennov
lost Santiago
Medina
Simón Balboa Morsy El-Deen Goodname
Hossam
Sandeep Singh Jakhar
balaji
???
Soriano Pérez Thanh-Vy
Jelani Hua
Nelson (Minilek)
M::B
wil_be_bak
paradigm2k10
Bin Jin VOJ problem setters
praveen123
rizwan hudda
Sharaf
Minh^^
Francky octalc0de
Abhishek Mishra
Varun
styrofox
Rafał Jalan
Nowak Mostafa Saad
Tomasz Niedzwiecki
Miorel-Lucian Palii
Tamer JaceTheMindSculptor
sieunhan
virtuosoenforcer
Ben Dilts FA
Fajri Rahmat
Race
Ali with time
Asgar Łukasz Kuszner
pradeep
bashrcMoran
David is back Josef Ziegler
WahbA
Islam Samir
Kumar Anurag Mikel Arteta
Andy William
Badreldin
Yandry Perez Apurv Singhal
priyamehtanit
.:: Debanjan
Marco Gallotta::. Pripoae Toni
el moatasem
AndresAriel
Pablo TellezHeiber Ahmed Aly
Kashyap Krishnakumar
Buda IM
? Krzysztof Lewko
Jonas Wagner
AUC LOCAL
Infinity Neal Wu
Saravannan Shaan
TouristGuide
Maciej Boniecki akaki
MateusDantas
Pig Yellow
Mislav Balunović kojak_
Camilo Andrés Varela León
Azat Taryhchiyev
xiaodao Matthew Reeder
bnta2
Rahul Parekh
Ishani Fernando Torres

2
 

Last updated: 2012-12-10 00:31:53

3
Preface
This electronic material contains a set of algorithmic problems, forming the archives of the Sphere
Online Judge (http://www.spoj.com/), tutorial problemset. The document can be accessed at the
following URLs:

in PostScript format: http://www.spoj.com/problems/tutorial.ps


in Portable Document Format: http://www.spoj.com/problems/tutorial.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.

4
Table of Contents
1. Problem INTSS (244. Internally Stable Sets)
2. Problem BCEASY (360. Bottom Coder (Easy))
3. Problem BCHARD (361. Bottom Coder (Hard))
4. Problem TSHPATH (440. The Turtle´s Shortest Path)
5. Problem INTEST (450. Enormous Input Test)
6. Problem SUMTRIAN (453. Sums in a Triangle (tutorial))
7. Problem ARMIES (490. Armies)
8. Problem MMATCH (491. The Cursed Room)
9. Problem TSORT (500. Turbo Sort)
10. Problem PRINT (503. Prime Intervals)
11. Problem LEXISORT (511. Easy Sorting)
12. Problem J4FUN (527. Just for Fun (Easy))
13. Problem TFIB (536. How many Fibs)
14. Problem PAYBACK (644. Byteland Money Exchange)
15. Problem HFLOOR (691. Hotel Floors)
16. Problem FFARM (692. Fruit Farm)
17. Problem JHNSN (732. Johnsons Algorithm)
18. Problem PCV1 (762. Problems Collection (Volume 1))
19. Problem LOTTERY (851. Tickets lottery)
20. Problem ADOMINO (1023. Arranging Dominoes)
21. Problem SNOWMAN (1118. Snowman)
22. Problem NIMGAME (1238. Special Nim Game)
23. Problem RECEQU (1239. Recurrence Equation Finder)
24. Problem RLDEC (1279. Run Length Decoding)
25. Problem COUNTISL (1282. How many Islands)
26. Problem CZ_PROB2 (1392. Sum of Factors)
27. Problem CZ_PROB3 (1393. Ping Pong Probability)
28. Problem CZ_PROB4 (1394. Dividing Spaces)
29. Problem CZ_PROB7 (1397. Put Them on a Circle)
30. Problem PCV2 (1415. Problems Collection (Volume 2))
31. Problem EMP (1417. University Employees)
32. Problem EASUDOKU (1428. Easy sudoku)
33. Problem TREE3 (1474. Charge)
34. Problem PT07K (1488. Balloons of JiaJia)
35. Problem ANNOYING (1679. Annoying painting tool)
36. Problem BLACK (1680. Black and white painting)
37. Problem DELI (1682. Deli Deli)
38. Problem NUMGUESS (1729. Guess the Number)
39. Problem DETER (1756. Find The Determinant)
40. Problem MKBOOK (1872. Making Book)
41. Problem CLIQSEP (2018. Clique Separation)
42. Problem PAINTPOI (2020. Painting Points)
43. Problem BBOARD (2122. Billboard)
44. Problem PANEL (2126. Panel)
45. Problem CCUBE (2134. Colorful Cubes)

5
46. Problem JCEASY (2155. Jamcode 2006 (Easy))
47. Problem JCHARD (2156. Jamcode 2006 (Hard))
48. Problem ANALYS_T (2261. Program Analyser (tutorial))
49. Problem WHEEL (2278. Merrily, We Roll Along!)
50. Problem MAGIC (2459. Magic Program)
51. Problem MAGIC3 (2494. Magic Program III)
52. Problem GNY07A (2523. Mispelling)
53. Problem GNY07B (2524. Conversions)
54. Problem POINTS (2533. Point Nesting)
55. Problem PCV3 (2625. Problems Collection (Volume 3))
56. Problem REX (2626. RegExp Master)
57. Problem BCH (2627. The Longest Chain)
58. Problem ARJ (2630. Autoarchive)
59. Problem MXP (2632. Max Power)
60. Problem ELDORADO (2854. El Dorado)
61. Problem FACTSUM (2907. Super Factor Sum)
62. Problem SPRIME (2912. Super Primes)
63. Problem ADUN (3032. Adding two numbers)
64. Problem LOOKSAY (3081. Look and Say)
65. Problem CURICULA (3131. Time to Graduate)
66. Problem SEVENPER (3250. The Seven Percent Solution)
67. Problem PERBITS (3252. Persistent Bits)
68. Problem ROCKSKIP (3256. Rock Skipping)
69. Problem SOFTBUG (3313. Software Bugs)
70. Problem PASCALTR (3318. Pascals Travels)
71. Problem SPEEDLM (3319. Speed Limit)
72. Problem LMIS (3320. Longest Monotonically Nondecreasing Sequence)
73. Problem KNAPSACK (3321. The Knapsack Problem)
74. Problem MERGSORT (3370. Mergesort)
75. Problem FASTPOW (3371. Fast Power)
76. Problem MIRRORED (3378. Mirrored Pairs)
77. Problem QUALITY (3386. Contest System Quality Assurance Tester)
78. Problem GARDENHU (3421. Garden Hull)
79. Problem CALCAREA (3422. Calculate the Area)
80. Problem INOUTEST (3440. Enormous Input and Output Test)
81. Problem NETIQUE (3443. Netiquette)
82. Problem COMPANY (3580. Company)
83. Problem LOGPOWER (3695. n-th Power)
84. Problem LOGFIB (3699. Fibonacci numbers)
85. Problem EZDIJKST (3700. Easy Dijkstra Problem)
86. Problem KLUCKY (3727. Lucky Number)
87. Problem SPHASH (3903. Special Hashing)
88. Problem BICOLOR (3916. Bicolor)
89. Problem TREEQ (3917. Tree Query)
90. Problem RSTOUR (3918. Rock Star Tour)
91. Problem HARDWARE (3997. HARDWARE)
92. Problem JACKPOT (4001. JACKPOT)

6
93. Problem PROBTNPO (4073. The 3n plus 1 problem)
94. Problem CE (4074. Compile Error)
95. Problem DIOEQ (4171. DIOPHANTINE)
96. Problem APLUSB2 (4190. A plus B)
97. Problem MFMOBILE (4207. Mobile (Again))
98. Problem INV (4215. Inversions)
99. Problem PLCNUM1 (4245. Place the Numbers I)
100. Problem BENCH (4293. Weightlifting)
101. Problem VOTE (4323. Voting Districts)
102. Problem POWTOWER (4349. Power Tower)
103. Problem BICOII (4375. Bicoloring II)
104. Problem LPS (4474. Longest Palindromic Substring)
105. Problem MAGIC1 (4492. Magic1)
106. Problem EQUAD1 (4493. Equation)
107. Problem LOTR1 (4500. Helms Deep)
108. Problem UCI2009A (4522. Adding Base36 BigNumbers)
109. Problem SPIDEY1 (4543. Mysterio s Menace)
110. Problem ANARC08E (4554. Relax! It is just a game)
111. Problem LQDRECT (4566. Đe^’m hinh chu+~ nhât)
112. Problem DESDEHAS (4762. Desde Hasta)
113. Problem PROBTRES (4765. The 3n plus 1 problem V2)
114. Problem COOLNUM (4768. Cool Numbers)
115. Problem ADDREVUT (4770. Add and Reverse Sums)
116. Problem PC1 (4786. Invertir Cadena)
117. Problem PC2 (4787. Vocales en un vector de letras)
118. Problem PC3 (4788. MCD)
119. Problem PC4 (4789. De decimal a binario)
120. Problem TPJOUR (4826. JOURNEY )
121. Problem KZWC (4830. Z meet)
122. Problem PITYFERM (4832. Pitagoras y Fermat)
123. Problem KZHAPPY (4834. Happy Sequence)
124. Problem KZGREEDY (4835. Weightlift challenge)
125. Problem PRIMOKRI (4854. Primo Kripta)
126. Problem FAIRPART (4855. Fair Partition)
127. Problem FLOTTERY (4861. Fantastic Lottery)
128. Problem PLANE (4863. Plane Division)
129. Problem YUPANA (4865. Yupana inca)
130. Problem COLLIDER (4866. The innovative collider)
131. Problem EEIGHTS (4867. Eeights)
132. Problem FLATLAND (4869. Flat Land)
133. Problem KZGD (4872. Good Sequence)
134. Problem KZBLK (4873. ABC Blocks)
135. Problem KZGM (4874. KZGAME)
136. Problem KZGME (4875. Scramble game)
137. Problem KZCITY (4876. Save City)
138. Problem VOCMINMA (4892. De minúsculas a mayúsculas)
139. Problem SIMTRANS (4893. Traductor Simple)

7
140. Problem NDINTERV (4895. N-D Intervals)
141. Problem MEOWIST (4897. Meowist Networking)
142. Problem PYTHTRIP (4906. Pythagorean Triples)
143. Problem MCL (4907. Most Common Letter)
144. Problem LISTTEST (4997. Test Básico de Listas)
145. Problem ALPHMATH (5009. Alphabet Arithmetic)
146. Problem SPANCONJ (5012. Spanish Conjugation)
147. Problem HEROADV (5105. Hero Adventure)
148. Problem HELLOKIT (5132. Hello Kitty)
149. Problem ROB (5194. Robbery)
150. Problem ANGRYKN (5195. Angry Knights)
151. Problem BRHFBALL (5200. Lsu Football)
152. Problem OLDP (5228. Old problem)
153. Problem ALCH (5241. Alchemy)
154. Problem FAMILYP (5297. Family Problems)
155. Problem MCPC06C (5302. Surprising Strings)
156. Problem MCPC06B (5306. Linear Pachinko)
157. Problem MCPC06G (5313. Root of the Problem)
158. Problem RATIONAL (5371. Rational Number)
159. Problem BIGFIBB (5387. Interesting determinant)
160. Problem ANARC09E (5447. Probability One)
161. Problem AP (5462. Art Plagiarism)
162. Problem IPS (5779. Interleaved Periodic String)
163. Problem FILIP (5848. Filip)
164. Problem GRID (5871. Grid)
165. Problem ANAG (5872. Anagram)
166. Problem RNUM (5873. Rnumber)
167. Problem SQRE (5874. Square)
168. Problem SIMEQN (5899. A simple equation)
169. Problem DECSTRNG (5900. Decreasing Strings)
170. Problem SURPRISE (5965. The Element of Surprise)
171. Problem GENCHESS (5966. Generalized Chess)
172. Problem ISPITI (6069. Ispiti)
173. Problem HFUN (6192. H Function)
174. Problem PROBLEM (6291. Problem)
175. Problem QMAX4 (6438. Giá tri. lo+’n nhât 4)
176. Problem KMBUS (6475. Da.o cho+i băng xe bus)
177. Problem XMEDIAN (6501. Median)
178. Problem SUPERPW (6521. SuperPower)
179. Problem DIGRT (6523. Digital Root Counter)
180. Problem FGROUP (6524. Find the group)
181. Problem CIRCP (6528. Circle Counting)
182. Problem BOPUZZLE (6555. F - Rompecabezas de Puzzle)
183. Problem SBE201P2 (6645. SBE201 Linked List)
184. Problem NICEQUAD (6647. Tu+’ giác đe.p)
185. Problem GCJ2010 (6651. Snapper Chain)
186. Problem LEXI1 (6653. Lexicographic Order 1)

8
187. Problem LEXI2 (6654. Lexicographic Order 2)
188. Problem LEXI3 (6655. Lexicographic Order 3)
189. Problem LEXI4 (6656. Lexicographic Order 4)
190. Problem HMT1 (6666. How Many Trees 1)
191. Problem HMT2 (6667. How Many Trees 2)
192. Problem GCJ2K10 (6677. Rope Intranet)
193. Problem BOSWEEP (6696. F - The Sweeper in Cleanland)
194. Problem SBE201P3 (6703. SBE201 Palindromes)
195. Problem CARDGAME (6705. Card Game)
196. Problem CRUCE (6734. Crossing the bridge)
197. Problem LQP (6802. Budget)
198. Problem PARKBUS (6954. Parking Busses)
199. Problem FINDMAX3 (6955. Find the max of the 3 numbers)
200. Problem TTREAT (7129. Happy Telephones)
201. Problem BLOWFUSE (7136. Blowing Fuses)
202. Problem ALCHE (7207. Alchemy)
203. Problem TRICAL (7213. TRIANGLE SUM)
204. Problem ROBODA (7214. Robo Track)
205. Problem NONSTOP (7215. No Red Lights Pl !!)
206. Problem NEXTODD (7236. The next odd number)
207. Problem INFINITY (7237. Biggest !)
208. Problem NTH (7262. Nth greater value)
209. Problem TAKE4 (7272. Take Away Game)
210. Problem PERMRANK (7273. Rank of a Permutation)
211. Problem FIBOREP (7274. Fibonacci Representation)
212. Problem MB2 (7289. Reverse text)
213. Problem MB1CH (7334. PP numbers)
214. Problem CURIOS (7366. Curious Numbers)
215. Problem PKH (7390. Buy your house)
216. Problem PKK (7391. Highway Patrol)
217. Problem MINMAX (7411. Reward for the hard work)
218. Problem HACK (7412. A little hacking)
219. Problem TILEGAME (7413. Tile game)
220. Problem THANKS (7414. Thank you Chief ;))
221. Problem RANJAN03 (7431. Vikram & Betaal)
222. Problem CCONST (7483. C style constants)
223. Problem PPROF (7513. Painful Prof)
224. Problem HAPLANT (7557. C- Watering Plants)
225. Problem YOKOG (7578. Polygons on the Grid)
226. Problem YOKOE (7580. Manhattan Wiring)
227. Problem YOKOI (7582. Enjoyable Commutation)
228. Problem MCDG (7633. Maximo común divisor generalizado)
229. Problem NEWLANG (7667. Minimum and maximum numbers)
230. Problem SALSA (7672. Salsa Dance)
231. Problem OWNCALC (7673. Making your own Calculator)
232. Problem CPCRC1A (7674. Easy Game)
233. Problem CPCRC1B (7675. Squares)

9
234. Problem CPCRC1D (7677. Frequent Values)
235. Problem LOGTWO (7688. PowerOf2)
236. Problem EXFOR (7775. Explicit Formula)
237. Problem ARR (7785. ARRAY(EASY))
238. Problem ADV04A (7856. Tower Game (Easy))
239. Problem ADV04B (7858. Upper Right King (Easy))
240. Problem ADV04F (7863. Four Chips (Easy))
241. Problem ADV04G (7865. Regular expressions (Easy))
242. Problem ADV04I (7869. Boards (Easy))
243. Problem HPYNOSI (7885. Happy Numbers II - Trial)
244. Problem WNAME (7893. Weekdays)
245. Problem PECOSSTR (7910. PECOS STRING)
246. Problem FIBPARIT (7925. Fibonnaci Parity)
247. Problem PBCGANGS (7999. Các băng đa?ng)
248. Problem AMR10F (8060. Cookies Piles)
249. Problem SPMAP (8094. Treasure map )
250. Problem RCLUSTER (8101. Rectangular Cluster)
251. Problem RECFUN (8142. Recursive function)
252. Problem ACEGAME (8144. Game of 3 cards)
253. Problem CONCATE (8146. Integer Concatenation)
254. Problem BANKQUE (8147. Waiting Queue)
255. Problem LINESEG (8149. Intersection)
256. Problem BUNNY (8152. Smart Bunny)
257. Problem GOLDCOIN (8191. Gold distribution)
258. Problem NOVICE21 (8214. Problem 1)
259. Problem NOVICE22 (8215. Problem 2)
260. Problem NOVICE23 (8216. Problem 3)
261. Problem NOVICE24 (8218. Problem 4)
262. Problem NOVICE25 (8219. Problem 5)
263. Problem SPRTFY (8220. Sports factory)
264. Problem BINSTR (8223. Binary Strings)
265. Problem PRSQRFR (8224. Perfect Composites)
266. Problem EPR (8226. PrePrimes)
267. Problem FIBPOS (8227. Fibonacci Terms)
268. Problem PRIME12 (8232. Fun With Primes)
269. Problem PTTRN (8264. Find The Pattern)
270. Problem COMPSTR (8266. Compare The Strings)
271. Problem WLCME (8267. Welcome To Code - Easy)
272. Problem WLCME2 (8268. Welcome To Code - Hard)
273. Problem REPEAT (8289. Find the unique Number)
274. Problem BITCNT (8293. Bit count)
275. Problem LARSQR (8294. Largest Square in a Circle)
276. Problem AU12 (8360. Prime After N)
277. Problem AVION1 (8373. AVION)
278. Problem PRQUEUE (8377. PRAYER QUEUE)
279. Problem DOPECUP (8378. find seat in dope cup)
280. Problem DOPECNT (8379. count frequency of digits)

10
281. Problem ATTENDC (8380. COUNT ATTENDANCE)
282. Problem ZBROJ (8395. ZBROJ)
283. Problem GRDGOVT (8412. Greedy Government)
284. Problem CLNFORUM (8413. Clean the Forum Posts)
285. Problem PROBLEM1 (8437. MODULUS)
286. Problem PROBLEM2 (8439. VijayAndAjith)
287. Problem NOVICE41 (8440. Problem 1)
288. Problem NOVICE42 (8441. Problem 2)
289. Problem NOVICE44 (8443. Problem 4)
290. Problem NOVICE45 (8444. Problem 5)
291. Problem C1 (8450. C ONE )
292. Problem CTWO (8455. C TWO)
293. Problem PROBLEM5 (8458. ALIGNSUBRACT)
294. Problem PROBLEM6 (8459. AVERYEASYPROBLEM)
295. Problem C3 (8465. C THREE)
296. Problem AVG (8468. AVERAGE)
297. Problem CIRCINT (8492. Intersecting Circles)
298. Problem COLORF (8493. Colorful Blocks)
299. Problem LUCKYN (8494. Lucky Numbers)
300. Problem BTHSP (8524. Back to High School Physics)
301. Problem SKEWB (8530. Skew Binary)
302. Problem QUINEI (8543. The Quine )
303. Problem MAIN71 (8544. Lexicographical ordering)
304. Problem PL_QUINE (8548. Brainf_cked!)
305. Problem PROKT1 (8582. Data transfer)
306. Problem SUMOF (8584. Borders)
307. Problem FACKT (8585. Easy Factorials)
308. Problem PRIME (8586. Factorial factorisation)
309. Problem SSLIDE (8597. Super Slider)
310. Problem TPRIMPER (8621. Prime Permutations (easy))
311. Problem NOVICE51 (8646. A Simple Game )
312. Problem NOVICE52 (8647. String Game)
313. Problem NOVICE53 (8648. Square number game )
314. Problem NOVICE54 (8649. Prime game)
315. Problem NOVICE55 (8650. Grid painting)
316. Problem SSSP (8682. kjgfkjadsf)
317. Problem TEASTER (8749. Waiting for Easter)
318. Problem MAIN8_A (8754. Cout)
319. Problem MAIN8_B (8755. Overlapping Squares)
320. Problem SUMMIT (8790. Find summits)
321. Problem NDIGITS (8792. N - DIGIT NUMBERS)
322. Problem FEELUCK (8847. Google is Feeling Lucky)
323. Problem BRKTS (8865. Brackets)
324. Problem VKANTH (8897. Vadivu vs Kanth)
325. Problem NITHY (8900. LUCKYNINE)
326. Problem BF (8901. BRAINF__K DESIGN)
327. Problem ARTIST (8903. DRAWING IT)

11
328. Problem WAYS2 (8911. FREE PATHS)
329. Problem WAYS3 (8931. PATHS( no source code limit))
330. Problem LQDFARM (9015. FARMER)
331. Problem STRINGS (9025. String Search)
332. Problem MAGICSQU (9044. Magic Square!)
333. Problem DHCAT (9067. Đông hô cát)
334. Problem GRAPHS11 (9078. Graph basics concepts )
335. Problem GRAPHS12 (9082. Graph basics concepts)
336. Problem C11HIGH (9085. HIGH)
337. Problem NOVICE61 (9106. REARRANGE)
338. Problem NOVICE66 (9108. SHAKE)
339. Problem NOVICE67 (9109. NTH WORD)
340. Problem NOVICE68 (9110. TILE IT)
341. Problem NSUJ02A (9111. Prime Time)
342. Problem NSUJ03C (9113. Digibomb!)
343. Problem NSUJ02D (9114. String Game)
344. Problem NSUJ02E (9115. Prime Kitties)
345. Problem GRAPHS21 (9127. Graph basics concepts II)
346. Problem GRAPHS22 (9128. Graph basics concepts II)
347. Problem MAXNUM (9129. MAXNUM)
348. Problem REPTTS (9173. Repetitions)
349. Problem EDITV1 (9188. Edit Distance Variant 1)
350. Problem EDITV2 (9189. Edit Distance Variant 2)
351. Problem BINARY2 (9291. SPBINARY2)
352. Problem AUCSE012 (9333. Student Proxy)
353. Problem AUCSE015 (9339. Contains Prime)
354. Problem VUDAAB (9369. Progression)
355. Problem PS11A (9392. Play With Sequence)
356. Problem PS11F (9397. Memoria)
357. Problem ARTHOP (9414. Arithmetic Operations)
358. Problem ALLFIVE (9415. It is all about five)
359. Problem RELOP (9416. Relational Operators)
360. Problem ABCS (9417. ABCs)
361. Problem NUMAVG (9418. Number Average)
362. Problem ODDSUM (9420. Odd Sum)
363. Problem BEHOLD (9421. Behold My Quadrangle )
364. Problem DRIRA (9435. Driving Range)
365. Problem CELSP (9438. Celebrity Split)
366. Problem SPECTRUM (9465. Spectrum of colours)
367. Problem BITCNTR (9500. Bit counts)
368. Problem SETRR (9501. Best balanced diet)
369. Problem TETRSIGM (9514. Parsing URL)
370. Problem DEPART (9526. Department)
371. Problem PIPEJ (9530. Pipe)
372. Problem STIJ (9531. Sticks)
373. Problem KINDJ (9533. Kindergarten Counting Game)
374. Problem MODPOW (9536. Calculating very big numbers very quickly)

12
375. Problem SPOTIT (9573. Spot the largest string)
376. Problem NUMSTR (9594. Count the strings)
377. Problem MEGAUSS (9595. Fast addition)
378. Problem GETCORR (9598. Get me correct)
379. Problem C2011AA (9605. Warmup Problem A)
380. Problem DONOTHIN (9639. Doing Nothing)
381. Problem PCOUNT (9654. Prime Count)
382. Problem RIDDLE (9682. Bí hie^?m)
383. Problem WINMINE (9688. Winmine)
384. Problem BINPALI (9716. Binary Palindromes Set)
385. Problem JIMMY (9718. Lazy Jimmy)
386. Problem EINST (9720. Is he smart or is he smart)
387. Problem BST1 (9737. Traversal(Easy))
388. Problem FIBOFAST (9739. Not Fibonacci please)
389. Problem SCPC11E (9758. Slalom)
390. Problem TOPOSORT (9808. Topological Sorting)
391. Problem WPC4A (9815. Measuring the odds)
392. Problem WPC4B (9816. Lake of the dead)
393. Problem WPC4E (9819. Out of place)
394. Problem WPC4G (9821. Gaming begins here)
395. Problem DODUCK (9980. Door Enclosure)
396. Problem JO1 (9989. Judging Olympia)
397. Problem ZVONIMIR (10143. To nisu istine)
398. Problem QTKNAP (10174. Túi Fibonacci)
399. Problem QTBIT (10198. Tro cho+i 0 1)
400. Problem OVFL (10208. Overestimate)
401. Problem STRSPL (10209. Theory of Computation)
402. Problem COLL (10211. The Collatz Sequence)
403. Problem MAVRG (10212. Row Max Average)
404. Problem AMR11G (10234. Here Be Dragons)
405. Problem ACPC11A (10238. Arabic and English)
406. Problem JANKEN (10324. Rock-paper-scissors I)
407. Problem KDBGTST1 (10331. Sample)
408. Problem DIFFICUL (10333. DIFFICULT INTERVIEW)
409. Problem ROMANN (10347. Roman Numerals)
410. Problem QWERTY01 (10359. How many words(SHELL))
411. Problem QWERTY02 (10360. BF writing)
412. Problem QWERTY03 (10361. JAVA COUNTING)
413. Problem QWERTY04 (10362. TRIVIADOR)
414. Problem CODEIT01 (10364. TREE SHAPES)
415. Problem CODEIT02 (10365. PICK UP DROP ESCAPE)
416. Problem ABA12A (10373. Help Balaji!)
417. Problem IPLUS4 (10379. Number Divisiblity)
418. Problem CHECK2 (10426. Check)
419. Problem PERIAN (10427. Lost in Perian)
420. Problem TESTF (10484. testingC)
421. Problem S1P1 (10485. Calculate Distance)

13
422. Problem S1P2 (10486. Reverse number)
423. Problem S2P1 (10487. Calculator)
424. Problem S2P2 (10488. Stock market)
425. Problem S1P3 (10489. The GamE)
426. Problem S3P1 (10490. Integer palindrome)
427. Problem S3P2 (10491. GCD)
428. Problem S4P1 (10492. Sum of factorial)
429. Problem S5P1 (10493. Calculator for Arrays)
430. Problem S1P4 (10494. Celebration)
431. Problem S5P2 (10495. Count Primes)
432. Problem S2P3 (10496. Two Face on the high way)
433. Problem S3P3 (10497. Arithmetic and Geometric Sequences)
434. Problem S3P4 (10499. Draw Rectangle)
435. Problem KOPC12F (10518. K12-Counting Staircases)
436. Problem KAM1 (10552. KAM)
437. Problem SPRLNMS (10601. Spiral numbers)
438. Problem CRNI (10625. CRNI)
439. Problem BYTESA (10681. MAG)
440. Problem BYTESH (10703. HOSTAGES)
441. Problem TETRASUM (10724. Sum of Tetranacci numbers (easy))
442. Problem SBE201A1 (10742. Hello, World!)
443. Problem FACTCG (10817. Easy Factorization)
444. Problem SBE201A2 (10834. Travelled Distance)
445. Problem DOR16 (10942. deleted)
446. Problem INS1 (10972. RIAsDILEMMA)
447. Problem INS2 (10981. SimpleSort)
448. Problem ZOOS1 (10990. Zoos )
449. Problem BANKROBB (11031. Bank Robbers)
450. Problem MAXINARR (11032. Maximum element of an array)
451. Problem COUNTINV (11034. Count inversions in a small array)
452. Problem SBE201A4 (11053. Array Minimum)
453. Problem BSEARCH1 (11062. Binary search)
454. Problem GP2 (11065. GP - Complete the Series v1)
455. Problem KH00 (11091. PUTS)
456. Problem SYMN (11095. Symmetric or not)
457. Problem TRIZ (11096. Triple Zeros)
458. Problem EPO (11097. Easy Powers)
459. Problem FIBOFUN (11100. Fun with Fibonacci Series)
460. Problem MAIN12D (11106. Dice Problem)
461. Problem ELIS (11110. Easy Longest Increasing Subsequence)
462. Problem EELCS (11111. Easy Longest Common Subsequence)
463. Problem MWINNER (11114. Who Won the Match)
464. Problem CKTPALIN (11121. Palindromic Cricketer)
465. Problem OPC5 (11203. Auris Love)
466. Problem OPC3A (11210. Arya and the exponacci)
467. Problem HELLO (11226. Hello World!)
468. Problem NUMTRYE (11239. Number Theory (Easy))

14
469. Problem PWAD (11247. Plus Within a diamond)
470. Problem ACMCEG2A (11264. FUN WITH NUMBERS)
471. Problem ACMCEG2B (11265. FIGUREFUL)
472. Problem ACMCEG2C (11266. Pick the candies)
473. Problem COMPSEM0 (11317. MAX AREA)
474. Problem COMPSEM1 (11318. NEMO)
475. Problem COMPSEM2 (11319. TARANIAMITKAUSHIK)
476. Problem SORT2D (11323. 2D-SORT)
477. Problem TWOSQ (11331. Two Squares)
478. Problem VOWELS (11333. Vowels)
479. Problem TWINP (11341. TWIN PRIMES)
480. Problem DUCKS (11342. Here be ducks)
481. Problem SBE201A6 (11349. Tertiary Calculator)
482. Problem TWINP2 (11356. TWIN PRIMES)
483. Problem HSH1 (11364. Home, sweet home 1)
484. Problem SQ2SQ2 (11365. TSquare TO Square)
485. Problem ZOOMOP (11366. Zoom Operation)
486. Problem TSHOW2 (11368. Fibonacci brain)
487. Problem FAREWELL (11382. Quadra vs PussyCat)
488. Problem COVER01 (11387. Perfect Cover)
489. Problem FINDWORD (11390. Hidden Key)
490. Problem TECHELN5 (11398. Do You know your Algorithms)
491. Problem EASYMAT2 (11403. EASY MATH 2)
492. Problem VUDBOL4 (11457. New iPad)
493. Problem SHLF (11464. Book Shelves(tutorial))
494. Problem SALVA1 (11491. Addict to Letters)
495. Problem RPLF (11492. Fast Schedule)
496. Problem EASYMAT3 (11505. EASY MATH 3)
497. Problem DIE4MARK (11506. ANYTHING FOR ATTENDANCE)
498. Problem SPIRAL2 (11507. SPIRAL RUN)
499. Problem NARYTREE (11514. N-ARY TREE)
500. Problem CHOCLATE (11522. CHOCOLATES)
501. Problem IN1 (11537. FACTSUM)
502. Problem SQREASY (11556. Find the minimum no of squares)
503. Problem DUMBPROB (11559. Are you smart enough )
504. Problem CARDSMIS (11567. Find the missing card)
505. Problem MUSIC2 (11572. A Famous Music Composer)
506. Problem CLOCK2 (11581. The Famous Clock)
507. Problem SUMOFPOW (11600. Another Mathematical Problem)
508. Problem MINEF1 (11643. Cross dangerous minefields)
509. Problem COMPLEX1 (11722. HELP ABHISHEK)
510. Problem FFIRE (11728. Forest Fires)
511. Problem ARD2 (11788. Ishika and Kashish)
512. Problem SUMUP2 (11791. Integer Factorization With A Twist)
513. Problem BEANALGO (11807. Think Different)
514. Problem COMBD (11821. Combinatorial Sequence)
515. Problem POWRTU (11852. Power with Combinatorics(EASY))

15
516. Problem MAJORITY (11876. Finding Majority)
517. Problem RAED0001 (11877. Upcoming Demons)
518. Problem TRINO (11934. PUT TRINOMO)
519. Problem FIBBIT (11936. FIBO BIT)
520. Problem DOM519 (11937. The Dominoes Problem)
521. Problem OPCPRIME (11960. Prime Factorization)
522. Problem MNNNITPA (11961. Party trouble)
523. Problem PERMUN (11976. Permutation)
524. Problem OPC1708C (11989. Factorial large)
525. Problem OPC1708D (11990. Measuring Water)
526. Problem TLL238 (11993. Addicted II)
527. Problem DCEPC801 (11995. Family Problem)
528. Problem DCEPC802 (11996. Medal Tally)
529. Problem DCEPC805 (11999. Catalan Powered)
530. Problem KPB (12071. Point Blank)
531. Problem IIITA1 (12072. Playing With Bits)
532. Problem DCEPC901 (12073. Unique Numbers)
533. Problem DCEPC902 (12074. Magical Ladders)
534. Problem DCEPC903 (12075. Encryption)
535. Problem DCEPC904 (12077. Secret Code)
536. Problem DCEPC905 (12078. Picking Weights)
537. Problem DCEPC906 (12081. Picture Perfect)
538. Problem ACMPRAC1 (12083. Appetizer)
539. Problem ACMPRAC4 (12092. Dessert)
540. Problem ACMPRAC3 (12100. Main Course)
541. Problem ACMPRAC2 (12101. Entrée)
542. Problem RIOI_T_0 (12111. FirstProblem)
543. Problem RIOI_T_1 (12112. SecondProblem)
544. Problem ACMPRAC5 (12113. Exotic Drinks)
545. Problem ENCRPASS (12165. Encrypted String)
546. Problem REVNUMBE (12166. Reverse And Add)
547. Problem FIBTUTO (12167. Fibonacci starters)
548. Problem APGPTUT (12168. APGP Tutorial)
549. Problem LISTTUT (12169. General Number Series)
550. Problem KFSTD (12184. Help the statistics department)
551. Problem IOI11GAR (12186. Tropical Garden)
552. Problem AGRADE (12208. The Chain Reaction)
553. Problem KSEQ1 (12246. Day sô 1)
554. Problem SPEEDPYR (12271. Speed test - Pyramid version)
555. Problem SPEEDCUB (12272. Speed test - Cube version)
556. Problem NITT3 (12275. Meeting and Dating)
557. Problem NITT5 (12276. Subset and upset)
558. Problem WORDNUMS (12281. Word or number (Easiest))
559. Problem WORDNUM2 (12282. Word or number (easiest 2))
560. Problem WAVE (12283. Phu? sóng)
561. Problem NITT7 (12289. Grid Travel)
562. Problem PASO (12298. Tirate un paso)

16
563. Problem POWERSUM (12348. Sum of Subsets)
564. Problem TAP2012I (12372. In Debt)
565. Problem MAXEQUA (12395. Maximizing the equation)
566. Problem LCPC12A (12396. Johnny divides by 2)
567. Problem LCPC12I (12410. No more Johnny)
568. Problem LCPCP1 (12411. Johnny And Modulo)
569. Problem LCPCP2 (12412. Johnny Learns Modular exponentiation)
570. Problem JUNMC (12447. LOVER BOY)
571. Problem PERMU (12454. Permutation)
572. Problem RIOI_0_1 (12455. Order)
573. Problem NUMSERIE (12456. NUMBER SERIES)
574. Problem DOTAA2 (12457. HELP NERUBAN)
575. Problem RIOI_0_2 (12458. Unique strings)
576. Problem GOODMEAL (12460. Eat a Good Meal)
577. Problem SHARELET (12465. Shared Letters)
578. Problem CLOSPT (12466. Closest Points)
579. Problem KHALED (12470. Friend numbers)
580. Problem TECHOFES (12473. INVITATION FOR TECHOFES)
581. Problem STRINGPR (12509. STRING PROBLEM)
582. Problem JUMPDORA (12510. JUMPING DORA)
583. Problem CUBEROO2 (12511. CUBE ROOT)
584. Problem TECHOFEZ (12515. INVITATION FOR TECHOFES (v2))
585. Problem TIGA (12523. Nuts Frenzy)
586. Problem EFFECTIV (12540. It is Super Effective)
587. Problem CDC12_I (12564. Innovative Combination)
588. Problem SID (12579. Search Insert Delete)
589. Problem MO1002 (12596. Palindrom 1)
590. Problem DIGIT (12599. K-DIGITS)
591. Problem MO1003 (12602. Urvuu too)
592. Problem RIOI_2_1 (12607. Missing one )
593. Problem RIOI_2_2 (12608. Switch)
594. Problem EVENODD (12650. Even and Odd)
595. Problem ATWO (12793. The power of two)
596. Problem HISTORY2 (12801. Browsing History)
597. Problem PBBN1 (12823. Print Big Binary Numbers)
598. Problem QTANCOL (12851. Bâc thây pha che^’ ru+o+.u)
599. Problem QTLOVE (12856. Hoa hu+o+’ng du+o+ng)
600. Problem QTLOVE2 (12857. Hoa hu+o+’ng du+o+ng )
601. Problem LATARNIE (12861. LATARNIE JASIA)
602. Problem TA1 (12910. Addicted Numbers)
603. Problem HICHEEL (1004151. Zoos )

17
SPOJ Problem Set (tutorial)

244. Internally Stable Sets


Problem code: INTSS
A weighted finite undirected graph is a triple G = (V, E, w) consisting of vertex set V, edge set
[IMAGE] , and vertex weighting function w such that [IMAGE] and [IMAGE] . For [IMAGE] and
[IMAGE] , N(u) and N(K) will denote the neighboring vertex sets of u and K respectively, formally
defined as:
[IMAGE]
A vertex set [IMAGE] satisfying [IMAGE] is called internally stable (also known as independent or
anti-clique). In this problem you must find an internally stable set B such that w(B) = max{w(S)},
where S belongs to the set of all internally stable sets of that graph.

Input
t - the number of test cases [t <= 100]
n k - [n - number of vertices (2 <= n <= 200), k - number of edges (1 <= k <= n*(n-1)/2)]
then n numbers follows (wi - the weight of i-th vertex) [ 0 <= wi <= 2^31-1]
then k pairs of numbers follows denoting the edge between the vertices (si sj edge between i-th and j-th
verices) [1 <= si, sj <= n]

Output
For each test case output MaxWeight - the weight of a maximum internally stable set of the given
graph. [ 0 <= MaxWeight <= 2^31-1]

Example
Input:
2
5 6
10 20 30 40 50
1 2
1 5
2 3
3 4
3 5
4 5

4 4
10 4 10 14
1 2
2 3
3 4
4 1

Output:
70
20

1
Added by: Roman Sol
Date: 2004-12-14
Time limit: 21s
Source limit:50000B
Languages: All
Resource: ZCon

2
SPOJ Problem Set (tutorial)

360. Bottom Coder (Easy)


Problem code: BCEASY
Some of you may be familiar with the TopCoder (TM) contest. Its exact rules are not important for
this problem, but know that the most important part of it is writing a program according to the given
specification. Many times the contestant ends up with a program which would work perfectly - if only
he could change a couple of characters (like, replacing "=" by "==" in C, etc.). Unfortunately, even the
best programmers sometimes aren’t able to spot these tiny but necessary changes until it’s too late...
and that’s why we developed a brand-new BottomCoder training for them!
The idea is very simple - you’re given a problem specification, a source code, and a list of permitted
modifications. Your task is to find a modification which would cause the program to behave according
to the specification.
Specification: "Write a program which outputs EXACTLY 42 asterisks and NOTHING more (e.g.
NO end-of-line markers, like "\n", ...)"
The code you are supposed to modify:
int i, n=42;
main() {
for(i=0; i<n; i--) {
printf("*");
}
}

As this is a really, really simple problem, you are only permitted to make exactly ONE of these
modifications to the source: 1) Add one character to the source. 2) Delete one character from the
source. 3) Replace one character in the source by a different one.
Moreover, it would be definitely too easy if we asked you to find just one solution, so you’ll need to
find TWO DIFFERENT solutions in order to obtain credit for this problem. (There are exactly three
different solutions, so don’t worry, it can be done!)

Input
There is no input for given problem.

Output
Your submission should consist of two parts. The first part should contain the first of your solutions. A
single line with the letter "Q" follows. (Note that the letter Q is used as a separator. You will have to
do without inserting the letter Q in at least one of your solutions :) After this line you should add your
second solution.
You don’t need to worry much about the exact formatting of your submission. The exact judging
procedure will look as follows:
The first occurrence of the letter Q is found, the input is split into two parts. Any whitespace in each of
the parts is removed. It is checked whether the two submissions differ and whether each of them was
obtained from the original program by an allowed change. Each of your two submissions is compared
to each of the three correct solutions.

1
Example
Output:
int i, n=42; main(
){ for(i=0; i<n; i--) { printf("?"); } }
Q
int i, n=41; main() { for(i=0; i<n;i--) { printf("*"); } }

(syntactically valid (but incorrect) submission)

Added by: Roman Sol


Date: 2005-05-13
Time limit: 1s
Source limit:10000B
Languages: TEXT
Resource: IPSC 2005

2
SPOJ Problem Set (tutorial)

361. Bottom Coder (Hard)


Problem code: BCHARD
Some of you may be familiar with the TopCoder (TM) contest. Its exact rules are not important for
this problem, but know that the most important part of it is writing a program according to the given
specification. Many times the contestant ends up with a program which would work perfectly - if only
he could change a couple of characters (like, replacing "=" by "==" in C, etc.). Unfortunately, even the
best programmers sometimes aren’t able to spot these tiny but necessary changes until it’s too late...
and that’s why we developed a brand-new BottomCoder training for them!
The idea is very simple - you’re given a problem specification, a source code, and a list of permitted
modifications. Your task is to find a modification which would cause the program to behave according
to the specification.
Specification: "Write a program which outputs a short English text mentioning our partner
competition - IPSC. The text must consist of one or more English sentences and each sentence has to
contain one or more English words (sequences of only upper-case characters) separated by spaces.
Additionally, you may use certain punctuaction characters - namely ".!?,’". Try to obfuscate the
program as much as possible." The code you are supposed to modify:
#include <stdio.h>

int rex[5];

void f3(int *a) {


int i;
for (i=0; i<5; i++) a[i]=0;
}

int f2(int *a) {


int i;
for (i=0; i<5; i++) if (a[i]!=0) return 0;
return 1;
}

void f1(int *a) {


int i;
for (i=0; i<5; i++) {
a[i]++;
if (a[i]<100) break;
a[i]-=100;
}
for (i=4; i>=0 && a[i]>=rex[i]; i--)
if (a[i]>rex[i])
f3(a);
}

void f4(int *a) {


int i;
for (i=0; i<5; i++) {
a[i]--;
if (a[i]>=0) break;
a[i]+=100;
}

1
if (i>=5) for (i=0; i<5; i++) a[i]=rex[i];
}

void f7(int *a, int *b) {


int c[5];
f3(c); f3(a);
while(!f2(b)) { f1(a); f4(b); f1(c); }
while(!f2(c)) { f1(b); f4(c); }
}

void f9(int *a, int *b) {


f1(a);
while(!f2(b)) { f4(b); f1(a); }
}

void f8(int *a, int *b) {


int c[5], d[5];
f7(d, a);
f3(a); f1(a);
while(!f2(b)) { f7(c, d); f9(a, c); f4(a); f4(b); }
}

void f5(int *a, int *b) {


int c[5], d[5];
f7(d, a);
f3(a); f1(a);
while(!f2(b)) { f7(c, d); f8(a, c); f4(a); f4(b); }
}

void f10(int x) {
int rpl[]=
{80, 125, 111, 18, 59, 88, 88, 28, 65, 98, 119, 103, 101, 79, 107, 2, 16,
92, 102, 123, 103, 84, 112, 78, 68, 98, 65, 37, 105, 85, 107, 13, 45, 9,
104, 81, 21, 31, 55, 110, 78, 66, 66, 3, 77, 63, 16, 105, 15, 123, 16, 84,
31, 96, 4, 82, 82, 122, 68, 115, 35, 73, 3, 108, 115, 83, 15, 19, 31, 99, 5,
123, 24, 65, 36, 15, 75, 84, 4, 2, -1};

int i;
int a[5], b[5], c[5];

if (x<100000000 || x>200000000) return;


x--;
f3(rex); rex[4]=1;
for (i=0; rpl[i]!=-1; i++)
{
f3(a); a[0]=i+1;
f3(b); f1(b); f3(c); f1(b); f1(b);
f1(c); f1(b); f5(a, b);

f1(c);
while(!f2(a))
{
f3(b); b[0]=x%100; b[1]=x/100;
f4(a); f8(c, b);
}
rpl[i]^=c[1];
printf("%c", rpl[i]);
}
printf("\n");
}

2
int main()
{
f10(47);
}

As you can see, the coder made almost everything according to the specification :) You’re only
allowed to alter one number in the source code - namely the number 47 on line 98 (the argument of
function "f10" called from "main"). You can replace it by any integer between 100‘000‘000 and
200‘000‘000 inclusive.

Input
There is no input for given problem.

Output
Your submission should consist of two lines. The first line should contain the value of the constant -
an integer between 100‘000‘000 and 200‘000‘000 inclusive. The second line should contain the output
produced by the program if it were compiled and executed with the correct value of the constant.

Example
Output:
123456789
ARE YOU SOLVING IPSC PROBLEMS RIGHT NOW?

(syntactically valid (but incorrect) submission)

Added by: Roman Sol


Date: 2005-05-13
Time limit: 1s
Source limit:1000B
Languages: All
Resource: IPSC 2005

3
SPOJ Problem Set (tutorial)

440. The Turtle´s Shortest Path


Problem code: TSHPATH
Given a list of cities. Each direct connection between two cities has its transportation cost (an integer
bigger than 0). The goal is to find the paths of minimum cost between pairs of cities. Assume that the
cost of each path (which is the sum of costs of all direct connections belongning to this path) is at most
200000. The name of a city is a string containing characters a,...,z and is at most 10 characters long.

Input
s [the number of tests <= 10]
n [the number of cities <= 10000]
NAME [city name]
p [the number of neighbours of city NAME]
nr cost [nr - index of a city connected to NAME (the index of the first city is 1)]
[cost - the transportation cost]
r [the number of paths to find <= 100]
NAME1 NAME2 [NAME1 - source, NAME2 - destination]
[empty line separating the tests]

Output
cost [the minimum transportation cost from city NAME1 to city NAME2 (one per line)]

Example
Input:
1
4
gdansk
2
2 1
3 3
bydgoszcz
3
1 1
3 1
4 4
torun
3
1 3
2 1
4 1
warszawa
2
2 4
3 1
2
gdansk warszawa
bydgoszcz warszawa

1
Output:
3
2

Warning: large Input/Output data, be careful with certain languages

Added by: Michał Małafiejski


Date: 2004-10-21
Time limit: 25s
Source limit:50000B
Languages: All
DASM Programming League 2003 (thanks to Darek Dereniowski)
Resource:
a copy of SHPATH problem with 60s time limit

2
SPOJ Problem Set (tutorial)

450. Enormous Input Test


Problem code: INTEST
The purpose of this problem is to verify whether the method you are using to read input data is
sufficiently fast to handle problems branded with the enormous Input/Output warning. You are
expected to be able to process at least 2.5MB of input data per second at runtime.

Input
The input begins with two positive integers n k (n, k<=10 7 ). The next n lines of input contain one
positive integer t i , not greater than 10 9 , each.

Output
Write a single integer to output, denoting how many integers t i are divisible by k.

Example
Input:
7 3
1
51
966369
7
9
999996
11

Output:
4

Added by: Adrian Kosowski


Date: 2004-11-09
Time limit: 8s
Source limit:50000B
Languages: All
Resource: Idea put forward by Michael Mendelsohn

1
SPOJ Problem Set (tutorial)

453. Sums in a Triangle (tutorial)


Problem code: SUMTRIAN
This is problem SUMITR without strict source limit.

Let us consider a triangle of numbers in which a number appears in the first line, two numbers appear
in the second line etc. Develop a program which will compute the largest of the sums of numbers that
appear on the paths starting from the top towards the base, so that:

on each path the next number is located on the row below, more precisely either directly below or
below and one place to the right;
the number of rows is strictly positive, but less than 100;
all numbers are positive integers between O and 99.

Input
In the first line integer n - the number of test cases (equal to about 1000). Then n test cases follow.
Each test case starts with the number of lines which is followed by their content.

Output
For each test case write the determined value in a separate line.

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

Output:
5
9

Warning: large Input/Output data, be careful with certain languages

1
Added by: Łukasz Kuszner
Date: 2004-11-10
Time limit: 2s
Source
5000B
limit:
Languages: All
6-th International Olympiad In Informatics July 3-10. 1994. Stockholm - Sweden,
Resource:
Problem 1

2
SPOJ Problem Set (tutorial)

490. Armies
Problem code: ARMIES
Two enemy countries - Bajtocja and Megabajtolandia - are preparing for crucial war with each other.
Each country has built an army consisting of some number of divisions, and each division consists of
some number of soldiers. The way of waging the war, given by strategists from each contry, consists
of sending the division with the most man power to fight, i.e. starting from the most numerous division
to the least.

Thus, first each country will send its division with the most man power. If one of these divisions has
more soldiers than the other, then the war is over and the winner is the owner of the larger division. If
the man power of each of the divisions sent is the same then all the soldiers will kill each other and the
next most numerous division is sent to fight. The man powers of the second divisions decide the war if
and only if they are not the same. If not, the battle is carried on in aforementioned way. If, at some
moment, one army runs out of divisions and the second one does not, then the war is over and the first
army is the loser. If both armies run out of divisions then the war is over and there is a draw.
Give the result of the war, without any blood and murder.
Write a program, which:

reads from standard input the description of Bajtocja’s and Megabajtolandia’s army,
respectively,
computes the result of the war,
writes it to standard output.

Input
The first line of input contains one integer D (1<=D<=30) meaning the number of test cases. The
description of each test case contains 4 lines. In the first, there is one integer B (1 <= B <= 50 000)
meaning the number of divisions in Bajtocja’s army. The second line contains B integers b i (1 <= b i
<= 1 000 000 000) (separated by single space) meaning the man power (the number of soldiers) of
consequtive divisions of Megabajtolandia’s army. In the third line, there is one integer M (1 <= M <=
50 000) meaning the number of divisions of Megabajtolandia’s army. The fourth line contains M
integers m i (1 <= m i < = 1 000 000 000) (separated by single space) meaning the man power of
consequtive divisions of Megabajtolandia’s army.

Output
For each test case, your program should write, in separate lines, exactly one word:

"Bajtocja" in case the winner is Bajtocja,


"Megabajtolandia" in case the winner is Megabajtolandia,
"Draw" in case of a draw.

1
Example
Sample input:
3
3
1 3 4
3
4 4 1
4
2 5 3 4
3
5 6 4
4
6 1 2 5
4
5 2 6 1

Sample output:
Megabajtolandia
Megabajtolandia
Draw

Added by: Rafał Nowak


Date: 2005-02-07
Time limit: 3s
Source limit:5000B
Languages: All
Resource: Winter sparing in Poznan, Poznan 2005 (22th January)

2
SPOJ Problem Set (tutorial)

491. The Cursed Room


Problem code: MMATCH
There is a school trip being organized for kids. The hotel the group is staying in can offer them one big
room with enough beds to suit any group of visitors, and several smaller rooms with B beds
alltogether. The children have heard many strange and frightening stories about the big room. That’s
why not even one of them wants to sleep in the big room. Furthermore not every kid would like to
sleep in any bed.
Your goal is to assign B beds from the smaller rooms in such a way that the maximal number of
children are happy (a child is happy when it gets to sleep in one of the beds it has selected).

Input
The first line contains a positive integer t<=1000 indicating the number of test cases. Each test case is
an instance of the problem defined above. The first line of each test case is a pair of positive integers L
and B (the number of children L<=100 and beds B<=100). The next lines contain a sequence of (c,b)
pairs ending with two zeros. (c,b) means that the child c will be happy if it gets to sleep in bed b.

Output
For each test case print the maximal number of happy children.

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

1
0 0

Output:
3
3
2

Added by: Tomasz Niedzwiecki


Date: 2005-01-18
Time limit: 5s
Source limit:50000B
Languages: All

2
SPOJ Problem Set (tutorial)

500. Turbo Sort


Problem code: TSORT
Given the list of numbers, you are to sort them in non decreasing order.

Input
t - the number of numbers in list, then t lines follow [t <= 10^6].
Each line contains one integer: N [0 <= N <= 10^6]

Output
Output given numbers in non decreasing order.

Example
Input:
5
5
3
6
7
1

Output:
1
3
5
6
7

Added by: Roman Sol


Date: 2005-03-14
Time limit: 5s
Source limit:50000B
Languages: All except: ERL JS
Resource: ZCon

1
SPOJ Problem Set (tutorial)

503. Prime Intervals


Problem code: PRINT
In this problem you have to print all primes from given interval.

Input
t - the number of test cases, then t lines follows. [t <= 150]
On each line are written two integers L and U separated by a blank. L - lower bound of interval, U -
upper bound of interval. [2 <= L < U <= 2147483647] [U-L <= 1000000].

Output
For each test case output must contain all primes from interval [L; U] in increasing order.

Example
Input:
2
2 10
3 7

Output:
2
3
5
7
3
5
7

Added by: Roman Sol


Date: 2005-03-28
Time limit: 9s
Source limit:15000B
Languages: All
Resource: ZCon

1
SPOJ Problem Set (tutorial)

511. Easy Sorting


Problem code: LEXISORT
Given is a list of words and a lexicographical ordering according to the ascii alphabet. Your task is to
sort the words in increasing order.

Input
The first line contains the numbers of testcases k (k< 100). Every testcase c onsists of n+1 (1< n<
50000) lines. Each line contains of a string of 10 character s. The first line of each testcase contains n.

Output
Output the sorted list of words.

Example
Input:
2
2
helloworld
worldhello
2
aaaaaaaaaa
Aaaaaaaaaa
Output:
helloworld
worldhello
Aaaaaaaaaa
aaaaaaaaaa

Added by: Simon Gog


Date: 2005-04-13
Time limit: 4s
Source limit:8083B
Languages: All

1
SPOJ Problem Set (tutorial)

527. Just for Fun (Easy)


Problem code: J4FUN
birds
Puzzle ID: birds
Ten birds sit on a clothes line. We shoot and kill one of them. How many birds remain on the clothes
line?
The answer for this puzzle consists of two lines, containing respectively:
- the ID of this puzzle
- one number: the number of birds that remain on the clothes line
bus
Puzzle ID: bus
A bus was travelling with less than 100 passengers. At stop A, exactly three quarters of the passengers
got off and 7 passengers got on the bus. The same thing happened at next two stops, B and C. How
many people got off at the stop C?
The answer for this puzzle consists of two lines, containing respectively:
- the ID of this puzzle
- the number of people getting off at C
palindrome
Puzzle ID: palindrome
Suppose we write dates in the MMDDYYYY format. In this format, the 2nd of October 2001 is a
palindrome (a string equal to its reverse): 10022001. Find the previous date that yields a palindrome in
this format.
The answer for this puzzle consists of two lines, containing respectively:
- the ID of this puzzle
- the 8-digit string
cube
Puzzle ID: cube
You have a cube NxNxN. How many straight cuts are necessary to cut it into N^3 cubes of size
1x1x1? You may arrange the pieces in any way you like before making each cut.
a) Solve for N=3
b) Solve for N=4
The answer for this puzzle consists of three lines, containing respectively:
- the ID of this puzzle
- the number of cuts from part a)
- the number of cuts from part b)
girl1
Puzzle ID: girl1
In a two-child family, one child is a boy.
What is the probability that the other child is a girl?
The answer for this puzzle consists of two lines, containing respectively:
- the ID of this puzzle
- the answer in the form a/b (where a,b are relatively prime)
girl2
Puzzle ID: girl2

1
In an unnamed overpopulated country the rulers agreed on a new law: Each woman may have as many
children as she wants to, until she gives birth to a girl. After that, she may have no more children.
Assume that the law will never be broken. All families will have as many children as they are
(physically and legally) able to. On each birth either one boy or one girl is born with equal chances. In
the current population the ratio males:females is 1:1. What will happen in the next 100 years?
A) The ratio of males to females will go up
B) The ratio of males to females will stay the same
C) The ratio of males to females will go down
The answer for this puzzle consists of two lines, containing respectively:
- the ID of this puzzle
- the uppercase letter corresponding to the correct answer
statements
Puzzle ID: statements
Given is a list with 2004 statements:
1. Exactly one statement on this list is false.
2. Exactly two statements on this list are false.
3. Exactly three statements on this list are false.
...
2004. Exactly 2004 statements on this list are false.
a) Determine which statements are true.
b) Replace "exactly" by "at least". Again, determine which statements are true.
The answer for this puzzle consists of three lines, containing respectively:
- the ID of this puzzle
- the encoded answer from part a)
- the encoded answer from part b)
How to encode the answer? If no statements are true, write the word ’NONE’ (without the quotes).
Otherwise take the set of true statements and write it as a set of ranges. E.g. the set {1,2,3,7,9,100,101}
is encoded as 1-3,7,9,100-101
letters
Puzzle ID: letters
How many letters does the _shortest_ correct answer to this puzzle contain?
The answer for this puzzle consists of two lines, containing respectively:
- the ID of this puzzle
- your exact answer
century
Puzzle ID: century
The twentieth century ended on 31. 12. 2000, which was a Sunday. Looking into the future, on which
days of the week won’t any century ever end?
Remember that leap years are those divisible by 400 plus those divisible by 4 but not by 100. (1996
was a leap year, so was 2000, but 2100 won’t be a leap year and neither will 2047.)
The answer for this puzzle consists of two lines, containing respectively:
- the ID of this puzzle
- the days of the week on which no century will ever end
The exact form of the answer is a comma-separated list of three-letter abbreviations of the days in the
order in which they appear in a week. E.g. if the answer were Monday, Tuesday and Wednesday, write
the string ’Mon,Tue,Wed’ (without the quotes).

2
Input
There is no input for given problem.

Output
Output answers for each puzzle described below in the order they was described.

Example
Output:
birds
100
bus
10000
...

Added by: Roman Sol


Date: 2005-05-18
Time limit: 1s
Source limit:10000B
Languages: C99 strict TEXT
Resource: IPSC 2005

3
SPOJ Problem Set (tutorial)

536. How many Fibs


Problem code: TFIB
Recall the definition of the Fibonacci numbers:

f 1 := 1
f 2 := 2
f n := f n-1 + f n-2 (n>=3)

Given two numbers a and b, calculate how many Fibonacci numbers are in the range [a,b].

Input
The input contains several test cases. Each test case consists of two non-negative integer numbers a
and b. Input is terminated by a=b=0. Otherwise, a<=b<=10 100 . The numbers a and b are given with
no superfluous leading zeros.

Output
For each test case output on a single line the number of Fibonacci numbers f i with a<=f i <=b.

Example
Input:

10 100
1234567890 9876543210
0 0

Output:

5
4

Added by: Adrian Kuegel


Date: 2005-07-05
Time limit: 10s
Source limit:50000B
Languages: All
Resource: University of Ulm Local Contest 2000

1
SPOJ Problem Set (tutorial)

644. Byteland Money Exchange


Problem code: PAYBACK
In Byteland after the food shortage banks made credit payment freely available. At the end of the year
companies have to settle their debts and to give a statement on their cashflow to the Claim Office.
Among Banks and Companies a net of debts was created. Unfortunetely Banks gave a sky-high price
on money transfers. For company owners it was unprofitable to pay all money transfers as they were.
They chose you to help them out. Your assignment is to balance the debt network.
>
> You are given [t<=1000] test cases- a test case consists of the size [N<=1000] of the debt network,
followed by a description of the network itself. Each line consists of integers separated by spaces
ending with a new line. Each value states how much money the company in line "i" is in debt to
company "j" where "j" is the column number.
>
> Your assignment is to limit the number of money transfers by determining which companies are in
debt, which have earned money and which have shown neither profit nor loss.
>
>

Input
t [- test cases]
> N [- size of the debt net]
> a[1,1] a[1,2] a[1,3] ... a[1,n]
> a[2,1] a[2,2] a[2,3] ... a[2,n]
> ...[[debt size for each company - a[1,3] denotes the sum borrowed by company 1 from 3]]
> ...
> a[n,1] a[n,2] a[n,3] ... a[n,n]
> [empty line]
> [next test case]
>
> a graphical example
>
> INPUT Graph
>
>

Output
T[Size of solution]
> a[1,1] a[1,2] a[1,3] ... a[1,n]
> a[2,1] a[2,2] a[2,3] ... a[2,n]
> ...[[debt size for each company - a[1,3] denotes the sum borrowed by company 1 from 3]]
> ...
> a[n,1] a[n,2] a[n,3] ... a[n,n]

1
> [empty line]
> [next solution]
>

> [All the output data should be integers.]


> Text grouped in [ ] does not appear in the input file.
>
> a graphical example
>
> OUTPUT Graph1
>
> a graphical example- same input
>
> OUTPUT Graph2
>
>

Example
Input:
1
7
0 18 25 34 14 21 40
44 0 64 0 11 5 24
11 35 0 23 17 26 23
19 50 20 0 16 7 0
0 14 9 0 0 27 18
42 5 17 8 3 0 17
36 26 0 47 7 6 0

Output:
7
0 10 0 0 0 0 0
0 0 0 0 0 0 0
0 12 0 0 0 6 3
0 0 0 0 0 0 59
0 0 0 0 0 0 29
0 0 0 0 0 0 0
0 0 0 0 0 0 0

Added by: Sylwester Herber


Date: 2005-12-01
Time limit: 10s
Source limit:50000B
Languages: All
Resource: inspired by "Algorithm Complexity Theory" project assignment 2002

2
SPOJ Problem Set (tutorial)

691. Hotel Floors


Problem code: HFLOOR
We are given a top view of a hotel floor, which is represented by an MxN matrix of characters,
composed of (only) the following:

’#’ is a Wall
’-’ is Free Space
’*’ is an occupied space (by a single person).

We are required to evaluate the average number of people living in a room.

Constraints:
M, N <= 100
Number of test-cases<= 10
All border edges of the map will be walls.
There will be at least one room.

Input
The 1st line contains the number of test inputs, with each test case consisting of:
MN
MxN matrix of characters

Output
For each test case output a line with the average number of people living per room, rounded to exactly
two decimal places.

Example
Input:
2
5 5
#####
#**##
###*#
#**##
#####
6 10
##########
#---*--*##
###-*----#
#**#######
##***---##

1
##########

Output:
1.67
4.00

Added by: Prasanna


Date: 2006-01-12
Time limit: 1s
Source limit:50000B
Languages: All
Resource: ByteCode ’06

2
SPOJ Problem Set (tutorial)

692. Fruit Farm


Problem code: FFARM
We visited a farm, which was barren except for certain points in which fruit trees existed. In general it
was true that only places with palindromic indices contained fruit trees. We are required to buy a
subregion of this farm of length at most L so that our aims (in the given priority) are satisfied best.

1. Maximize the amount of fruit trees present in it.


2. Minimize the size (length) of the farm bought.
3. Select the farm whose beginning is leftmost.

Input
The 1st line contains the number of test cases, T<=20, each test case:
ABL
where [A,B] is the closed interval of land which we visited.

Output
SE
where [S,E] is the closed interval of land which we buy.
If there is no fruit-tree in the visited interval, print "Barren Land."

Constraints:
1<=A<=B<=1000

Example
Input:
6
1 10 5
800 1000 5
80 120 5
30 60 12
12 18 40
23 30 10

Output:
1 5
808 808
99 101
33 44
Barren Land.
Barren Land.

1
Added by: Prasanna
Date: 2006-01-13
Time limit: 1s
Source limit:50000B
Languages: All
Resource: ByteCode ’06

2
SPOJ Problem Set (tutorial)

732. Johnsons Algorithm


Problem code: JHNSN
Johnson’s algorithm solves the all-pairs shortest path problem in a weighted, directed graph.

Input
t [number of test graphs]

[description of each graph]


n [number of nodes, 1<=n<=100]
m [number of edges, m>=0]
[next the list of edges, one edge per line]
u v w [e(u,v) - edge from node u to node v with weight w]
[1<=u<=n, 1<=v<=n, -1000<=w<=1000]
... [next edge]

[next graph]
...

Output
If the i-th test graph has negative weight cycles, then the answer should be:
graph i no [where ’i’ is the number of the graph, 1<=i<=t]

Otherwise you should output the following data:


graph i yes

[vector of function h(v)]


h 1 h 2 ... h n+1

[matrix d[u,v], the solution of the all-pairs shortest path problem]


d 1,1 d 1,2 ... d 1,n
d 2,1 d 2,2 ... d 2,n
... ... ... ...
d n,1 d n,2 ... d n,n
[if the path doesn’t exist, you should output # instead]

Example
Input:
6

2
2
1 2 -2
2 1 1

1
8
1 2 8
1 6 6
6 2 3
2 3 -1
3 6 -2
6 5 -2
5 4 2
3 4 3

4
4
1 2 1
2 3 2
3 4 3
4 1 0

2
0

1
0

2
2
1 2 -1
2 1 0

Output:
graph 1 no

graph 2 yes

0 0 -1 -3 -5 -3 0

0 8 7 5 3 5
# 0 -1 -3 -5 -3
# 1 0 -2 -4 -2
# # # 0 # #
# # # 2 0 #
# 3 2 0 -2 0

graph 3 yes

0 0 0 0 0

0 1 3 6
5 0 2 5
3 4 0 3
0 1 3 0

graph 4 yes

0 0 0

0 #
# 0

graph 5 yes

0 0

2
0

graph 6 no

Added by: Bartłomiej Kowalski


Date: 2006-02-05
Time limit: 10s
Source limit:50000B
Languages: All
Resource: http://www.sphere.pl/~deren/gms/03_najkrsc2.pdf

3
SPOJ Problem Set (tutorial)

762. Problems Collection (Volume 1)


Problem code: PCV1
Problem 1 It is easily proved that no equilateral triangle exists with integral length sides and integral
area. However, the almost equilateral triangle 5-5-6 has an area of 12 square units. We shall define an
almost equilateral triangle to be a triangle for which two sides are equal and the third differs by no
more than one unit. Find the sum of the perimeters of every almost equilateral triangles with integral
side lengths and area and whose perimeters do not exceed one billion (1,000,000,000).
Problem 2 If a box contains twenty-one coloured discs, composed of fifteen blue discs and six red
discs, and two discs were taken at random, it can be seen that the probability of taking two blue discs,
P(BB) = (15/21)*(14/20) = 1/2. The next such arrangement, for which there is exactly 50% chance of
taking two blue discs at random, is a box containing eighty-five blue discs and thirty-five red discs. By
finding the first arrangement to contain over 10^12 = 1,000,000,000,000 discs in total, determine the
number of blue discs that the box would contain.
Problem 3 Consider the fraction, n/d, where n and d are positive integers. If n < d and HCF(n,d)=1, it
is called a reduced proper fraction. If we list the set of reduced proper fractions for d <= 8 in ascending
order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5,
5/6, 6/7, 7/8 It can be seen that there are 3 fraction between 1/3 and 1/2. How many fractions lie
between 1/3 and 1/2 in the sorted set of reduced proper fractions for d <= 10,000?
Problem 4 The series, 1^1 + 2^2 + 3^3+ ... + 10^10 = 10405071317. Find the last ten digits of the
series, 1^1 + 2^2 + 3^3+ ... + 1000^1000
Problem 5 The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104
(384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three
permutations of its digits which are also cube. Find the smallest cube for which exactly five
permutations of its digits are cube.
Problem 6 Euler’s Totient function, phi(n), is used to determine the number of numbers less than n
which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively
prime to nine, phi(9) = 6. Interestingly, phi(87109) = 79180,and it can be seen that 87109 is a
permutation of 79180. Find the value of n, below ten million, for which phi(n) is a permutation of n
and the ratio n/phi(n) - produces a minimum.
Problem 7 The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11
+ 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The
longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is
equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive
primes? (Integer 1 isn’t prime)
Problem 8 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers
which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they
are not included.
Problem 9 A permutaion is an ordered arrangement of objects. For example, 3124 is one possible
permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or
alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012,
021, 102, 120, 201, 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6,
7, 8 and 9?
Problem 10 By counting carefully it can be seen that a rectangular grid measuring 3 by 2 contains
eighteen rectangles. Although there exists no rectangular grid that contains exactly two million

1
rectangles, find the area of the grid with the nearest solution.

Input
There is no input for this problem.

Output
Output answer as the set of lines. On each line first is number of problem and second is answer for this
problem. If any of answers will be incorrect, you’ll recieve Wrong Answer.

Score
For each solved problem you’ll recieve exactly one point (10 points maximum, if all problems are
solved correctly).

Example
Output:
1 6174046
2 6568127473
5 806257
8 51146700

It’s just the example how output would look like. If all 4 answers correct (1, 2, 5 and 8 problems),
you’ll recieve 4 points.

Added by: Roman Sol


Date: 2006-01-23
Time limit: 1s
Source limit:5000B
Languages: TEXT
Resource: ZCon 2006

2
SPOJ Problem Set (tutorial)

1023. Arranging Dominoes


Problem code: ADOMINO
Dominoes have long entertained both game enthusiasts and programmers for quite some time. Many
games can be played with dominoes, including multiplayer and single player games. Hari Khan has
come up with a single player game. He takes N boxes and arranges them in a row at positions N 1 , N 2
... N N . Now he has to place D dominoes (D <= N) in the boxes such that the minimum distance
between any two filled boxes is maximized.

Input
The first line of the input contains an integer t, the number of test cases. t test cases follow.

The first line of each test case consists of two integers, N <= 100000 and D <= N, separated by a
single space.

N lines follow, each containing a single integer N i <= 1000000000, indicating the location of the i th
box.

Output
For each test case, output a single line containing a single integer denoting the largest minimum
distance achievable between any two boxes with dominoes.

Example
Input:
1
5 3
1
2
3
4
5

Output:
2

Added by: Matthew Reeder


Date: 2006-10-29
Time limit: 3s
Source limit:30000B
Languages: All
Resource: Al-Khawarizm 2006

1
SPOJ Problem Set (tutorial)

1118. Snowman
Problem code: SNOWMAN
Finally the time of the year has come where children can build snowmans. The children have collected
some snow and ask you how big the snowman is going to be.

Assume that the snowman will consist of three spheres stacked on top of each other. The lower two
spheres are of equal size, the smaller sphere (used for the head) will have a radius of 25 percent of the
radius of the larger spheres.

Input
The first line of the input contains a number t <= 100, which indicates the number of test cases to
follow. Each test case consists of a line with one integer a <= 500000, the amount of snow in cm 3 .

Output
For each test case, print a line with the height of the snowman in cm. Round this number down to the
next smaller integer.

Example
Input:
2
100
500000

Output:
10
175

Added by: Adrian Kuegel


Date: 2006-11-28
Time limit: 5s
Source limit:5000B
Languages: All

1
SPOJ Problem Set (contest)

1238. Special Nim Game


Problem code: NIMGAME
In this variant of the Nim game, a pile of N stones is placed between two players. The players take
alternating turns and remove some stones. The player who takes the last stone wins.

There are two restrictions however:

1. The first player has to remove between 1 and N-1 stones.


2. After the first move, the next player has to remove between 1 and 2.k stones, where k is the
number of stones removed in the last move.

If both players play perfectly, then it is possible to determine which player will win the game. Note
that during the game the game state can be described by the number of remaining stones and the
number of stones which can be taken in the next move. Each game state is either a winning position or
a losing position.

You have to determine for which values of N (2 <= N <= 2000) the second player has a winning
strategy.

Input
There is no input for this problem.

Output
Print the values N for which the second player has a winning strategy.

Example
Output:
2
3
5
...
1597

Obviously, the example output is incomplete and shows only the first three values and the last value to
be printed.

Added by: Adrian Kuegel


Date: 2007-01-18
Time limit: 5s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

1239. Recurrence Equation Finder


Problem code: RECEQU
Many problems have solutions involving linear recurrence equations of the form f(n) = a . f(n-1) + b .
f(n-2) (n >= 2). Usually the coefficients a and b are between 0 and 10, so it would be useful to have a
program which checks if some given values can be produced by such a recurrence equation. Since the
growth of the values f(n) can be exponential, we will consider the values modulo some integer
constant k.

More specifically you will be given f(0), f(1), k and some value pairs (i , x i ), where x i is the
remainder of the division of f(i) by k.

You have to determine coefficients a and b for the recurrence equation f such that for each given value
pair (i, x i ) the equation x i = f(i) mod k holds.

Hints
You can write the recurrence equation as follows:

Let [IMAGE] n , the identity A n = (A n div 2 ) 2 . A n mod 2 may be used. Also, (a . b) mod c = ((a mod c) . (b mod c)) mod c.

Input
The first line of the input contains a number T <= 20 which indicates the number of test cases to follow.
Each test case consists of 3 lines.
The first line of each test case contains the three integers f(0), f(1) and k, where 2 <= k <= 10000 and 0 <= f(0),f(1) < k

Output
For each test case print one line containing the values a and b separated by a space character, where 0 <= a,b <= 10.
You may assume that there is always a unique solution.

Example

1
Input:
2
1 1 1000
3
2 2 3 3 16 597
0 1 10000
4
11 1024 3 4 1000000000 4688 5 16

Output:
1 1
2 0

Added by: Adrian Kuegel


Date: 2007-01-18
Time limit: 10s
Source limit:50000B
Languages: All

2
(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 (tutorial)

1279. Run Length Decoding


Problem code: RLDEC
Your task is to write a program that decodes a sequence of characters which was encoded using a
simple form of run-length encoding, as described by the rules below.

Any sequence of between 2 to 9 identical characters is encoded by two characters. The first character
is the length of the sequence, represented by one of the characters 2 through 9. The second character is
the value of the repeated character. A sequence of more than 9 identical characters is dealt with by first
encoding 9 characters, then the remaining ones.

Any sequence of characters that does not contain consecutive repetitions of any characters is
represented by a 1 character followed by the sequence of characters, terminated with another 1. If a 1
appears as part of the sequence, it is escaped with a 1, thus two 1 characters are output.

Input
The first line in the input contains a number T <= 200 which specifies the number of test cases to
follow. Each test case consists of one line with the encoding of a sequence of characters. Each line
consists of letters (both upper- and lower-case), digits, spaces, and punctuation and is terminated with
a newline character. No other characters appear in the input. You may assume that each line is a valid
encoding of some sequence of characters.

Output
For each line in the input print one line with the decoded sequence of characters.

Example
Input:
3
9A1ABC131
1112 3124
1112111

Output:
AAAAAAAAAABC111
12 344
121

1
Added by: Adrian Kuegel
Date: 2007-01-27
Time limit: 10s
Source limit:50000B
Languages: All except: ERL JS PERL 6

2
SPOJ Problem Set (contest)

1282. How many Islands


Problem code: COUNTISL
You are given a simple map of an archipelago. Can you determine how many islands it shows?

The map consists of grid squares with characters, where ’#’ indicates land and ’.’ indicates water. Two
land squares belong to the same island if they are neighbouring grid squares, which means their x
coordinates and y coordinates differ by at most 1.

Input
The first line of the input contains a number T <= 20 which indicates the number of test cases to
follow.

Each test case starts with a line containing two numbers n and m (1 <= n,m <= 200), the number of
rows and the number of columns of the grid, respectively. The following n lines contain m characters
each and describe the map to be processed. You may assume that the map contains only characters ’#’
and ’.’, and that the border of the map consists only of water (character ’.’).

Output
For each test case print in a line the number of islands shown on the corresponding map in the input.

Example
Input:
2
1 1
.
6 4
....
..#.
.#..
....
.##.
....

Output:
0
2

Added by: Adrian Kuegel


Date: 2007-01-29
Time limit: 10s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

1392. Sum of Factors


Problem code: CZ_PROB2
Find the sum of the factors of a number including 1 and the given number.

Input
Number of test cases T followed by T lines of number n.
0 < T <= 5000
0 < n <= 999999999
Note: The number will not have a very large prime factor.

Output
The sum of the factors for each test case.

Example
Input:
2
6
5
Output:
12
6

Added by: Rahul


Date: 2007-03-10
Time limit: 1s
Source limit:4000B
Languages: All
Resource: Siddharth Agarwal

1
SPOJ Problem Set (tutorial)

1393. Ping Pong Probability


Problem code: CZ_PROB3
Two Ping Pong players agree to play several games. The players are evenly matched. However, the
person serving first has a probability p of winning that game. A serves the first game and thereafter the
loser serves first. What is the Probability that A wins the nth game?

Input
Number of test cases T followed by T lines of ’n’ - the number of games played; and ’p’ probability of
person serving first winning.
0 < T < 100

Output
Print for each test case the probability of A winning.
Please print a double value.

Example
Input:
2
4 0.7
7 0.7

Output:
0.4872
0.500819

Added by: Rahul


Date: 2007-03-10
Time limit: 1s
Source limit:5000B
Languages: All
Resource: Dilip Rajeev

1
SPOJ Problem Set (tutorial)

1394. Dividing Spaces


Problem code: CZ_PROB4
Into how many parts can k cuts using an n-1 dimensional hyper-plane divide an n- dimensional
hypercube?
Hint: Experiment with n=2, n=3 find a pattern
Eg: n=3, k=5 => dividing a cube with 5 cuts using planes.

Input
T, number of test cases followed by T lines of ’n’ and ’k’.

Output
The number of parts in separate lines for each of ’T’ test cases.

Example
Input:
2
14 20
6 23

Output:
1026876
145499

Added by: Rahul


Date: 2007-03-11
Time limit: 10s
Source limit:50000B
Languages: All
Resource: Dilip Rajeev

1
SPOJ Problem Set (tutorial)

1397. Put Them on a Circle


Problem code: CZ_PROB7
An array of numbers ( N1, N2, N3... Nn) is given. The numbers are to be placed on a circle such that
the sum of any two adjacent numbers is not divisible by a number in the set of Numbers V1, V2
,V3...Vk . Write a function, that given N and V determines if such an arrangement exists.

Input
T, the number of test-cases.
For each test case: Input array size of N, ’n’ and array size of V, ’k’. This is followed by one line of
values of array N (separated by spaces) and then one line of values of array ’V’(separated by spaces).

Output
For each test case print "yes" or "no" on a separate line.

Example
Input:
2
9
3
1 2 3 4 5 6 7 8 9
3 5 7
9
3
1 2 3 4 5 6 7 8 9
1 2 3

Output:
yes
no

Added by: Rahul


Date: 2007-03-11
Time limit: 3s
Source limit:7000B
Languages: All
Resource: Dilip Rajeev

1
SPOJ Problem Set (main)

1415. Problems Collection (Volume 2)


Problem code: PCV2
Problem 1 How many consecutive positive integers can you find, such that the sum of digits (in
decimal representation) of each of them is not divisible by 13?
Note: Because 49 is the first number for which the sum of digits divisible by 13, so for instance
integers from 1 to 48 satisfy the condition.
Problem 2 You can find the solution in this file: answer.zip
Problem 3 Find the answer in this picture:

Find the Answer

Problem 4 When looking at a number from left-to-right, if no digit is smaller than the digit to its left,
then the number is called increasing; for example, 125589.
Similarly if no digit is smaller than the digit to its right, the number is called decreasing; for example,
995421.
We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for
example, 64783.
Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers
below one-thousand (525) are bouncy. In fact, the smallest number for which the proportion of bouncy
numbers first exceeds 50% is 538. Bouncy number become more and more common and by the time
we reach 21780 the proportion of bouncy numbers is equal to 90%.
Find the least number for which the proportion of bouncy numbers is exactly 99%.
Problem 5 The radical of n, rad(n) - is the product of distinct prime factors of n. For example, 1008 =
2^4*3^2*7 , so rad(1008) = 2*3*7 = 42.
If we calculate rad(n) for 1 <= n <= 10, then sort them with respect to rad(n), breaking ties by sorting
with respect to the value of n, we get:
Unsorted:
n = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
rad(n) = 1, 2, 3, 2, 5, 6, 7, 2, 3, 10
Sorted:
n = 1, 2, 4, 8, 3, 9, 5, 6, 7, 10
rad(n) = 1, 2, 2, 2, 3, 3, 5, 6, 7, 10
k = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Let E(k) be the kth element in the sorted n column; for example, E(4) = 8 and E(6) = 9.
If rad(n) is sorted for 1 <= n <= 100000, find E(10000).
Problem 6 Consider the infinite polynomial series: AF(x) = x*F(1) + x^2*F(2) + x^3*F(3) + ..., where
F(k) is the kth term in the Fibonacci sequence: 1, 1, 2, 3, 5, 8, ..., that is, F(1) = 1; F(2) = 1; F(k) =
F(k-1) + F(k-2).
For this problem we shall be interested in values of x for which AF(x) is a positive integer.
Surprisingly AF(1/2) = 1/2 + 1/4 + 2/8 + 3/16 + 5/32 + ... = 2
The corresponding values of x for the first five natural numbers are shown below:
1) x = sqrt(2)-1 AF(x) = 1
2) x = 1/2 AF(x) = 2
3) x = (sqrt(13)-2)/3 AF(x) = 3
4) x = (sqrt(89)-5)/8 AF(x) = 4

1
5) x = (sqrt(34)-3)/5 AF(x) = 5
We shall call AF(x) a golden nugget if x is rational, because they become increasingly rarer; for
example, the 10th golden nugget is 74049690.
Find the 15th golden nugget.
Problem 7 Euler’s totient function F(n) is defined as the number of positive integers not exceeding n
that are relatively prime to n, where 1 is counted as being relatively prime to all numbers. So, for
example, F(20) = 8, because the eight integers 1, 3, 7, 9, 11, 13, 17, and 19 are relatively prime to 20.
The table below shows values of F(n) for the first 10 integers:
F(1) = 1, F(2) = 1, F(3) = 2, F(4) = 2, F(5) = 4,
F(6) = 2, F(7) = 6, F(8) = 4, F(9) = 6, F(10) = 4
Euler’s totient valence function v(n) is defined as the number of positive integers k such that F(k) = n.
For instance, v(8) = 5 because only the five integers k = 15, 16, 20, 24, and 30 are such that F(k) = 8.
The table below shows values of v(n) for n <= 16. (For n not in the table, v(n) = 0).

n v(n) k such that F(k)=n


1 2 1, 2
2 3 3, 4, 6
4 4 5, 8, 10, 12
6 4 7, 9, 14, 18
8 5 15, 16, 20, 24, 30
10 2 11, 22
12 6 13, 21, 26, 28, 36, 42
16 6 17, 32, 34, 40, 48, 60

Evaluate v(2^1000).
Problem 8 In how many ways can 50! be expressed as a sum of two or more consecutive positive
integers?
Problem 9 Imagine you have a crystal in the shape of an equilateral triangle, one unit long on each
side. In the right conditions, the crystal starts to grow. After one minute, two sides grow from each
side of the triangle that are perfectly symmetrical. The result is a six-pointed star, that has sides that
are exactly 1/3 of the length of the side they grew from. After another minute, each side sprouts two
more sides that are exactly 1/3 of the length of the side they came from. See the pictures to get a better
idea:

[IMAGE] [IMAGE]
[IMAGE] [IMAGE]
[IMAGE] [IMAGE]
[IMAGE] [IMAGE]

Your challenge is to find the perimeter (rounded to the nearest whole number) after one hour,
thirty-three minutes.
Problem 10 One more picture:

Number 758932

2
Input
There is no input for this problem.

Output
Output the answer as a set of lines. In each line first give the number of the problem and then the
answer to this problem. If any of the answers are incorrect, you will receive Wrong Answer.

Score
For each solved problem you’ll recieve exactly one point (10 points maximum, if all problems are
solved correctly).

Example
Output:
1 6174046
2 AnsweR
5 806257
8 51146700

It’s just the example of what the output should look like. If all 4 answers are correct (problems 1, 2, 5
and 8), you will recieve 4 points.

Added by: Roman Sol


Date: 2006-04-11
Time limit: 1s
Source limit:10000B
Languages: TEXT
Resource: ZCon 2007

3
SPOJ Problem Set (classical)

1417. University Employees


Problem code: EMP
On some island each inhabitant is either a knight who only tells the truth, or a liar who always lies.
Also, on the island there exists a university of technology where some of the inhabitants work. All of
the university employees will always tell you the following two things, no matter which employee you
ask:

1. There are fewer than N employees who work more than me.

2. At least M employees of the university have a larger salary than me.

It is also known that no two employees of the university have an identical salary, and no two work
equally. Write a program which will compute how many persons are employed by this university.

Input
The only input line contains two integers N and M, with one space between them [N, M <=
1000000000].

Output
The output must contain only one integer - the total number of employees of this university, or 0 if
there is no way to find the number of employees.

Example
Input:
1 1

Output:
2

Author: Filimonenkov D.O.

Added by: Roman Sol


Date: 2006-04-24
Time limit: 1s
Source limit:50000B
Languages: All
Resource: ZCon 2007

1
SPOJ Problem Set (tutorial)

1428. Easy sudoku


Problem code: EASUDOKU
You are to solve the classic 9x9 sudoku problem.

Input
The first line contains only one number - number of test cases (more than 1 and less then 15). Than the
test cases are given. Each of them is given by 81 numbers (from 0 to 9) seperated by single white
space (new line after each 9th number). Zero means that it is to solve by your program.

Output
In case of there does not exist the solution write "No solution". If there exist 81 number beeing the
solution of sudoku problem, you have to write all those 81 numbers (separated like in input).

Example
Input:
2
0 0 0 0 6 9 8 3 0
9 8 0 0 0 0 0 7 6
6 0 0 0 3 8 0 5 1
2 0 5 0 8 1 0 9 0
0 6 0 0 0 0 0 8 0
0 9 0 3 7 0 6 0 2
3 4 0 8 5 0 0 0 9
7 2 0 0 0 0 0 6 8
0 5 6 9 2 0 0 0 0

0 0 0 0 6 9 8 3 0
9 8 0 0 0 0 0 7 6
6 0 0 0 3 8 0 5 1
2 0 5 4 8 1 0 9 0
0 6 0 0 0 0 0 8 0
0 9 0 3 7 0 6 0 2
3 4 0 8 5 0 0 0 9
7 2 0 0 0 0 0 6 8
0 5 6 9 2 0 0 0 0

Output:
5 1 2 7 6 9 8 3 4
9 8 3 5 1 4 2 7 6
6 7 4 2 3 8 9 5 1
2 3 5 6 8 1 4 9 7
1 6 7 4 9 2 3 8 5
4 9 8 3 7 5 6 1 2
3 4 1 8 5 6 7 2 9
7 2 9 1 4 3 5 6 8
8 5 6 9 2 7 1 4 3
No solution

1
Added by: Rafał Nowak
Date: 2007-03-23
Time limit: 1s
Source limit:5000B
Languages: All

2
SPOJ Problem Set (tutorial)

1474. Charge
Problem code: TREE3
Network is becoming more and more important in the modern times. There are hundreds million of
people studying,researching and playing with the Internet. However, we can’t forget that there will be
a lot of cost when the network is running. So charging from the users is necessary and of course
reasonable.

The very very famous Southern Moutain high School in the City of Soft Sheep has such a network of
education. There are 2^N users in total, which are numbered 1,2,3...2^N . These users are connected
by routers and cables.

Users,routers,cables make a Full Binary Tree together. Each leaf(colored white) of the tree denotes a
user,each non-leaf node(colored gray) denotes a router,each edge denote a cable,see the following
picture.

[IMAGE]

The charge mode of the network company in the city of Soft Sheep is quite strange, so called "Pairing
Charging". It means that they charge from each two users i and j (1 <= i < j <= 2^N ). Users can
choose one mode of charge among A and B by themselves,so the cost that the company charge from
the great school is relative to the mode of charging by each user. The total cost equals to the sum of the
cost of each pair of users.

Some definations:

Ancestor:The root of the tree has no Ancestor,each ancestor of some other node Ancestors are
father of this node and the father’s Ancestor.
dominated Leaf:The leaves dominate nothing,the leaves dominated by one non-leaf node are all
the leaves dominated by the left and right child of this node.
Dist:The shortest path between each pair of nodes in the tree.

For each pair of users i,j(1 <= i < j <= 2^N),first we find the LCA(Least Common Ancestor) of the two
node named P,then let’s consider the Donimated Leaves of P(the users assign to P). We define nA,nB
denoted the number of users choose A and B to charge in these Donimated Leaves.

Charging is following the rule below:(in the rule,F(i,j) denotes the flux between i and j and will be
given.)

[IMAGE]

Since the total cost is relative to the mode of charging,the users in the great Southern Moutain School
hope to minimize the cost by changing the way of charging.However,the company has recorded the
mode that each user choosed when they registered.So for each user i,if he/she wants to change the
mode of charging,(change from mpde A to mode B,or change from mode B to mode A),he/she must
pay $Ci to the company to modify the record.

1
Your task is:

Given the mode the users chosen when they registered,and Ci,decide the mode to charge of each user
to minimize the total cost(the cost of changing mode + the sum of the cost of the Pairing Charging).

Input
T [The number of test cases]
N [N<=10]
D1 D1 D2 ... DM [M=2^N, Di=0 iff the mode user i chosen when he/she registerd is A and Di=1 otherwise.]
C1 C1 C2 ... CM [the cost of changing the mode of each user,0<=Ci<=500000]
F(1,2) F(1,3) ... F(1,M)
F(2,3) F(2,4) ... F(2,M)
...
F(M-2,M-1) F(M-2,M)
F(M-1,M)
[The table above is the flux table description,0<=F(i,j)<=500]
[other tests]

Output
TheMinCost
[other tests]

Example
Sample Input:
1
2
1 0 1 0
2 2 10 9
10 1 2
2 1
3

Sample Output:
8

Hints:

Change the mode of the first user from mode B to mode A.

Added by: Blue Mary


Date: 2007-04-01
Time limit: 17s
Source limit:50000B
Languages: All except: C99 strict
Resource: Chinese National Olympiad in Informatics 2006,Day 1(co-author lcosvse)

2
SPOJ Problem Set (main)

1488. Balloons of JiaJia


Problem code: PT07K
In WinD’s birthday, JiaJia opens a small contest for all guests: just typing all characters from ’a’ to ’z’,
who fastest is the winner. The award is a very big bunch of balloons. Of course, JiaJia hopes his
girlfriend - WinD can win, since he only carries two bunches with him and the award for this contest
looks prettier. Unfortunately, life is not always as he expected, the winner is Amber. So JiaJia can only
give WinD his second bunch of balloons. After the party ended, WinD said "I prefer that bunch of
balloons to this one!! If you can’t give me something the same as it, I don’t want to see you
anymore!". Well, JiaJia really has a brainstorm.

If we consider balloons as nodes, the colorful strings connect them as edges, and color of each balloon
is label of each node then we have each bunch of balloons is a rooted, labeled, ordered tree.

We call T a labeled tree if each node is assigned a symbol from a fixed finite alphabet. And T is an
ordered tree if a left-to-right order among siblings in T is given.

JiaJia can do these 3 operators to change the shape of a bunch of balloons (T):

Relabel (recolor a balloon) Change the label of a node v in T.


Delete (remove a balloon) Delete a non-root node v in T with parent p, making the children of v
become the children of p. The children are inserted in the place of v as a subsequence in the
left-to-right order of the children of p.
Insert (add a balloon) The complement of Delete. Insert a node v with any label as a child of
node p in T, making v be the parent of a consecutive subsequence of the children of p.

[IMAGE] [IMAGE]

Please help the poor guy JiaJia, use as few number of operators to make WinD’s bunch of balloons
exactly the same as Amber’s bunch of balloons. His girlfriend can’t wait any longer. Note that, he can
only make changes with WinD’s bunch.

Input
The input file contains two bunches of balloons (or trees). The first is of WinD, the second is of
Amber.

The first line of the input file contains one integer N - number of balloons in the bunch T1 (1 <= N <=
500). Balloons are numbered from 1 to N.

In next N lines, the i-th line contains the ordered children list of the i-th balloon. The first integer l[i] of
the i-th line is the color id of the i-th balloon (0 <= l[i] <= 10 4 ). The second integer c[i] of the i-th line
c[i] is the number of the children of the i-th balloon. Then c[i] integers followed, which means the
ordered children list of the i-th balloon.

1
The remaining part of the input file is the description of the second bunch of balloons T2. The format
is the same as T1.

Output
Output minimum number of operators JiaJia needs to do.

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

Output:
2

Explanation
We cut the string connected between 1st balloon and
3rd balloons, then change the color of 2nd balloon to 3.

Added by: Thanh-Vy Hua


Date: 2007-04-07
Time limit: 0.100s-2.5s
Source limit:50000B
Languages: All
Resource: Co-author Amber

2
SPOJ Problem Set (tutorial)

1679. Annoying painting tool


Problem code: ANNOYING
Maybe you wonder what an annoying painting tool is? First of all, the painting tool we speak of
supports only black and white. Therefore, a picture consists of a rectangular area of pixels, which are
either black or white. Second, there is only one operation how to change the colour of pixels:

Select a rectangular area of r rows and c columns of pixels, which is completely inside the picture. As
a result of the operation, each pixel inside the selected rectangle changes its colour (from black to
white, or from white to black).

Initially, all pixels are white. To create a picture, the operation described above can be applied several
times. Can you paint a certain picture which you have in mind?

Input Specification
The input contains several test cases. Each test case starts with one line containing four integers n, m,
r and c. (1 <= r <= n <= 100, 1 <= c <= m <= 100), The following n lines each describe one row of
pixels of the painting you want to create. The i th line consists of m characters describing the desired
pixel values of the i th row in the finished painting (’0’ indicates white, ’1’ indicates black).

The last test case is followed by a line containing four zeros.

Output Specification
For each test case, print the minimum number of operations needed to create the painting, or -1 if it is
impossible.

Sample Input
3 3 1 1
010
101
010
4 3 2 1
011
110
011
110
3 4 2 2
0110
0111
0000
0 0 0 0

1
Sample Output
4
6
-1

Added by: Adrian Kuegel


Date: 2007-07-06
Time limit: 10s
Source limit:50000B
Languages: All
Resource: University of Ulm Local Contest 2007

2
SPOJ Problem Set (tutorial)

1680. Black and white painting


Problem code: BLACK
You are visiting the Centre Pompidou which contains a lot of modern paintings. In particular you
notice one painting which consists solely of black and white squares, arranged in rows and columns
like in a chess board (no two adjacent squares have the same colour). By the way, the artist did not use
the tool of problem A to create the painting.

Since you are bored, you wonder how many 8 × 8 chess boards are embedded within this painting.
The bottom right corner of a chess board must always be white.

Input Specification
The input contains several test cases. Each test case consists of one line with three integers n, m and c.
(8 <= n, m <= 40000), where n is the number of rows of the painting, and m is the number of
columns of the painting. c is always 0 or 1, where 0 indicates that the bottom right corner of the
painting is black, and 1 indicates that this corner is white.

The last test case is followed by a line containing three zeros.

Output Specification
For each test case, print the number of chess boards embedded within the given painting.

Sample Input
8 8 0
8 8 1
9 9 1
40000 39999 0
0 0 0

Sample Output
0
1
2
799700028

Added by: Adrian Kuegel


Date: 2007-07-06
Time limit: 10s
Source limit:50000B
Languages: All
Resource: University of Ulm Local Contest 2007

1
SPOJ Problem Set (tutorial)

1682. Deli Deli


Problem code: DELI
Mrs. Deli is running the delicatessen store "Deli Deli". Last year Mrs. Deli has decided to expand her
business and build up an online store. She has hired a programmer who has implemented the online
store.

Recently some of her new online customers complained about the electronic bills. The programmer
had forgotten to use the plural form in case that an item is purchased multiple times. Unfortunaly the
programmer of Mrs. Deli is on holiday and now it is your task to implement this feature for Mrs. Deli.
Here is a description how to make the plural form:

1. If the word is in the list of irregular words replace it with the given plural.
2. Else if the word ends in a consonant followed by "y", replace "y" with "ies".
3. Else if the word ends in "o", "s", "ch", "sh" or "x", append "es" to the word.
4. Else append "s" to the word.

Input Specification
The first line of the input consists of two integers L and N (0 <= L <= 20, 1 <= N <= 100). The
following L lines contain the description of the irregular words and their plural form. Each line
consists of two words separated by a space character, where the first word is the singular, the second
word the plural form of some irregular word. After the list of irregular words, the following N lines
contain one word each, which you have to make plural. You may assume that each word consists of at
most 20 lowercase letters from the english alphabet (’a’ to ’z’).

Output Specification
Print N lines of output, where the i th line is the plural form of the i th input word.

Sample Input
3 7
rice rice
spaghetti spaghetti
octopus octopi
rice
lobster
spaghetti
strawberry
octopus
peach
turkey

1
Sample Output
rice
lobsters
spaghetti
strawberries
octopi
peaches
turkeys

Added by: Adrian Kuegel


Date: 2007-07-06
Time limit: 1s
Source limit:50000B
Languages: All
Resource: University of Ulm Local Contest 2007

2
SPOJ Problem Set (tutorial)

1756. Find The Determinant


Problem code: DETER
In this problem you have to calculate the determinant of an N x N matrix whose entries are given by
m[i][j] = gcd(i,j), 1 <= i,j <= N.
Here gcd(i,j) denotes the greatest common divisor of i and j.
As the determinant D can grow very large, you have to print D%1000003.

Input
First line of input consists of a single integer containing the number of test cases T ( equal to around
500000), each of the following T lines contain an integer N the size of the matrix. N lies between 1
and 2000000 ( both inclusive ).

Output
One line corresponding to each test case containing the determinant modulo 1000003 for the
corresponding test case.

Example
Input:
3
1
3
5

Output:
1
2
16

Added by: Ajay Somani


Date: 2007-09-01
Time limit: 6s
Source limit:2048B
Languages: All
Resource: "The Art Of Computer Programming"

1
SPOJ Problem Set (tutorial)

1872. Making Book


Problem code: MKBOOK
A printer - who still uses moveable type - is preparing to print a set of pages for a book. These pages
are to be numbered, as usual. The printer needs to know how many instances of each decimal digit will
be required to set up the page numbers in the section of the book to be printed.

For example, if pages 10, 11, 12, 13, 14 and 15 are to be printed, computing the number of digits is
relatively simple: just look at the page numbers that will appear, and count the number of times each
digit appears. The digit 0 appears only once, the digit 1 appears 7 times, the digits 2, 3, 4 and 5 each
appear once, and 6, 7, 8 and 9 don’t appear at all.

Your task in this problem is to provide the printer with the appropriate counts of the digits. You will be
given the numbers of the two pages that identify the section of the book to be printed. You may safely
assume that all pages in that section are to be numbered, that no leading zeroes will be printed, that
page numbers are positive, and that no page will have more than three digits in its page number.

Input
There will be multiple cases to consider. The input for each case has two integers, A and B, each of
which is guaranteed to be positive. These identify the pages to be printed. That is, each integer P
between A and B, including A and B, is to be printed. A single zero will follow the input for the last
case.

Output
For each input case, display the case number (1, 2, ...) and the number of occurrences of each decimal
digit 0 through 9 in the specified range of page numbers. Display your results in the format shown in
the examples below.

Example
Input:
10 15
912 912
900 999
0

Output:
Case 1: 0:1 1:7 2:1 3:1 4:1 5:1 6:0 7:0 8:0 9:0
Case 2: 0:0 1:1 2:1 3:0 4:0 5:0 6:0 7:0 8:0 9:1
Case 3: 0:20 1:20 2:20 3:20 4:20 5:20 6:20 7:20 8:20 9:120

1
Added by: Camilo Andrés Varela León
Date: 2007-10-07
Time limit: 1s
Source limit:50000B
Languages: All
Resource: North Central North America Regional Programming Contest - 2003

2
SPOJ Problem Set (tutorial)

2018. Clique Separation


Problem code: CLIQSEP
The Clique Problem

Problem
Let G be the set of di-graphs with n nodes, m edges and maximum clique (complete subgraph) size of
k nodes, determine whether it is possible to divide every element of G into two disjoint sets of nodes,
such that the largest size of a clique contained in one set is equal to the largest size of a clique
contained in the other set.

The Input
Each line of input has n <= 1000 , m <= 1000000 , k <= n , listed in that order.

The Output
For each line of input, output "yes" if it is possible, "no" if it is not possible.

Sample Input
10 99 8
9 80 3

Sample Output
yes
no

Problemsetter --- Chen, Xiaohong

Added by: Chen Xiaohong


Date: 2007-11-06
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

2020. Painting Points


Problem code: PAINTPOI
Painting Points

Problem
Two players play the following game. The first player paints a point on the plane red. The second
player paints k uncoloured points on the plane green. The first player paints an uncoloured point on the
plane red. The second player paints k uncoloured points on the plane green. And so on. The first
player wins if there are three red points which form an equilateral triangle. The second player wins if it
is not possible within a finite number of moves. Assume he plays prefectly to prevent or delay the first
player from winning. Given k, determine the minimum number of moves it takes for the first player to
force a win. If it’s not possible for the first player to win, output -1.

The Input
Each line of input has an even integer k, 0 < k <= 1000000.

The Output
For each line of input, output the answer on one line.

Sample Input
10

Sample Output
12

Problemsetter --- Wu, Xiaogang

Added by: Chen Xiaohong


Date: 2007-11-06
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

2122. Billboard
Problem code: BBOARD
The manager of the International Popcorn-Selling Company has just decided that a number of
advertising billboards should be installed throughout the city. The city consists of a number of
crossings connected by (bidirectional) streets. Crossings are numbered by integers 1..N.

There should be one billboard at every crossing. However, to cut down expenses, there have been only
three types of billboards printed. Nevertheless, the billboards should be arranged in such a way that
one never meets the same billboard twice in a row when driving through the city (suppose that it is
possible to turn back only at the crossing). How should they be installed?

Input specification
The input file starts with a line containing the number of test cases. Every test case starts with a line
containing two (blank separated) integers N(1<= N <=600), M(1<= M <=10000) where N is the
number of crossings and M is the number of streets. Each of the next M lines contains two integers x,
y, indicating a street connecting crossings x and y.

Output specification
The output file contains a sequence of N numbers delimited by whitespace for every test case. The i-th
member of this sequence denotes the type of the billboard at the crossing i (assume that the types of
the billboards are numbered 1,2,3). If it is not possible to install the billboards in the described manner,
the sequence consists of a single number -1.

Note that it is not necessary to write the entire sequence in one line. To prevent the problems with the
mailer you may split long lines into several shorter ones.

Example
Input file:
2
6 7
1 3
1 4
5 2
2 6
4 2
3 4
6 3
5 8
1 2
1 5
1 3
2 5
2 3
5 3
3 4

1
4 5

Output file:
1 2 2 3 3 1
-1

Added by: Blue Mary


Date: 2007-12-01
Time limit: 3s
Source limit:50000B
Languages: All except: C99 strict
Resource: IPSC 1999

2
SPOJ Problem Set (tutorial)

2134. Colorful Cubes


Problem code: CCUBE
Bill Games, an excellent programmer, spent Easter with his grandparents. In their old house he came
across wooden cubes - a child’s toy. When he was a child, he used to build castles and towers and
pyramids of these colorful cubes. He started to play with them again. However, the problem which he
tries to solve today is much more complicated than building a simple pyramid.

Each face of a cube is colored with one color. Bill wants to build a tower from all cubes he has. This
means to stack all the cubes in one column, one on another. Bill does not want to put the cubes in
arbitrary order - the bottom face of every cube (except the bottom cube which is lying on the floor)
should have the same color as the top face of the cube below it.

Input file specification


The first line of the input file consists of two numbers M(1<=M<=100) and N(1<=N<=500). M is the
number of colors used (colors are numbered 1...M) and N is the number of cubes (cubes are numbered
1...N in the order as they appear on the input).

Next N lines represent cubes 1,2,...,N in this order. A cube is described by six numbers giving colors
of its faces in the following order: front, back, right, left, bottom, and top face.

Output file specification


Given the cubes described in the input file determine how to arrange them into a tower. Every cube
has to be used exactly once. You need to find only one solution. Assume that the solution exists.

The output file consists of N lines. The i-th line contains the description of the cube on the i-th position
in the tower, counting from bottom. The description of a cube consists of seven numbers. The first
number is the number of the cube (the order of the cube in the input file) and the following six
numbers represent colors of the faces in the following order: front, back, right, left, bottom, and top
face. Notice that cubes can be rotated.

Example
Input file #1:
6 2
1 2 3 4 5 6
2 1 3 4 5 6

Output file #1:


1 6 5 3 4 1 2
2 6 5 3 4 2 1

Input file #2:


3 3
1 2 2 2 1 2
3 3 3 3 3 3

1
3 2 1 1 1 1

Output file #2:


1 1 2 2 2 1 2
3 1 1 1 1 2 3
2 3 3 3 3 3 3

Added by: Blue Mary


Date: 2007-12-01
Time limit: 30s
Source limit:10000B
Languages: All except: C99 strict
Resource: IPSC 2000

2
SPOJ Problem Set (tutorial)

2155. Jamcode 2006 (Easy)


Problem code: JCEASY
There is one unnamed popular programming contest for people from all around the world. (Its name
matches "SearchEngine Program Marmalade".) The contest starts with a coding phase where the
contestants write code. After the coding phase there is a challenge phase. In this phase one can gain
points when she finds a bug in someone else’s code.

We were all lame and performed very badly. In fact, none of our programs worked. Thus we decided
to hold a new contest: the Jam Code. Here, the task is to write a program that will never work
correctly.

This contest will have an anti-challenge phase, where your goal is to find at least one test case such
that a given program actually works ; in other words, it computes the correct answer.

Problem specification
You will be given a programming task and someone’s source code. Find a valid input such that the
program computes the correct answer.

Easy Task specification


The input file contains an integer M (0< M and M < 200) followed by M integers a[1], ..., a[m] in the
range 1, 2, ..., 334. Output one line with the string s a[1] s a[2] ...s a[m] . Here is the list of strings s 1 , ...,
s 334 .

Example
Input
3
1
2
3

Output
020202020202020212021202121212021202121202021212

The file jceasy.cpp contains the program you are supposed to anti-challenge.

You are to submit a file which contains a valid input.

1
Added by: Blue Mary
Date: 2007-12-01
Time limit: 1s
Source limit:50000B
Languages: TEXT
Resource: IPSC 2006

2
SPOJ Problem Set (tutorial)

2156. Jamcode 2006 (Hard)


Problem code: JCHARD
There is one unnamed popular programming contest for people from all around the world. (Its name
matches "SearchEngine Program Marmalade".) The contest starts with a coding phase where the
contestants write code. After the coding phase there is a challenge phase. In this phase one can gain
points when she finds a bug in someone else’s code.

We were all lame and performed very badly. In fact, none of our programs worked. Thus we decided
to hold a new contest: the Jam Code. Here, the task is to write a program that will never work
correctly.

This contest will have an anti-challenge phase, where your goal is to find at least one test case such
that a given program actually works ; in other words, it computes the correct answer.

Problem specification
You will be given a programming task and someone’s source code. Find a valid input such that the
program computes the correct answer.

Hard Task specification


You are organizing a big party for a lot of people. You want to invite 2N men and 2N women. At the
beginning of the party, there will be a dance. Before the party, each man sent you a list of women he is
willing to dance with. You have to maximize the number of pairs that can dance at the same time.

The first line of the input file contains an integer N (0< N and N < 100). On each of the next 2N lines
there are 2N numbers. If the i-th number on the j-th line is 0, then the j-th man doesn’t want to dance
with the i-th woman. If the number is 1, the man is willing to dance with the woman.

Output one number on one line with the maximum number of pairs which can dance at the same time.

Example
Input
1
1 1
1 1

Output
2

The file jchard.cpp contains the program you are supposed to anti-challenge.

You are to submit a file which contains a valid input.

1
Added by: Blue Mary
Date: 2007-12-01
Time limit: 1s
Source limit:50000B
Languages: TEXT
Resource: IPSC 2006

2
SPOJ Problem Set (tutorial)

2261. Program Analyser (tutorial)


Problem code: ANALYS_T

Input
A Program which has the following format:
<Program>::=<sentence><line break>{<sentence><line break>}
<setence>::=<level><space><body>
<body>::=<addition> | <output> | <goto> | <condition> | <end>
<addition>::=<variable>+<integer>
<output>::=<variable>?
<goto>::=GO<space><level>
<condition>::=IF<space><variable>=<integer><space><goto>
<end>::=END
<variable>::=<character>
<level>::=<integer>
<integer>::=<digit>{<digit>}
<character>::=A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z
<digit>::= 0|1|2|3|4|5|6|7|8|9
<line break>::=(ASCII 10)
<space>::=(ASCII 32)

The program runs following the following rules:

Program starts from the sentence whose level is minimum, and executed by the level from low to
high except that the sentence is<goto>or<condition>.
All variables are initialized to 0.
<Addition>means<variable>+=<integer>in C++.
<output>means write the value of<variable>to the output file(we aren’t interesting about the real
output file.)
<condition>means if and only if the value of the <variable> equals to <integer>, <goto> will be
executed, otherwise the next sentence executed is as usual.
After<goto>, the next sentence executed is the sentence with level which equals to the level
in<goto>.
Program terminates by itself when <end> is executed.
This program can deal with all the signed 32-bit integers.
The number of sentences in the program is not more than 100.
The length of each line in the input file is not more than 20.
The input is correct.
The sentence with the maximum level is always <end>.
The levels is not more than 3000.

Input terminate by EOF.

1
Output
Output the number of sentences executed.If the program can not terminate by itself,output -1.

Example
Input:
10 A+1
20 IF A=5 GO 60
60 END
30 A+2
40 A?
50 GO 20

Output:
11

Hint:
10->20->30->40->50->20->30->40->50->20->60

Added by: Blue Mary


Date: 2008-01-02
Time limit: 60s
Source limit:50000B
Languages: All except: C99 strict
Resource: a copy of ANALYSER problem with 60s time limit

2
SPOJ Problem Set (tutorial)

2278. Merrily, We Roll Along!


Problem code: WHEEL
One method used to measure the length of a path is to roll a wheel (similar to a bicycle wheel) along
the path. If we know the radius of the wheel and the number of revolutions it makes as it travels along
the path, the length of the path can be computed.

This method works well if the path is smooth. But when there are curbs or other abrupt elevation
changes in the path, the path distance may not be accurately determined, because the wheel may rotate
around a point (like the edge of a curb), or the wheel may roll along a vertical surface. In this problem
you are to determine the distance moved by the center of such a wheel as it travels along a path that
includes only horizontal and vertical surfaces.

To measure a path, the wheel is placed with its center directly above the origin of the path. The wheel
is then moved forward over the path as far as possible, always remaining in contact with the surface,
ending with its center directly above the end of the path.

Consider the path shown in the illustration on the left below, and assume the wheel has a radius of 2.
The path begins and ends with horizontal segments of length 2 at the same elevation. Between these
there is a horizontal segment of length 2.828427 at 2 units below the elevation of the other two
horizontal segments. To measure this path, the wheel is placed at position 1. It then moves horizontally
to position 2, rotates 45 degrees to position 3, rotates another 45 degrees to position 4, and finally rolls
horizontally to position 5. The center of the wheel moved a distance of 7.1416, not 6.8284.

In the illustration on the right below, the path begins and ends with horizontal segments of length 3,
separated by a 7-unit wide region placed 7 units below the surface. If the wheel has a radius of 1, then
it will move 26.142 units before reaching the end of the path.

[IMAGE]

Input
For this problem there are multiple input cases. Each case begins with a positive real number
specifying the radius of the wheel and an integer n, which is at least 1 but not greater than 50. There
then follow n pairs of real numbers. The first number in each pair gives the horizontal distance along
the path to the next vertical surface. The second number in each pair gives the signed change in the
elevation of the path at the vertical surface, with positive numbers representing an increase in
elevation. The vertical surfaces are always perpendicular to the horizontal surfaces. The elevation
change in the nth pair will always be 0.

The input is terminated by a pair of zeroes.

1
Output
For each case, display the case number and the distance moved by the center of the wheel with 3 digits
to the right of the decimal point.

Place a blank line after the output of each test case.

Example
Input:
2.0 3
2.0 -2.0
2.828427 2.0
2.0 0.0
1.0 3
3.0 -7.0
7.0 7.0
3.0 0.0
1.0 3
1.0 -4.0
2.0 4.0
1.0 0.0
0 0

Output:
Case 1: Distance = 7.142

Case 2: Distance = 26.142

Case 3: Distance = 5.142

Added by: Blue Mary


Date: 2008-01-03
Time limit: 1s
Source limit:50000B
Languages: All except: C99 strict
Resource: ACM/ICPC World Final 2002 (unofficial testdata)

2
SPOJ Problem Set (classical)

2523. Mispelling
Problem code: GNY07A
Misspelling is an art form that students seem to excel at. Write a program that removes the nth
character from an input string.

Input
The first line of input contains a single integer N, (1 <= N <= 1000) which is the number of datasets
that follow.

Each dataset consists of a single line of input containing M, a space, and a single word made up of
uppercase letters only. M will be less than or equal to the length of the word. The length of the word is
guaranteed to be less than or equal to 80.

Output
For each dataset, you should generate one line of output with the following values: The dataset number
as a decimal integer (start counting at one), a space, and the misspelled word. The misspelled word is
the input word with the indicated character deleted.

Example
Input:
4
4 MISSPELL
1 PROGRAMMING
7 CONTEST
3 BALLOON

Output:
1 MISPELL
2 ROGRAMMING
3 CONTES
4 BALOON

Added by: Marco Gallotta


Date: 2008-03-11
Time limit: 60s
Source limit:50000B
Languages: All
Resource: ACM Greater New York Regionals 2007

1
SPOJ Problem Set (classical)

2524. Conversions
Problem code: GNY07B
Conversion between the metric and English measurement systems is relatively simple. Often, it
involves either multiplying or dividing by a constant. You must write a program that converts between
the following units:

Type Metric English equivalent


Weight 1.000 kilograms 2.2046 pounds
0.4536 kilograms 1.0000 pound
Volume 1.0000 liter 0.2642 gallons
3.7854 liters 1.0000 gallon

Input
The first line of input contains a single integer N, (1 <= N <= 1000) which is the number of datasets
that follow.

Each dataset consists of a single line of input containing a floating point (double precision) number, a
space and the unit specification for the measurement to be converted. The unit specification is one of
kg, lb, l, or g referring to kilograms, pounds, liters and gallons respectively.

Output
For each dataset, you should generate one line of output with the following values: The dataset number
as a decimal integer (start counting at one), a space, and the appropriately converted value rounded to
4 decimal places, a space and the unit specification for the converted value.

Example
Input:
5
1 kg
2 l
7 lb
3.5 g
0 l

Output:
1 2.2046 lb
2 0.5284 g
3 3.1752 kg
4 13.2489 l
5 0.0000 g

1
Added by: Marco Gallotta
Date: 2008-03-11
Time limit: 60s
Source limit:50000B
Languages: All
Resource: ACM Greater New York Regionals 2007

2
SPOJ Problem Set (tutorial)

2533. Point Nesting


Problem code: POINTS
A point in 3D A(ax,ay,az) is said to nest another point B(bx,by,bz), iff bx <= ax AND by <= ay AND
bz <= az. Given a set of 3D points, find a nesting sequence using maximal number of points. A
sequence P0, P1, P2, ... is said to be a valid nesting sequence iff, P1 nests P0, P2 nests P1 and so on.
Please note there could be duplicate points, and each input point must be used atmost once while
creating the sequence.

Input
First line contains the number of testcases T.
Each testcase starts with n - The number of points. (0 < n <= 100,000)
The next n lines give the input points.

Output
For each testcase print one integer saying the length of the longest nesting sequence.

Example
Input:
2
4
930887 692778 636916
747794 238336 885387
760493 516650 641422
202363 490028 368691
10
897764 513927 180541
383427 89173 455737
5212 595369 702568
956430 465783 21531
722863 665124 174068
703136 513930 979803
634023 723059 133070
898168 961394 18457
175012 478043 176230
377374 484422 544920

Output:
2
3

1
Added by: Prasanna
Date: 2008-03-12
Time limit: 3s
Source limit:50000B
Languages: All
Resource: CMI Local Contest

2
SPOJ Problem Set (tutorial)

2625. Problems Collection (Volume 3)


Problem code: PCV3
Problem 1 Using a combination of black square tiles and oblong tiles chosen from: red tiles of two
units length, green tiles of three units length, and blue tiles of four units length, it is possible to tile a
row of five units length in exactly fifteen different ways:

[IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE]

[IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE]

[IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE]

[IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE]

In how many ways can a row measuring fifty units in length be tiled?
Problem 2 A hexagonal tile with number 1 is surrounded by a ring of six hexagonal tiles, starting at
"12 o’clock" and numbering the tiles 2 to 7 in an anti-clockwise direction. New rings are added in the
same fashion, with the next rings being numbered 8 to 19, 20 to 37, 38 to 61, and so on. The diagram
below shows the first three rings:

[IMAGE]

By finding the difference between tile n and each of its six neighbours we shall define PD(n) to be the
number of those differences which are prime. For example, working clockwise around tile 8 the
differences are 12, 29, 11, 6, 1, and 13. So PD(8) = 3. In the same way, the differences around tile 17
are 1, 17, 16, 1, 11, and 10, hence PD(17) = 2. It can be shown that the maximum value of PD(n) is 3.
If all of the tiles for which PD(n) = 3 are listed in ascending order to form a sequence, the 10th tile
would be 271. Find the 2000th tile in this sequence.
Problem 3 Let S(A) represent the sum of elements in set A of size n. We shall call it a special sum set
if for any two non-empty disjoint subsets, B and C, the following properties are true:
1) S(B) != S(C); that is, sums of subsets cannot be equal.
2) If B contains more elements than C then S(B) > S(C).
For this problem we shall assume that a given set contains n strictly increasing elements and it already
satisfies the second rule.
Surprisingly, out of the 25 possible subset pairs that can be obtained from a set for which n = 4, only 1
of these pairs needs to be tested for equality (first rule). Similarly, when n = 7, only 70 out of the 966
subset pairs need to be tested. For n = 12, how many of the 261625 subset pairs that can be obtained
need to be tested for equality?
Problem 4 Find the smallest integer N > 15, for which N^3 can be written using prime digits only
{i.e., 2, 3, 5, 7}.
Problem 5 Let’s call an integer a "titanic number" if we need 1000 or more digits to write it in
decimal format. In this task you must find the minimal titanic number, which can be presented in p^q
form, where p and q are prime numbers. You must output the answer in the following form: X-q,
where X - the last 10 digits of the titanic number and q - the power of the exponent. For example:
8765839202-97
Problem 6 Find the smallest positive integer for which every number in the series (N-k)/k is a prime

1
number for every k=1,...n, for n = 11. For n=4 the answer would be N=12, let’s check: (12-1)/1 = 11,
(12-2)/2 = 5, (12-3)/3 = 3, (12-4)/4 = 2.
Problem 7 You are playing the following game. You can ask the host of the game to tell you a
number. Each number is an independent random uniformly distributed real number between 0 and 1.
After the host tells you the number you can ask for more or just stop. When you stop, your score is
equal to the sum of all numbers which the host has given to you. Let 0 < x < 1 and suppose that you’re
trying to get a score in the interval from x to 1. What is the probability of winning, assuming that you
are using the best possible strategy? Find the value of probability of winning for x=0.334568 and
output it after rounding in the form of *.****** - where each * denotes a digit.
Problem 8 Find the number of integers 1 < n < 10^7, for which n and n + 1 have the same number of
positive divisors. For example, 14 has the positive divisors 1, 2, 7, 14 while 15 has 1, 3, 5, 15.
Problem 9 Decode the message in the picture:

[IMAGE]

Output it with lowercase letters without spaces.


Problem 10 Suppose that you find a small program which is protected by an "activation key". The
value of the key depends on the name you input. The protection for this program is performed using
the code in the C programming language, presented below. The program asks you for your name and
password and outputs "Accept" or "Failure".
#include <stdio.h>

unsigned int code (unsigned int arg, int p, int n)


{
unsigned int r = 1;
for(; p >= 1; p--)
r = (r*arg)%n;
return r;
}

void main ()
{
unsigned int e = 35467, n = 54031, pwd;
char name[256];
unsigned int hash, x;

printf("Name: ");
scanf("%s", name);

printf("Password: ");
scanf("%d", &pwd);

hash = 0;
for (x = 0; ; x++){
if (name[x] == 0)
break;
hash += name[x];
}

if (code(pwd, e, n) == hash)
printf("Accept!\n");
else
printf("Failure\n");
}

2
Your goal is to find the right passwords for each name presented in file: nicks.zip (~330 Kb). The
answer for this problem will be the sum of all passwords obtained for each name from file.

Input
There is no input for this problem.

Output
Output answer as a set of lines. In each line first output the number of the problem and then the answer
for this problem. If any of the answers are incorrect, you’ll receive Wrong Answer.

Score
For each solved problem you’ll recieve exactly one point (10 points maximum, if all problems are
solved correctly).

Example
Output:
1 6174046
2 AnsweR
5 806257
8 51146700

It’s just an example of what the output should look like. If all 4 answers are correct (for problems 1, 2,
5 and 8), you’ll receive 4 points.

Added by: Roman Sol


Date: 2007-07-23
Time limit: 1s
Source limit:10000B
Languages: TEXT
Resource: ZCon 2008

3
SPOJ Problem Set (tutorial)

2626. RegExp Master


Problem code: REX
You are given a set of 10 tasks. For each of these tasks you must write the correct Regular Expression
of minimal size in C format (current SPOJ version). Each regular expression will be tested against a
special test set, which contains right and wrong strings. The expression which is composed by you
must correctly work on all test cases.
Task 1 You are to write regular expression which determines if a given string is equal to
"abcdefghijklmnopqrstuv18340" or not.
Example of correct strings:
abcdefghijklmnopqrstuv18340
Example of wrong strings:
abcdefghijklmnoasdfasdpqrstuv18340
Task 2 You are to write a regular expression which determines whether a given string is a GUID, with
or without brackets. Here GUID is a string, consisting of 8, 4, 4, 4, 12 hex digits separated by ’-’.
Examples of correct strings:
{e02fa0e4-01ad-090A-c130-0d05a0008ba0}
e02fd0e4-00fd-090A-ca30-0d00a0038ba0
Examples of wrong strings:
02fa0e4-01ad-090A-c130-0d05a0008ba0}
e02fd0e400fd090Aca300d00a0038ba0
Task 3 You are to write a regular expression which determines whether the given string is a valid
MAC-address.
Examples of correct strings:
01:32:54:67:89:AB
aE:dC:cA:56:76:54
Examples of wrong strings:
01:33:47:65:89:ab:cd
01:23:45:67:89:Az
Task 4 You are to write a regular expression which determines whether a given string is uppercase
and sorted in non-descending order.
Examples of correct strings:
AABCD
ABCDZ
Examples of wrong strings:
aABCD
ZABCD
Task 5 You are to write a regular expression which determines whether a given string is the hex
identification of a color in HTML. Here #FFFFFF stands for white, #000000 for black, #FF0000 for
red, etc.
Examples of correct strings:
#FFFFFF
#FF3421
#00ff00
Examples of incorrect strings:
232323
f#fddee
#fd2
Task 6 You are to write a regular expression which determines whether the given string is a date in

1
dd/mm/yyyy format. The date is in the range from the year 1600 to the year 9999.
Examples of correct strings:
29/02/2000
30/04/2003
01/01/2003
Examples of wrong strings:
29/02/2001
30-04-2003
1/1/1899
Task 7 You are to write a regular expression which determines whether the given string is a valid
e-mail address with respect to RFC number 2822
Examples of correct strings:
mail@mail.ru
valid@megapochta.com
aa@aa.info
Examples of wrong strings:
bug@@@com.ru
@val.ru
Just Text2
val@val
val@val.a.a.a.a
12323123@111[]][]
Task 8 You are to write a regular expression which determines whether the given string is an IP
address, in decimal format
Examples of correct strings:
127.0.0.1
255.255.255.0
192.168.0.1
Examples of wrong strings:
1300.6.7.8
abc.def.gha.bcd
254.hzf.bar.10
Task 9 You are to check whether a given password is strong. A password is said to be strong if it
consists of 8 and more symbols, where a symbol is one from the set: English letter, digit or underline.
Additionally, a strong password must contain at least one uppercase letter, at least one lowercase letter
and at least one digit.
Examples of correct strings:
C00l_Pass
SupperPas1
Examples of wrong strings:
Cool_pass
C00l
Task 10 You are to write a regular expression which determines whether a given string is a six-digit
positive integer, printed in decimal format without leading zeros.
Examples of correct strings:
123456
234567
Examples of wrong strings:
1234567
12345
For testing we use the following C-function:
int match(const char *string, char *pattern)
{
int status;
regex_t re;

2
if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) {
return(0);
}
status = regexec(&re, string, (size_t) 0, NULL, 0);
regfree(&re);
if (status != 0) {
return (0);
}
return (1);
}

Input
There is no input data for this problem

Output
Output your answer as a set of 10 lines. The first line is for the first task, the second line for the second
task, etc. All other lines will be ignored. If you don’t want to solve some task, then in the
corresponding line output "---". Otherwise, output the regular expression for this task. If any of your
regular expressions are invalid you’ll get Wrong Answer status.

Score
For each solved task you’ll get exactly 1 point plus a bonus points equal to 1/(regular expression size).

Example
Output:
---
^[1-9]{1}[0-9]{3} ?[A-Z]{2}$
---
---
---
---
---
---
---
---

It’s just an example of what output data should look like. If the answer for second task were right, then
you would get 1 + 1/28 = 1.035714 points.

Added by: Roman Sol


Date: 2007-07-31
Time limit: 10s
Source limit:10000B
Languages: TEXT
Resource: ZCon 2008

3
SPOJ Problem Set (main)

2627. The Longest Chain


Problem code: BCH
Output the longest chain of integers which has the following properties:

1. All integers are positive and have 4 digits in their decimal representation (i.e. all numbers are in
the range [1000, 9999])
2. All numbers in the chain are different
3. The decimal representations of each number differs from the next one at only position (digit)
4. All integers are prime

The winner is the participant who obtains the longest chain.

Input
There is no input data in this problem.

Output
In the first line output the length of your chain N. In the next N lines output each number of your
chain.

Score
The number of points you’ll get for the given problem is calculated using following formula: score =
1000/(1062 - length), where length - length of your chain.

Example
Output:
3
9857
9887
9883

Score:
In this case score = 1000/(1062-3) = 0.944287,

Problem author: Filimonenkov D.O.

1
Added by: Roman Sol
Date: 2007-09-03
Time limit: 1s-30s
Source limit:50000B
Languages: All
Resource: ZCon 2008

2
SPOJ Problem Set (tutorial)

2630. Autoarchive
Problem code: ARJ
Write a program of minimal possible size which outputs the given file: ZARJ.txt (101350 bytes)
Note: it’s much better to submit source file, not text, when submit your solution.

Input
There is no input data for this problem

Output
Output your answer in the same format as the given file. If the output is different from the given file
then you get status Wrong Answer.

Score
The total number of points obtained for your solution will be equal to its source code size in bytes.

The solution to this problem isn’t allowed in some programming languages because these
languages support compression functions.

Added by: Roman Sol


Date: 2008-02-27
Time limit: 20s
Source limit:100000B
Languages: C C99 strict C++ PAS gpc PAS fpc JAVA C# ASM
Resource: Inspired by MAGIC2 (ZCon 2008)

1
SPOJ Problem Set (main)

2632. Max Power


Problem code: MXP
You are given two sequences of positive integers a1, a2, ..., an and b1, b2, ..., bn of length n each. You
are to write a program which finds k such that ak to the power of bk is maximal.

Input
The first line of input contains a positive integer n, not greater than 10000. In the second line you are
given a set of positive integers ai separated by spaces, and in the third line - integers bi. All numbers in
both sequences are not greater than 10000. It is guaranteed that all power values are different.

Output
The output must contain one number - the answer to the problem.

Score
The score to this problem is equal to (1000 - t), where t is the time used by your solution, in
milliseconds. If your solution works for more than 1 second then you get 0 points.

Example
Input:
5
1 2 2 3 3
100 1 3 2 1

Output:
4

Added by: Roman Sol


Date: 2008-03-13
Time limit: 10s-25s
Source limit:50000B
Languages: All
Resource: ZCon 2008

1
SPOJ Problem Set (tutorial)

2854. El Dorado
Problem code: ELDORADO
Bruce Force has gone to Las Vegas, the El Dorado for gamblers. He is interested especially in one
betting game, where a machine forms a sequence of n numbers by drawing random numbers. Each
player should estimate beforehand, how many increasing subsequences of length k will exist in the
sequence of numbers.

A subsequence of a sequence a 1 , ..., a n is defined as a i 1 , ..., a i l , where 1 <= i 1 < i 2 < ... < i l <= n.
The subsequence is increasing, if a i j-1 < a i j for all 1 < j <= l.

Bruce doesn’t trust the Casino to count the number of increasing subsequences of length k correctly.
He has asked you if you can solve this problem for him.

Input
The input contains several test cases. The first line of each test case contains two numbers n and k (1
<= k <= n <= 100), where n is the length of the sequence drawn by the machine, and k is the desired
length of the increasing subsequences. The following line contains n pairwise distinct integers a i
(-10000 <= a i <= 10000 ), where a i is the i th number in the sequence drawn by the machine.

The last test case is followed by a line containing two zeros.

Output
For each test case, print one line with the number of increasing subsequences of length k that the input
sequence contains. You may assume that the inputs are chosen in such a way that this number fits into
a 64 bit signed integer (in C/C++, you may use the data type "long long", in Java the data type "long").

Example
Input:
10 5
1 2 3 4 5 6 7 8 9 10
3 2
3 2 1
0 0
Output:
252
0

1
Added by: Adrian Kuegel
Date: 2008-07-12
Time limit: 5s
Source limit:50000B
Languages: All
Resource: University of Ulm Local Contest 2008

2
SPOJ Problem Set (tutorial)

2907. Super Factor Sum


Problem code: FACTSUM
Given a positive integer K > 2, with prime
factorization:

K = p1^a1 * p2^a2 ... * pn^an

Compute the following:

S = a1*p1 + a2*p2 ... + an*pn.

Input
A list of <100 integers, one on each line, all less than 2*10^19.

Output
For each integer compute the super factor sum and output it on a single line.

Example
Input:
6
7
Output:
5
7

Added by: Chen Xiaohong


Date: 2008-08-05
Time limit: 30s
Source limit:50000B
Languages: All
Resource: original

1
SPOJ Problem Set (tutorial)

2912. Super Primes


Problem code: SPRIME
In mathematics, a prime number (or a prime) is a natural number which has exactly two distinct
natural number divisors: 1 and itself.

Super-prime numbers are the elements of the subsequence of prime-numbers that occupy
prime-numbered positions within the sequence of all prime numbers. That is, if p(i) denotes the ith
prime number, the numbers in this sequence are those of the form p(p(i)) or Primes with a prime index
in the sequence of prime numbers (the 2nd, 3rd, 5th, ... prime).

Your task is to generate all super primes ≤ 10^7.

Input:
There is NO input for this problem.

Output:
Print all super-primes ≤ 10^7 in ascending order,one per line.

First few lines of Output


3
5
11
17
31
41
59
67
83
109
...

Added by: u.swarnaprakash


Date: 2008-08-05
Time limit: 8s
Source limit:10000B
Languages: All
Resource: Myself

1
SPOJ Problem Set (tutorial)

3032. Adding two numbers


Problem code: ADUN
Your task is to read two numbers a and b (0 < a, b <2100000000) and to output their sum.

Input
Input contains two lines, on the first line the number a and on the second line the number b.

Output
Output the sum of the two numbers.

Example
Input:
20
30

Output:
50

Added by: Pripoae Toni


Date: 2008-09-14
Time limit: 1s
Source limit:1024B
Languages: All
Resource: Original

1
SPOJ Problem Set (tutorial)

3081. Look and Say


Problem code: LOOKSAY
The look and say sequence is defined as follows. Start with any string of digits as the first element in
the sequence. Each subsequent element is defined from the previous one by "verbally" describing the
previous element. For example, the string 122344111 can be described as "one 1, two 2’s, one 3, two
4’s, three 1’s". Therefore, the element that comes after 122344111 in the sequence is 1122132431.
Similarly, the string 101 comes after 1111111111. Notice that it is generally not possible to uniquely
identify the previous element of a particular element. For example, a string of 112213243 1’s also
yields 1122132431 as the next element.

Input
The input consists of a number of cases. The first line gives the number of cases to follow. Each case
consists of a line of up to 1000 digits.

Output
For each test case, print the string that follows the given string.

Example
Input:
3
122344111
1111111111
12345

Output:
1122132431
101
1112131415

Added by: Nikola P Borisov


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

1
SPOJ Problem Set (tutorial)

3131. Time to Graduate


Problem code: CURICULA
Consider the following example. A student is required to take 4 courses, mt42, cs123, cs456, and
cs789. mt42 is only offered in the fall semester and has no prerequisites. Similarly, cs123 is only
offered in the spring semester and has no prerequisites. cs456 is only offered in the spring semester
and has both cs123 and mt42 as prerequisites. Finally, cs789 is offered in both fall and spring and has
cs456 as its only prerequisite. The shortest time to graduate is 5 semesters, by taking mt42 in the fall,
cs123 in the next spring, cs456 the following spring (since it is not offered in the fall) and finally
cs789 the following fall.

For this problem, there are only two semesters, fall and spring. Always start counting semesters from
the fall.

In addition to the fall/spring scheduling issues, there is one slight complication. In order to keep the
dormitories full, each university limits the number of courses that can be taken in any semester. This
limit appears as part of the input data. The third example below illustrates this issue.

Input
There are one to twenty-five data sets, followed by a final line containing only the integers ‘-1 -1’.
A data set starts with a line containing two positive integers n , 1 <= n <= 12 , which is the number of
courses in this data set and m , 2 <= m <= 6 , which is the maximum number of courses that can be
taken in any single semester. The next line contains the n course identifiers. Each is a 1-5 character
string from the set {a-z, 0-9}. Following the course identifiers is the individual course
information. This consists of n lines, one line for each course, containing the course identifier,
semester offered (‘F’=Fall, ‘S’=Spring, ‘B’=Both semesters), the number of prerequisite courses, p , 0
<= p <= 5 , and finally p prerequisite course identifiers. The first example data set below corresponds
to the problem described above.

Output
The output contains one line for each data set, formatted as shown in the sample output.

Example
Input:
4 6
cs123 mt42 cs456 cs789
mt42 F 0
cs123 S 0
cs456 S 2 cs123 mt42
cs789 B 1 cs456
3 6
math1 comp2 comp3
comp3 S 1 comp2
math1 S 0
comp2 F 1 math1

1
4 3
m10 m20 c33 c44
m10 B 0
m20 B 0
c33 B 0
c44 B 0
-1 -1

Output:
The minimum number of semesters required to graduate is 5.
The minimum number of semesters required to graduate is 4.
The minimum number of semesters required to graduate is 2.

Added by: Nikola P Borisov


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

2
SPOJ Problem Set (tutorial)

3250. The Seven Percent Solution


Problem code: SEVENPER
Uniform Resource Identifiers (or URIs) are strings like http://icpc.baylor.edu/icpc/,
mailto:foo@bar.org, ftp://127.0.0.1/pub/linux, or even just readme.txt that are used to identify a
resource, usually on the Internet or a local computer. Certain characters are reserved within URIs, and
if a reserved character is part of an identifier then it must be percent-encoded by replacing it with a
percent sign followed by two hexadecimal digits representing the ASCII code of the character. A table
of seven reserved characters and their encodings is shown below. Your job is to write a program that
can percent-encode a string of characters.

Character Encoding
" " (space) %20
"!" (exclamation point) %21
"$" (dollar sign) %24
"%" (percent sign) %25
"(" (left parenthesis) %28
")" (right parenthesis) %29
"*" (asterisk) %2a

Input
The input consists of one or more strings, each 1-79 characters long and on a line by itself, followed
by a line containing only "#" that signals the end of the input. The character "#" is used only as an
end-of-input marker and will not appear anywhere else in the input. A string may contain spaces, but
not at the beginning or end of the string, and there will never be two or more consecutive spaces.

Output
For each input string, replace every occurrence of a reserved character in the table above by its
percent-encoding, exactly as shown, and output the resulting string on a line by itself. Note that the
percent-encoding for an asterisk is %2a (with a lowercase "a") rather than %2A (with an uppercase
"A").

Example
Input:
Happy Joy Joy!
http://icpc.baylor.edu/icpc/
plain_vanilla
(**)

1
?
the 7% solution
#

Output:
Happy%20Joy%20Joy%21
http://icpc.baylor.edu/icpc/
plain_vanilla
%28%2a%2a%29
?
the%207%25%20solution

Added by: Nikola P Borisov


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

2
SPOJ Problem Set (tutorial)

3252. Persistent Bits


Problem code: PERBITS
WhatNext Software creates sequence generators that they hope will produce fairly random sequences
of 16-bit unsigned integers in the range 0-65535. In general a sequence is specified by integers A, B,
C, and S, where 1 <= A < 32768, 0 <= B < 65536, 2 <= C < 65536, and 0 <= S < C. S is the first
element (the seed) of the sequence, and each later element is generated from the previous element. If X
is an element of the sequence, then the next element is

(A*X + B) % C

where ’%’ is the remainder or modulus operation. Although every element of the sequence will be a
16-bit unsigned integer less than 65536, the intermediate result A*X + B may be larger, so calculations
should be done with a 32-bit int rather than a 16-bit short to ensure accurate results.

Some values of the parameters produce better sequences than others. The most embarrassing
sequences to WhatNext Software are ones that never change one or more bits. A bit that never changes
throughout the sequence is persistent. Ideally, a sequence will have no persistent bits. Your job is to
test a sequence and determine which bits are persistent.

For example, a particularly bad choice is A = 2, B = 5, C = 18, and S = 3. It produces the sequence 3,
(2*3+5)%18 = 11, (2*11+5)%18 = 9, (2*9+5)%18 = 5, (2*5+5)%18 = 15, (2*15+5)%18 = 17, then
(2*17+5)%18 = 3 again, and we’re back at the beginning. So the sequence repeats the the same six
values over and over:

Decimal 16-Bit Binary


3 0000000000000011
11 0000000000001011
9 0000000000001001
5 0000000000000101
15 0000000000001111
17 0000000000010001
overall 00000000000????1

The last line of the table indicates which bit positions are always 0, always 1, or take on both values in
the sequence. Note that 12 of the 16 bits are persistent. (Good random sequences will have no
persistent bits, but the converse is not necessarily true. For example, the sequence defined by A = 1, B
= 1, C = 64000, and S = 0 has no persistent bits, but it’s also not random: it just counts from 0 to
63999 before repeating.) Note that a sequence does not need to return to the seed: with A = 2, B = 0, C
= 16, and S = 2, the sequence goes 2, 4, 8, 0, 0, 0, ....

1
Input
There are from one to sixteen datasets followed by a line containing only 0. Each dataset is a line
containing decimal integer values for A, B, C, and S, separated by single blanks.

Output
There is one line of output for each data set, each containing 16 characters, either ’1’, ’0’, or ’?’ for
each of the 16 bits in order, with the most significant bit first, with ’1’ indicating the corresponding bit
is always 1, ’0’ meaning the corresponding bit is always 0, and ’?’ indicating the bit takes on values of
both 0 and 1 in the sequence.

Example
Input:
2 5 18 3
1 1 64000 0
2 0 16 2
256 85 32768 21845
1 4097 32776 248
0

Output:
00000000000????1
????????????????
000000000000???0
0101010101010101
0???000011111???

Added by: Nikola P Borisov


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

2
SPOJ Problem Set (tutorial)

3256. Rock Skipping


Problem code: ROCKSKIP
As a member of the International Rock-Skipping League, you travel to a different lake each week and
compete in a rock-skipping contest. The goal is to throw a rock so that it skips as many times as
possible; the exact rules for determining the winner are given below. To make the competitions
interesting, the IRSL often chooses lakes with logs, sandbars, and other obstacles. You are provided
with a side-view, water-level "map" of the lake as shown in the top line of the example below. (The
numbers 0..29 below the map are just for reference.) A period (".") indicates clear water, where a rock
will skip; any other character indicates some kind of obstacle that will stop a rock.

...=...**..#...@....:.:.:..=..
______________________________
11111111112222222222
012345678901234567890123456789

You stand at the left end of the lake. You can throw a rock so that it lands at any position in the lake,
and then skips at any fixed interval thereafter. So a throw can be defined as a pair (i,d), where i >= 0 is
the initial landing position and d > 0 is the distance between skips. Note that d must be positive. The
count of a throw is the number of times that it skips on the water. The length is the position of its last
contact with either the water or an obstacle. To rank two distinct throws, use the following criteria, in
order, until a winner is determined: count (highest wins); length (greatest wins); initial position
(greatest wins); distance between skips (smallest wins).

For the map shown above, throw (27,2) hits the obstacle at position 27; it has count 0 and length 27.
Throw (16,1) skips at positions 16, 17, 18, and 19, then hits the obstacle at position 20; it has count 4
and length 20, so it beats throw (27,2). Throw (2,7) skips at positions 2, 9, 16, and 23, then skips over
the lake; it has count 4 and length 23, so it beats throw (16,1). Throw (1,4) skips at positions 1, 5, 9,
13, 17, 21, 25, and 29, then skips over the lake; it has count 8 and distance 29, and is the best possible
throw for this lake.

Input
The input consists of one or more lake maps, each 1-40 characters long and on a line by itself,
followed by a line containing only "END" that signals the end of the input. Positions within a map are
numbered starting with zero. Maps will only contain printable ASCII punctuation characters. A period
indicates clear water and any other character indicates an obstacle.

Output
For each map, compute the best possible throw (i,d), then output a line containing i and d separated by
one space.

1
Example
Input:
...=...**..#...@....:.:.:..=..
.(+)
/^\.
*++&*
END

Output:
1 4
0 3
3 1
4 1

Added by: Nikola P Borisov


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

2
SPOJ Problem Set (tutorial)

3313. Software Bugs


Problem code: SOFTBUG

Problem text
The biggest problem for all software developers are bugs. You definitely know the situationwhen a
user calls to say "I’ve found a bug in your program". Once you have found and removedthe bug,
another one appears immediately. It is a hard and never-ending process.Recently, there appeared a
promising open-source initiative called "bug-preprocessor". The bug-preprocessor is a program able to
find all bugs in your source code and mark them, so they arerelatively easy to be removed. Your task
is to write a program that will remove all marked bugsfrom the preprocessed source code.

Input Specification
The input contains a text representing the preprocessed source code, an unspecified number oflines of
text, some of them may be empty. Bugs are represented by a case-sensitive string "BUG".The text is
terminated by the end of file. No line in the input will be longer than 100 characters.

Output Specification
Your program must remove all of the bugs from the input and print a text that does not containany
BUG strings. Nothing else than bugs may be removed, not even spaces.

Example

Output: print "No bugs here..."


Input: print "No bugs here..." void hello() {
void hello() { printf("Hello,
BUGBUG printfBUG("Hello, world!\n"); }  
world!\n"); } writeln("Hello
wriBUGBUGtelBUGn("Hello B-U-G");
B-U-G");

Added by: Robert Rychcicki


Date: 2008-11-07
Time limit: 10s
Source limit:50000B
Languages: C C99 strict C++ PAS gpc PAS fpc JAVA C# PERL PYTH TEXT
Resource: CEPC 2007

1
SPOJ Problem Set (tutorial)

3318. Pascals Travels


Problem code: PASCALTR
An n x n game board is populated with integers, one nonnegative integer per square. The goal is to
travel along any legitimate path from the upper left corner to the lower right corner of the board. The
integer in any one square dictates how large a step away from that location must be. If the step size
would advance travel off the game board, then a step in that particular direction is forbidden. All steps
must be either to the right or toward the bottom.

Consider the 4 x 4 board shown in Figure 1, where the solid circle identifies the start position and the
dashed circle identifies the target. Figure 2 shows the three paths from the start to the target, with the
irrelevant numbers in each removed.

$\textstyle \parbox{.24\textwidth}{ \begin{center} \mbox{} \epsfxsize=1.5in \epsfbox{p3390a.eps}


\par \medskip Figure 1 \end{center}}$ $\textstyle \parbox{.75\textwidth}{ \begin{center} \mbox{}
\epsfxsize=4.5in \epsfbox{p3390b.eps} \par \medskip Figure 2 \end{center}}$

  Figure 1   Figure 2

Input
The input contains data for one to thirty boards, followed by a final line containing only the integer
‘-1’. The data for a board starts with a line containing a single positive integer n , 4 <= n <= 34 ,
which is the number of rows in this board. This is followed by n rows of data. Each row contains n
single digits, 0-9, with no spaces between them..

Output
The output consists of one line for each board, containing a single integer, which is the number of
paths from the upper left corner to the lower right corner. There will be fewer than 2 63 paths for any
board.

Warning: Brute force methods examining every path will likely exceed the allotted time limit. 64-bit
integer values are available as long values in Java or long long values in C/C++ compilers.

Example
Input:
4
2331
1213
1231
3110
4
3332
1213
1232
2120

1
5
11111
11111
11111
11111
11111
-1

Output:
3
0
70

Added by: Nikola P Borisov


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

2
SPOJ Problem Set (tutorial)

3319. Speed Limit


Problem code: SPEEDLM
Bill and Ted are taking a road trip. But the odometer in their car is broken, so they don’t know how
many miles they have driven. Fortunately, Bill has a working stopwatch, so they can record their speed
and the total time they have driven. Unfortunately, their record keeping strategy is a little odd, so they
need help computing the total distance driven. You are to write a program to do this computation.

For example, if their log shows

Speed in miles per hour Total elapsed time in hours


20 2
30 6
10 7

this means they drove 2 hours at 20 miles per hour, then 6-2=4 hours at 30 miles per hour, then 7-6=1
hour at 10 miles per hour. The distance driven is then (2)(20) + (4)(30) + (1)(10) = 40 + 120 + 10 =
170 miles. Note that the total elapsed time is always since the beginning of the trip, not since the
previous entry in their log.

Input
The input consists of one or more data sets. Each set starts with a line containing an integer n, 1 <= n
<= 10,  followed by n pairs of values, one pair per line. The first value in a pair, s, is the speed in miles
per hour and the second value, t, is the total elapsed time. Both s and t are integers, 1 <= s <= 90 and 1
<= t <= 12.  The values for t are always in strictly increasing order. A value of -1 for n signals the end
of the input.

Output
For each input set, print the distance driven, followed by a space, followed by the word "miles". 

Example
Input:
3
20 2
30 6
10 7
2
60 1
30 5
4
15 1
25 2
30 3

1
10 5
-1

Output:
170 miles
180 miles
90 miles

Added by: Nikola P Borisov


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

2
SPOJ Problem Set (tutorial)

3320. Longest Monotonically Nondecreasing


Sequence
Problem code: LMIS
You are given a set of numbers on the standard input. You need to figure out what is the smallest
number of them that you need to remove so that you are left with the Longest Monotonically
Nondecreasing Sequence.

Input
On the standard input your are given a set with less than 1000000 integers each less than 30000.

Output
A single integer - the number of numbers you will remove.

Example
Input:
3 1 2 0 5 4 10

Output:
3

(you need to remove 3, 0, (5 or 4), then you will be left with 1, 2, (5 or 4), 10).

Added by: Nikola P Borisov


Date: 2008-11-09
Time limit: 15s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

3321. The Knapsack Problem


Problem code: KNAPSACK
The famous knapsack problem. You are packing for a vacation on the sea side and you are going to
carry only one bag with capacity S (1 <= S <= 2000). You also have N (1<= N <= 2000) items that
you might want to take with you to the sea side. Unfortunately you can not fit all of them in the
knapsack so you will have to choose. For each item you are given its size and its value. You want to
maximize the total value of all the items you are going to bring. What is this maximum total value?

Input
On the first line you are given S and N. N lines follow with two integers on each line describing one of
your items. The first number is the size of the item and the next is the value of the item.

Output
You should output a single integer on one like - the total maximum value from the best choice of items
for your trip.

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

Output:
13

Added by: Nikola P Borisov


Date: 2008-11-10
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

3370. Mergesort
Problem code: MERGSORT
Simple. Sort the numbers on the standard input using the merge sort algorithm. Don’t try to cheat by
just calling your build in functions... I can see your source.

Input
On the standard input you will receive N (1 <= N <= 100000). Each number will fit in 32-bit integer

Output
Output the same integers in a sorted manner. Smallest to largest.

Example
Input:
7 3 2 5 4 3

Output:
2 3 3 4 5 7

Added by: Nikola P Borisov


Date: 2008-11-17
Time limit: 1s-2s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

3371. Fast Power


Problem code: FASTPOW
You are asked to compute A^B (A to the power of B) (1 <= A,B <= 100 000 000). You surely
understand that this number can be quite astonishing and i don’t like big numbers unless they are on
my paycheck so I’m just interested in the reminder of A^B mod C (1<= C <= 1000000)

Input
Three integers A B and C.

Output
Single integer - the result of the computation.

Example
Input:
2 10 1000

Output:
24

Added by: Nikola P Borisov


Date: 2008-11-17
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (classical)

3378. Mirrored Pairs


Problem code: MIRRORED
The letters b and d are mirror images of each other, as are p and q. No other pairs of letters are mirrors,
except for letters like H that are mirrors of themselves, and what’s the interest in a pair that’s just two
of the same letter? We refuse to count self-mirrors as mirrored pairs.

Input
Input is a list of lines with two characters on each line. Your program should end immediately when it
encounters a line with two spaces.

Output
The first line of output should contain only Ready. For each pair of characters (prior to a pair of
spaces), print the line Mirrored pair if the characters are mirrors, otherwise print the line Ordinary pair.

Example
Input:
Fr
qp
HH
db

pq

Output:
Ready
Ordinary pair
Mirrored pair
Ordinary pair
Mirrored pair

Added by: Daniel Gómez Didier


Date: 2008-11-17
Time limit: 1s
Source limit:50000B
Languages: All
Resource: 2007 PUJ - Circuito de Maratones ACIS / REDIS

1
SPOJ Problem Set (classical)

3386. Contest System Quality Assurance Tester


Problem code: QUALITY
Write a program to score a small, three-problem programming contest. Each input line contains six
space-separated integers representing raw score data. The first three integers are in the range 0 . . .
100000. They represent seconds taken to solve the first, second, and third problems, respec- tively.
Zero seconds indicates that a problem has not been solved. The last three integers are in the range 0 . .
. 100, representing the attempts taken to solve the first, second, and third problems, respectively. Every
failed attempt is penalized with 20 minutes, but only for problems that are eventually solved.
Each output line should begin with the string team, followed by a single space, the input line number,
a colon, a single space, the number of solved problems, a comma, a single space, and the total number
of seconds including penalties it took for the solved problems.
Input:
0 777 0 4 1 1
1 1 1 1 1 1

Output:
team 1: 1, 777
team 2: 3, 3

Added by: Daniel Gómez Didier


Date: 2008-11-18
Time limit: 2s
Source limit:50000B
Languages: All
Resource: 2007 U.Nacional - Circuito de Maratones ACIS / REDIS

1
SPOJ Problem Set (tutorial)

3421. Garden Hull


Problem code: GARDENHU
We have a garden with trees in it. For each tree is represented by x and y coordinates. Your goal is to
find the least amount of net needed to surround all the trees so that all trees are inside the net. In other
words you need to find the the length of the convex hull around those points

Input
On the first line a lonely integer N (3 <= N <= 10000) representing the number of trees in the garden.
On each of the following N lines you will find two integers - the coordinates of the next tree.

Output
A single integer - the length of the convex hull. Round it up to an integer.

Example
Input:
4
0 0
5 0
1 1
0 5

Output:
17

Added by: Nikola P Borisov


Date: 2008-11-24
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Fall Bulgarian National Contest 2003

1
SPOJ Problem Set (tutorial)

3422. Calculate the Area


Problem code: CALCAREA
Very simple. You are given polygon and you need to calculate his area. The polygon does not self
intersect

Input
A lonely integer N (3 <= N <= 10000) - the number of nodes. On each of the next N lines you will find
the coordinates of the next vertex from the polygon.

Output
A single integer - the rounded up area of the polygon.

Example
Input:
4
0 0
1 0
1 1
0 1

Output:
1

Added by: Nikola P Borisov


Date: 2008-11-24
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

3440. Enormous Input and Output Test


Problem code: INOUTEST
Similar to that of the problem Enormous Input Test, the purpose of this problem is to determine
whether your method of reading input data and writing output data is fast enough to process extremely
large test cases.

Input
The first line of input contains a single integer N (1 <= N <= 10 6 ), denoting the number of lines to
follow. Each of these lines contains two space-separated integers a and b (|a|, |b| <= 40,000).

Output
For each pair a and b, write a single line of output containing the value of a × b.

Example
Input:
5
-1 -1
1 1
0 999
654 321
39999 -39999

Output:
1
1
0
209934
-1599920001

Added by: Neal Wu


Date: 2008-11-30
Time limit: 20s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

3443. Netiquette
Problem code: NETIQUE
Mr. Manners teaches netiquette ("net etiquette", particularly as it applies to email) at the local
community college. There are many different aspects to proper netiquette, including courtesy, correct
spelling, and correct grammar. Through experience Mr. Manners has found that his college’s email
system does a good job of catching most spelling and grammatical errors, and he’s also found that
most of his students are courteous. So there are four violations of netiquette that Mr. Manners pays
careful attention to, and he’s devised a quick way to test for them. A message is suspicious if it
contains any of the following:

1. two adjacent uppercase letters,


(because you might be SHOUTING)
2. a digit adjacent to a letter,
(because you might be l33t, d00d)
3. an isolated character other than a, A, or I,
(because u r probably abbreviating words; the spell checker doesn’t catch this for some reason)
4. two adjacent punctuation marks, unless one of them is a double quote (the character ").
(because you might be using an emoticon :-)

For this problem, all characters in an email message are printable ASCII characters with codes in the
range 32..126 (inclusive). A punctuation mark is any character other than a letter, digit, or space. Two
characters are adjacent if they are right next to each other, with no characters in between. An isolated
character is one whose only adjacent characters (if any) are spaces. Your job is to write a program that
can tell if a one-line email message is suspicious.

Input
The input consists of one or more email messages, followed by a line containing only # that signals the
end of the input. Each message is on a line by itself, does not begin or end with a space, and does not
contain consecutive spaces. End-of-line characters occur at the end of every line (of course), but they
are not considered to be part of the message. A message will contain 1..80 characters.

Output
For each message, output suspicious if it meets one or more of the four criteria defined above, and
output OK otherwise. In the examples below, the second email meets all four criteria, and the fourth
and sixth emails meet one criterion each.

Example
Input:
"This is a safe message," said 50 wise men.
DON’T b l8 for the Apple ][ user’s group meeting.
I ate at "Al’s Big Burritos" for lunch!
It’s not OK to burp at your grandmother.

1
*BuT* YoU _CaN_ Do ThIs, YoU KnOw.
We 8 eight oranges.
#

Output:
OK
suspicious
OK
suspicious
OK
suspicious

Added by: Nikola P Borisov


Date: 2008-12-02
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Mid-Central Regional ACM-ICPC Contest 2005

2
SPOJ Problem Set (classical)

3580. Company
Problem code: COMPANY
In Plumsoft company, there is a hierarchy among employees, i.e. some of them are bosses to the
others. Person A is in charge of person B if there is a sequence of employees P 1 = A, P 2 , ..., P k = B,
such that P 1 is P 2 ’s boss, P 2 is P 3 ’s boss, ..., and P k-1 is P k ’s boss. As Plumsoft is a pretty sane
company, you can assume that no two employees can be in charge of each other. The management
wants to cut the costs of meetings (they eat a lot of food), so they plan to minimize the number of "A is
boss of B" relations by keeping only some of the existing ones. However they want to keep all "A is in
charge of B" relations. Please, help them to successfully make this transition.

Input
The first line of the input contains two integers N and M separated by a space character (1 <= N <=
1000, 1 <= M <= 10000). N is the number of employees, and M is the number of "boss" relations in
the company. Employees are labeled with numbers 1 through N. Each of the next M lines contain two
labels A and B separated by a space character, meaning that A is a boss of B.

Output
In the first line of the output, write a single number M min , which is the minimum number of "boss"
relations that the company has to keep. In the next M min lines write the relations that are kept. In each
line, write two labels A and B separated by a space character, meaning that A is still a boss of B. If
there are multiple solutions, write any of them. Relations can be listed in any order. Each line of the
output should be followed by a newline.

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

Output:
5
3 5
1 4
4 3
1 2
2 3

1
Added by: Jelani Nelson (Minilek)
Date: 2008-12-22
Time limit: 2s
Source limit:50000B
Languages: All
Resource: MIT Individual Contest 2008

2
SPOJ Problem Set (tutorial)

3695. n-th Power


Problem code: LOGPOWER
Given an integer A, N and M, calculate R = A N modulo M, ie. the remainder after dividing N-th power
of A by the modulus M.

Input
First line: positive integer T - numer of test cases, T<1000.
> Next T lines contain 3 integers each: A i<sub>, N i and M i .
> Data constraints:
> -2 30 < A i < +2 30
> 0 < N i<sub> < +2 60
> 2 < M i<sub> < +2 30
>

Output<h3>
For each of test cases, output the number R - one in each line. i

Example
Input:
6
1 2 3
4 5 6
7 8 9
12 34 56
78 90 123
4567890 123456789012 34567890

Output:
1
4
4
16
42
781950

1
Robert
Added by:
Rychcicki
Date: 2009-01-10
Time limit: 0.400s
Source
50000B
limit:
Languages: All

2
SPOJ Problem Set (tutorial)

3699. Fibonacci numbers


Problem code: LOGFIB
Let’s define:
> F(0)=0, F(1)=1.
> F(j)=F(j-1)+F(j-2), for j>1
>
> P(0)=0, P(1)=1, P(2)=2
> P(j)=P(j-1)+2P(j-3), for j>2
> Given an integer X and M, calculate the remainder of F(X) and P(X) after dividing them by the
modulus M.

Input
First line: positive integer T - numer of test cases, T<20000.
> Next T lines contain 2 integers each: X i<sub>, and M i .
> Data constraints:
> 0 < X i < +2 60
> 2 < M i<sub> < +2 30
>

Output<h3>
For each of test cases, output the numbers F(X i ) mod M i and P(X i )
mod M i separated by a single space - one line per test case.

Example
Input:
6
1 23
4 56
7 89
123 456
7890 123
123456789012 34567890

Output:
1 1
3 4

1
13 20
2 204
55 103
29441184 24923102

Robert
Added by:
Rychcicki
Date: 2009-01-10
Time limit: 15s
Source
50000B
limit:
Languages: All

2
SPOJ Problem Set (tutorial)

3727. Lucky Number


Problem code: KLUCKY
The Kurukshetra OPC team observed that many online programming contests have a problem titled
"Lucky Number". So we decided to have one in KOPC too.

We define the Lucky sequence as the infinite sequence of all integers, in ascending order, that can
represented as any positive integer power of 5 (i.e 5 k where k is a positive integer) or as a sum of
distinct positive integer powers of 5 (i.e 5 a1 + 5 a2 + 5 a3 + ... , where a1,a2,a3, ... are distinct positive
integers). All the numbers in the lucky sequence are called lucky numbers. The first few lucky
numbers are 5, 25, 30, 125, 130, 150, ...

Given n your task is to find the n th lucky number.

Input
First line of input contains an integer t, t <= 200, representing the number of test-cases. Then t lines
follow each containing one integer n, 1 <= n <= 8000.

Output
For each test case output the nth lucky number on a separate line. Answers will fit in a 32-bit signed
integer.

Example
Input:
4
1
2
3
9

Output:
5
25
30
630

Added by: u.swarnaprakash


Date: 2009-01-17
Time limit: 2s
Source limit:50000B
Languages: All
Resource: Kurukshetra 09 OPC

1
SPOJ Problem Set (acm)

3903. Special Hashing


Problem code: SPHASH
Linear Probing is one of the most used Hashing techiniques. We define here a special hashing which is
similar to linear probing.

The following operations are defined.

Hash: Hash is defined for a number N to be N%k.


Move forward : Move to the next number (the number connected by the forward link) . Initially,
every number’s forward link points to the itself. (currentIndex).
Move backward : Move to the previous number (the number connected by the back link) .
Initially, every number’s back link points to the itself in the link (currentIndex).
Insertion operation: Given a number N , find hash(N)=N%k where k is the size of the list. If the
list[hash(N)] is empty the element is inserted at position hash(N) in the list and forward link is
made to point at (currentIndex+1)%(size of list) and backward link is made to point at
(currentIndex-1+sizeof list)%(size of list). If it is filled , we do move_forward/move_backward as
specified and then the same process is again repeated.

Note: Thus list is circular due to modulus property.

Merge Operation: Let x be a index in the list which is not empty. Calculate xmin by doing a
move_backward from index x till the previous index is empty . Similarily calculate xmax by
doing a move_forward from index x till the next element is an empty space . Do the same for y to
find out ymin and ymax. For a valid merge operation, the index x and y should not be empty and
either xmax < ymin or ymax < xmin. Now, when merging x and y, if ymin > xmax, the forward
link of xmax is made to point at ymin and the backward link of ymin is made to point to xmax.
Same approch is applied in the other case.

Note: for the merge operation take the min(b,c). The merge is only to be done from x(b)max to
x(c)min if the merge was allowed.

Input
The first line of input contains a number representing the number of test cases. Each test case states
with a line conataining two integers k(size of list) and C(operations to be applied).C lines follow. Each
line contains a,b,c. a is 0 for merge operation followed by index b and c to be merged. a is 1 for insert
operation and b is the element to be inserted and c is either 0 or 1(1 in case of left insertion and 0 in
case right).

Output
For each operation in each test case,

1
Case 1: Insertion operation print the position of the hash(b). If the number cannot be inserted print the
string "cannot insert element"

Case 2: Merge operation print "merge successful" if the merge was succesful and "cannot merge" if
the merge operation failed.

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

Output:

cannot merge
1
2
4
merge successful
0

Constraints
Dataset 1:T<25, k <==10000,C<=25000 Score: 100
Time limit: 5s Memory Limit: 128MB
Dataset 2:T<8, k <==400000,C<=800000 Score: 50
Time limit: 5s Memory Limit: 128MB

Added by: Race with time


Date: 2009-02-19
Time limit: 5s
Source limit:50000B
Languages: All
Resource: Code Craft 09

2
SPOJ Problem Set (tutorial)

3916. Bicolor
Problem code: BICOLOR
When you look at a political map of the world, each country is colored in color different from its
neighbors’ so that you can clearly see the borders. But as you know, the are between 192 and 195
countries in the world (depending on where you live) so it is common for two countries on the map to
have the same color. After all, men can see only 16 colors ("Peach" is not a color according to me), so
it has been a hard question for a long time if it is possible to color the map of the world with just 4
colors, following the rule that you are not allowed to color neighboring countries with the same color.
This problem, however, is not easy at all, and we are going to simplify it a little bit. You are a Rock
Star, and you are going on a tour in the galaxy. You are looking at the map of the sky and some of the
stars are connected with other stars to form oddly shaped constellations. You are wondering if the stars
can be bicolored (colored with just two colors) following the rule that you can not color two stars with
the same color if they are directly connected with line on the map. You are bored as you are traveling
towards the first star on your tour with speeds close to the speed of light so the clock in your space
ship are ticking slower. Having nothing better to do, you decide to write a computer program to solve
it.

Input
The input will consist of multiple maps. Each map starts with the number of stars on the map N (1 <=
N <= 1024). On the next line is the number M (1<= M <=30000), the number of lines on the map
connecting the stars. The stars are numbered with integers from 0 to N-1. On the next M lines you will
find 2 integers - the ID-s of two stars that are connected. To denote the end of the input, the last map
will have N = 0, and at this point you should stop reading.

Output
For each map in the input case, you need to output exactly one line in the output containing either the
string "NOT BICOLORABLE" or "BICOLORABLE".

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

1
Output:
NOT BICOLORABLE
BICOLORABLE

Added by: Nikola P Borisov


Date: 2009-02-21
Time limit: 1s
Source limit:50000B
Languages: All

2
SPOJ Problem Set (tutorial)

3917. Tree Query


Problem code: TREEQ
You are given a full binary tree, and there is an integer representing the data at each node of the tree.
The other members of your band are asking you questions in the following form. They give you an
integer X, and you have to tell them which leaf of the tree will get X for if you follow the path from it
to the root of the tree and sum the numbers in each node. If there are two such leaves, choose the one
with a smaller ID. The root of the tree has an ID of 0. Its left child has an ID of 1, and its right one an
ID of 2. In more mathematical form, if you have a node with an ID of x, then the left child of x is
2*x+1 and the right one is 2*x+2. The members of your band will be impressed if you answer their
questions fast and correctly. Cool!

Input
The input consists of multiple test cases. Each test case starts with the number of nodes in the tree N
(1<= N <= 1000). The last test case will have N = 0, so at this point you should quit. As you know a
full binary tree with N nodes will have N = (2^x) - 1 nodes. The nodes are given IDs using the scheme
described above, and the root has an ID of 0. On the next N lines of the input, you will find the the
data that is stored in the corresponding node. On the next line after this is the integer M (1<= M <=
1000) - the number of question the band members are going to ask you. On each of the next M lines
you will find one integer representing the question.

Output
For each of the questions you have to output the minimum ID of a leaf node that meets the
requirements. If no leaf meats the requirements output "NOT FOUND". Refer to the example tests.

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

Output:
NOT FOUND
1
2
NOT FOUND

1
Added by: Nikola P Borisov
Date: 2009-02-21
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Microsoft Interview

2
SPOJ Problem Set (tutorial)

3918. Rock Star Tour


Problem code: RSTOUR
You and your band are so famous that people from all around the world want to hear you. Even people
in Bulgaria, so you decide to make a tour there. Funnily enough, all the cities in Bulgaria have names
with the same length and only use lower case letters from the English alphabet. You are thinking about
which cities to visit during your tour, and because you are a polite Rock Star you would like to start
each concert with the sentence "Make some noise Sofia" or "Make some noise Varna". Unfortunately
you are not really good with foreign languages, so you want two cities that are next to each other in the
tour schedule to have names that differ in at most 2 characters. For example "aaaaa" and "aaabb" are
ok to be next to each other but "aaaaa" and "cccca" are not because they have a difference of 4
characters. You are wondering between different possibilities of a start and end city of the tour. It
would be useful to know for given start and end cities, what the distance of the shortest tour is.
Another interesting thing is if a tour is even possible given a start and an end city.

Input
Again, the input consists of multiple test cases. For each test case, on the first line is the number N (1
<= N <= 1000) - the number of cities in Bulgaria. On the next N line you will find the name of the N
cities. All names have the same length. The first integer after this is the number of possibilities you are
considering - M (1<= M <= 1000). On the next M lines there will be a question in one of two possible
forms: "LENGTH start-city-name end-city-name" or "POSSIBLE start-city-name end-city-name".
When you are asked the LENGTH question, you have to output the shortest possible tour length (by
the number of trips you will need to do, or 1 less than the number of cities) or -1 if such tour is
impossible. If the question is POSSIBLE that you just need to tell if tour with this starting and ending
city is possible.

Output
For each question, output a line in the form "Query #X" where x is the number of the question in the
test case, and another line with the answer. If the question was LENGTH output the min length of the
tour or -1 if it is impossible. For a POSSIBLE question answer with "YES" or "NO"(quotes are here
for clarity only). Refer to the example tests.

Example
Input:
4
aaaaa
aaaab
aabbb
ccccc
4
LENGHT aaaaa aabbb
POSSIBLE aaaab ccccc
LENGHT aaaaa ccccc
POSSIBLE aaaab aaaaa

1
6
bbbb
abbb
aaaa
baba
aabb
aaab
5
LENGHT aabb aaaa
POSSIBLE aabb aaab
POSSIBLE aaaa bbbb
LENGHT aaab aabb
POSSIBLE aabb aaaa

Output:
Query #1
2
Query #2
NO
Query #3
-1
Query #4
YES
Query #1
1
Query #2
YES
Query #3
YES
Query #4
1
Query #5
YES

Added by: Nikola P Borisov


Date: 2009-02-21
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Google Interview

2
SPOJ Problem Set (tutorial)

3997. HARDWARE
Problem code: HARDWARE
Ola Clason’s Hardware store is an old company where most work is done "the old way". Among other
things, the company is the one and only provider of marble house numbers. These house numbers have
become extremely popular among construction companies, especially the ones building luxury estates.
This is of course great for Ola Clason, but also a small problem. Nisse, who has been managing the
incoming orders has turned out to be a bottleneck in Ola’s business. Most orders are on the form
"Coconut Drive 200, 202, 204, ..., 220". This means every even number between 200 and 220. Nisse’s
work is to transfer an order to a list of necessary digits and other symbols. Your assignment is to write
a program that automates Nisse’s work with orders containing only positive integer house numbers.
Nisse will still in the future process all special orders (those including non digit symbols) by hand.

Input
On the first line of input is a single positive integer n, specifying the number of orders that follow. The
first line of each order contains the road name for that order. No road name is longer than 50
characters. The second line states the total number of buildings needing new marble numbers on that
order. Then follows the different house number specifications on several lines. These lines are of two
kinds: single number lines and multiple number lines. A single number line simply consists of the
house number by itself, while a multiple number line starts with a "+"-sign, followed by three positive
integer numbers: first number, last number and the interval between the house numbers. The distance
between the first and last house number will always be a multiple of the house number interval. A
house number will never have more than five digits. After the last house number specification line, the
next order follows, if there is any.

Output
For each order, the output consists of 13 lines. The first and second lines should be identical with the
first two input lines. Then, there follows 10 lines with information on how many marble digits of each
kind the order consists of. These rows are on the format "Make X digit Y" where X is how many
copies of digit Y they need to make. The last row states the total number Z of digits needed, on the
format "In total Z digits". If there is only one digit to produce, it should say "In total 1 digit", in order
to be grammatically correct.

Example
Input:
1
Short Street
23 addresses
+ 101 125 2
275
+ 100 900 100

Output:
Short Street

1
23 addresses
Make 23 digit 0
Make 22 digit 1
Make 5 digit 2
Make 4 digit 3
Make 1 digit 4
Make 5 digit 5
Make 1 digit 6
Make 4 digit 7
Make 1 digit 8
Make 3 digit 9
In total 69 digits

Added by: Fabio Avellaneda


Date: 2009-03-01
Time limit: 60s
Source limit:50000B
Languages: All except: ICON
Resource: I maratón interuniversitaria del circuito Redis - Acis. Sedes: Politécnico - Javeriana

2
SPOJ Problem Set (tutorial)

4001. JACKPOT
Problem code: JACKPOT
Bill has found the perfect way to make money playing the slot machines. After months of careful
research, he has finally figured out the mechanics behind how the machines operate. Now he is ready
to make profit of his findings. But first an introduction to the game. A slot machine consists of a
number of wheels, usually three or four, each with a number of symbols printed on it - cherries,
oranges, bells, etc. - and will show one of its symbols at a given time. To play, you insert a coin, push
a button and the wheels start spinning. After spinning for a while, each wheel stops - at random it
seems - at one of its symbols. If all wheels stop at the same symbol, or some nice combination of
symbols, the player wins. One combination that is especially desirable is having the jackpot symbol on
all wheels. This combination is simply called ’jackpot’ and will make you rich for life. What Bill has
discovered is that each wheel will stop at the jackpot symbol with a certain periodicity, which differs a
lot between wheels. He has also figured out (after some sneeking around at the slot-machine factory)
that all newly manufactured slot-machines are delivered showing the jackpot combination, and that
they all have a counter at the back, telling how many times the machine has been played. This counter
is always set to zero at delivery. Now, all Bill needs to do is to calculate the number of times a
machine has to be played between two occurrences of the jackpot combination. We will call this
number the jackpot periodicity. This is of course the same as the number of times the machine has to
be played after leaving the factory, before it gives its first jackpot. Thus, with a glance at the counter
on the back of a machine, Bill can figure out if it is about to give a jackpot. As Bill knows that you are
a skillful computer programmer, he turns to you with the problem of calculating the jackpot
periodicity. For each machine, he will give you the number of wheels, and the periodicity with which
the jackpot symbol shows up on each wheel.

Input
One line with the number of machines n <= 20. For each machine, one line with the number of wheels
w <= 5, and one line with w numbers, p1, ..., pw the periodicity of each wheel pk <= 1000.

Output
One line per machine: The jackpot periodicity of the machine, if it is less than or equal to a billion
(10^9), otherwise output the text ’More than a billion.’.

Example
Input:
1
3
10 6 15

Output:
30

1
Added by: Fabio Avellaneda
Date: 2009-03-01
Time limit: 60s
Source limit:50000B
Languages: All
Resource: I maratón interuniversitaria del circuito Redis - Acis. Sedes: Politécnico - Javeriana

2
SPOJ Problem Set (tutorial)

4073. The 3n plus 1 problem


Problem code: PROBTNPO
Background:
Problems in Computer Science are often classified as belonging to a certain class of problems (e.g.,
NP, Unsolvable, Recursive). In this problem you will be analyzing a property of an algorithm whose
classification is not known for all possible inputs.

The Problem:
Consider the following algorithm:

1. input n

2. print n

3. if n = 1 then STOP

4. if n is odd then n = 3n + 1

5. else n = n / 2

6. GOTO 2

Given the input 22, the following sequence of numbers will be printed 22 11 34 17 52 26 13 40 20 10
5 16 8 4 2 1

It is conjectured that the algorithm above will terminate (when a 1 is printed) for any integral input
value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been
verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers
than this.)

Given an input n, it is possible to determine the number of numbers printed (including the 1). For a
given n this is called the cycle-length of n. In the example above, the cycle length of 22 is 16.

For any two numbers i and j you are to determine the maximum cycle length over all numbers between
i and j.

The Input:
The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers
will be less than 1,000,000 and greater than 0.

You should process all pairs of integers and for each pair determine the maximum cycle length over all
integers between and including i and j.

You can assume that no operation overflows a 32-bit integer.

1
The Output:
For each pair of input integers i and j you should output i, j, and the maximum cycle length for integers
between and including i and j. These three numbers should be separated by at least one space with all
three numbers on one line and with one line of output for each line of input. The integers i and j must
appear in the output in the same order in which they appeared in the input and should be followed by
the maximum cycle length (on the same line).
Sample Input:
1 10
100 200
201 210
900 1000

Sample Output:
1 10 20
100 200 125
201 210 89
900 1000 174

Added by: Coach UTN FRSF


Date: 2009-03-18
Time limit: 3s-10s
Source limit:50000B
Languages: All
Resource: http://icpcres.ecs.baylor.edu/onlinejudge/

2
SPOJ Problem Set (tutorial)

4074. Compile Error


Problem code: CE
You are to write a program to analyse some simple arithmetical expressions. The BNF form of the
defination of the expression is below.
<expression>::=<num><oper><num>
<num>::=0|1|2|...|99
<oper>::=+|-|*

Tip: You may find this problem is like the problem GALAXY very much. You may use any language
you like to solve this problem.

Input
Exactly 99 test cases.

Each test case contains one line with a correct expression, without leading or trailing spaces.

Output
For each test case you should output one line contains the result of the expression without any leading
zeros. You may assume this number is always a non-negative one.

Score
Score is the length of your source.

Example
Input:
6*7
67-25
31+11
[And 96 test cases more.]

Output:
42
42
42
[And 96 test cases more.]

1
Added by: [Trichromatic] XilinX
Date: 2009-03-19
Time limit: 10s
Source limit:10000B
Languages: All
Resource: A copy of problem GALAXY, with language restrictions and source limit modified.

2
SPOJ Problem Set (tutorial)

4190. A plus B
Problem code: APLUSB2
Given 2 integers, A and B, find their sum. Beware: There are no limits on A and B

Input
Two integers up to 100000 digits in length

Output
Output their sum

Example
Input:
1
4

Output:
5

Added by: Saravannan Shaan


Date: 2009-04-09
Time limit: 1s-60s
Source limit:50000B
Languages: All except: C99 strict JAVA PYTH RUBY
Resource: Classic

1
SPOJ Problem Set (tutorial)

4207. Mobile (Again)


Problem code: MFMOBILE
Fred is a baby. Above Fred’s crib hangs a mobile. Fred is amused by this mobile. Fred has a twin
sister, Mary. Above Mary’s crib hangs another mobile. Fred wonders whether the mobile above his
crib and the mobile above Mary’s crib are the same. Help Fred.
A mobile is a collection of bars, strings, and decorative weights suspended from the ceiling. Each bar
is suspended by a string tied to the exact centre of the bar. From each end of a bar hangs a string that is
tied either to another bar or to a weight. The bars can rotate freely about their centres. Fred cannot tell
two bars apart, even if they have different lengths. Fred also cannot tell two strings apart. Fred
therefore considers two mobiles to be the same if the bars of one mobile can be rotated somehow to
make the two mobiles appear identical.
Fred has even developed a notation for describing mobiles. He assigns each bar a distinct positive
integer from 1 to the number of bars in the mobile, and he assigns the various objects negative
integers. 1 always represents the bar suspended from the ceiling. (So, for example, a biplane might be
represented by Fred as object -2, a crescent-moon might be object -57, and a star might be object -21.)
Fred can only count down to -9999, so you can assume that he gave no objects lower numbers than
-9999.

Input
The input contains two mobile descriptions. The first line of a mobile description contains a single
nonnegative integer n (1 <= n <= 100000), indicating the number of bars in the mobile. On the next n
lines, there are two numbers per line, with these two numbers representing the objects hanging from
bar i.

Output
Output is composed of one line. Write "Fred and Mary have different mobiles." if Fred’s information
is enough to distinguish the two mobiles; otherwise, "Fred and Mary might have the same mobile.".

Example #1
Input:
5
2 3
4 5
-1 -2
-3 -4
-5 -6
5
2 5
-1 -2
-3 -4
-5 -6

1
3 4

Output:
Fred and Mary might have the same mobile.

Example #2
Input:
5
2 3
4 5
-3 -4
-1 -2
-5 -6
5
2 5
-1 -2
-3 -4
-5 -6
3 4

Output:
Fred and Mary have different mobiles.

Added by: Analysis Mode (Elspeth, Knight-Errant)


Date: 2009-04-12
Time limit: 1s
Source limit:50000B
Languages: All except: C99 strict
Resource: Canadian Computing Competition 2008 Stage 2 Day 1 Problem C

2
SPOJ Problem Set (tutorial)

4215. Inversions
Problem code: INV
Calculate the number of ways that k things can be ’chosen’ from a set of n things.

Input
The first line of input is the number of tests t <= 100000. Next t lines contains two integers each n and
k, separated with a single space. 0 <= k <= n <= 100000.

Output
For each test output the number of ways that k things can be ’chosen’ from a set of n things modulo
1000000007.

Example
Input:
3
9876 5432
100 50
100000 50000

Output:
266875274
538992043
149033233

Added by: Spooky


Date: 2009-04-13
Time limit: 4s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

4245. Place the Numbers I


Problem code: PLCNUM1
Little Chucha is having a lot of fun with her new computer game. She is given a NxN board which she
has to fill with the numbers 1 to N^2, no repetitions allowed. The computer calculates the sum of
distances for each pair of consecutive numbers, that is, 1 -> 2, 2 -> 3, ..., N^2 -> 1. The goal is to make
that sum as short as possible.

Input
Input consists of a single integer number 1<=N<=100, the size of the board.

Output
Output one possible placing of the numbers. You are to write N lines, N space separated integers each.

Example
Input:
3

Output:
1 2 3
4 5 6
7 8 9

Score:
Score for the example is:
Distance 1 -> 2 : 1
Distance 2 -> 3 : 1
Distance 3 -> 4 : 3
Distance 4 -> 5 : 1
Distance 5 -> 6 : 1
Distance 6 -> 7 : 3
Distance 7 -> 8 : 1
Distance 8 -> 9 : 1
Distance 9 -> 1 : 4
Sum of distances (SOD): 16, Min SOD: 10, Score: 1+16-10=7 points.

Added by: yandry pérez clemente


Date: 2009-04-22
Time limit: 3s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

4293. Weightlifting
Problem code: BENCH
Joe the Jock is spending the day at the gym, and he needs a certain amounts of weight for his
benchpress sets.

The gym has several different types of weights, each no more than 100kg. There are an unlimited
number of each type of weight.

Spare Joe the math and write a program to figure out what weights he should lift.

He thinks the bigger weights look a lot more impressive, so make sure to give him the biggest weights
possible (e.g. 3,2,2 would be better than 3,2,1,1).

Unfortunately, it might also be impossible to reach the desired weight in any way.

Input
The first line is T (<50), the number of sets Joe has to do. Each of the T set descriptions are followed
by a line.

The first line of each set is the total weight Joe needs, in decigrams (tenths of a gram), not more than
10^6. The second line is N (<100), the number of distinct denominations of weight. The following N
lines are the weights, in decigrams.

Output
Separate the solutions for the sets by a blank line.

For each set, output one line for each type of weight he will use at least once, from heaviest to lightest.
Each line will have the weight (in decigrams), a single space, and the number of that type of weight.

If a set is impossible to make, output a single line -1 instead.

Example
Input:
3

10
3
3
1
2

5
1
10

1
4799
5
2
3
6
7
42

Output:
3 3
1 1

-1

42 114
7 1
2 2

Added by: Paul Draper


Date: 2009-05-01
Time limit: 1s-2s
Source limit:50000B
Languages: All

2
SPOJ Problem Set (classical)

4323. Voting Districts


Problem code: VOTE
The land of Yu consists of N cities, labeled 1,2,...N connected by N-1 roads in such a way that there
exists a path between any two cities.

For the first time in history, Yu is holding free elections. But they need to divide their new republic
into voting districts.

The division of Yu into voting districts must satisfy the following:

Each city belong to exactly one district.


Districts must have an equal number of cities.
Each district must be entirely self-connected (i.e. for any two cities in the same district, there
exists a path between them passing only including cities of that district).

For what numbers of voting districts can this work?

Input
The first line of input is the number of test cases (less than 100) to follow.

Each test case is preceded by a blank line and begins with N (less than 10^5), the number of cities.  N
lines follow.

The first integer of the ith line (indexing starting at 1) is K_i, the number of cities directly connected to
City i.  The next K_i integers are the cities directly connected to City i.

Output
For each test case print a line of all numbers of districts into which Yu can be divided, from least to
greatest, separated by spaces.

Example
Input:341 22 1 32 2 41 343 2 3 41 11 11 110Output:1 2 41 41

Note: Notice that Yu can always be divided into 1 district (of N cities), or N districts (of 1 city each).

Added by: Paul Draper


Date: 2009-05-05
Time limit: 0.5s-8s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

4349. Power Tower


Problem code: POWTOWER
Calculate

a_1^a_2^...a_n mod b

for integers a_1,a_2,...a_n and b.

Constraints
0 < n < 10^3
0 < a_1,a_2,...a_n,b < 10^6

Input
The first line is the number of test cases to follow (less than 100), which are separated by blank lines,
and each of which has the form:
n
a_1 a_2 ...a_n
b

Output
Output the answers, in order, on separate lines.

Example
Input:
5

2
2 3
3

3
1 1000 3142
2

1
8
1

3
12 15 2
18

4
10 10 10 34

1
42

Output:
2
1
0
0
4

Added by: Paul Draper


Date: 2009-05-07
Time limit: 2s
Source limit:50000B
Languages: All

2
SPOJ Problem Set ()

4375. Bicoloring II
Problem code: BICOII
In 1976 the "Four Color Map Theorem" was proven with the assistance of a computer. This theorem
states that every map can be colored using only four colors, in such a way that no region is colored
using the same color as a neighbor region. Here you are asked to solve a simpler similar problem. You
have to decide whether a given arbitrary connected graph can be bicolored. That is, if one can assign
colors (from a palette of two) to the nodes in such a way that no two adjacent nodes have the same
color. You can assume:

No node will have an edge to itself.


The graph is non-directed. That is, if a node a is said to be connected to a node b, then you must
assume that b is connected to a.

Input
The input consists of several test cases. Each test case starts with a line containing the number n (1 < n
< 200) of different nodes. The second line contains the number of edges l. After this, l lines will
follow, each containing two numbers that specify an edge between the two nodes that they represent.
A node in the graph will be labeled using a number a (0 <= a <= n). An input with n = 0 will mark the
end of the input and is not to be processed.

Output
You have to decide whether the input graph can be bicolored or not, and print it as shown below.

Example
Input:
3
3
0 1
1 2
2 0
9
8
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0

Output:
NOT BICOLORABLE.
BICOLORABLE.

1
Added by: Daniel Gómez Didier
Date: 2009-05-14
Time limit: 2s
Source limit:50000B
Languages: All
Resource: ACM javeriana - acm.javeriana.edu.co

2
SPOJ Problem Set (tutorial)

4474. Longest Palindromic Substring


Problem code: LPS
A palindrome is a string that is the same as its reverse. Example "malayalam", "dad", "appa" etc. In
this problem you are asked to find the length of the longest contiguous substring of a given string,
which is a palindrome.

Input

The first line consists of a single integer N, the no. of characters in the string. 1 <= N <= 100000.

Second line is a string with N characters, where the characters are always lowercase english alphabets,
ie ’a’ to ’z’. 

Output

A single line with an integer representing the length of longest palindromic substring.

Example

Input:5ababa 

Output:5

Added by: Srivatsan B


Date: 2009-06-04
Time limit: 1s-5s
Source limit:50000B
Languages: All
Resource: http://opc.iarcs.org.in/problems/iarcs-feb05-ad-1

1
SPOJ Problem Set (classical)

4492. Magic1
Problem code: MAGIC1
A Magic Square is an N by N matrix such that the sum of all the elements in each row, each column
and the two diagonals is the same. Also, all the elements of a Magic Square are different and are in the
range from 1 to N^2.

Your are given a matrix with some element missing. Your task is to complete the matrix so that it is a
Magic Square (if it is possible).

Input
The first line of the standard input will contain one integer N, (1 <= N <= 5). Each of the next N lines
will contain N integers representing the elements in the matrix. The number 0 represents an empty
element.

Output
If it is possible to complete the matrix so that it is a Magic Square, then output the matrix to the
standard output - in N lines output N integers separated by a single space that represent the matrix. If it
is impossible to fill out the empty elements so that the marix is a Magic Square, then output -1 to the
standard output.

Example
Input:

2
10
23
Output:-1

Added by: Tomas. Bob


Date: 2009-06-12
Time limit: 0.400s-1s
Source limit:50000B
Languages: All
Resource: www.z-trening.com

1
SPOJ Problem Set (classical)

4493. Equation
Problem code: EQUAD1
You are given an equation, which when you solve, you get a huge prize.

The equation consists out of integers between 1 and 1000, signs +, - (plus and minus) and parenthesis (
and ), and finally one ? which represents the unknown variable. The question mark can be on either
side of the equation.

Input
From the first line of the standard input read the equation, the equation will contain at most 1000000
characters.

Output
You shoud write the wanted number.

Example
Input:5 + ? = 32 - 2Output:

25

Added by: Tomas. Bob


Date: 2009-06-12
Time limit: 0.009s
Source limit:50000B
Languages: All
Resource: www.z-trening.com

1
SPOJ Problem Set (tutorial)

4500. Helms Deep


Problem code: LOTR1
We have all heard about good triumphing over evil. A perfect example would be the Battle of Helms
Deep.

Lets probe a little deeper...

The people (especially warriors) of Rohan (good side) could not have known that they would win the
battle before it was actually fought. This would have forced them to think up of some other alternate
means of escape. A river flows near the fortress and naturally, they think this to be the best escape
route. They build the biggest ship possible with the available materials.

This ship can carry a total weight of W(0<W<10^9) kilograms. There are a total of n (0<n<10000)
people at Helms Deep having weights wi (0<wi<10^9).

What is the maximum number of people who can escape?

Input
1st line contains t, the number of testcases. First line of each test case contains the number of people
n(0<n<10000) and the capacity of the ship W(0<W<10^9). The next n lines each contain the weights
wi(0<wi<10^9) of the i th person. All numbers in the input file are integers.

Output
One line giving the maximum number of people who can escape.

Example
Input:13 3213Output:2

Added by: pradeep


Date: 2009-06-15
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Lord of the Rings (2 towers)

1
SPOJ Problem Set (tutorial)

4522. Adding Base36 BigNumbers


Problem code: UCI2009A
Ivan Ivanovich, the evil problemsetter, got tired of you and your team always using Java’s BigInteger
class. In an attempt to get back at you, he created this problem. You are to write a program which
calculates the sum of pairs of integers. Simple, isn’t it?

Not so fast, coder. You will be dealing with base36 integers. Haven’t you heard of them? It’s easy.

Digits from ’0’ to ’9’ represent the values 0 to 9.


Digits from ’A’ to ’Z’ represent the values 10 to 35.

So ACMICPC 36 is 22531225296 10 and UCI2009 36 is 66059390601 10 .

Input
Input starts with an integer T, representing the number of test cases (1<=T<=100). For each test case
you will be given two base36 positive integers X1 and X2, whose lengths won’t exceed 1000 digits.

Output
Print T sums, no leading zeroes, one line each.

Example
Input:2ACMICPCUCI2009ACMICPCUCI2009Output:14P4KCPL14P4KCPL

Added by: yandry pérez clemente


Date: 2009-06-23
Time limit: 3s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (classical)

4543. Mysterio s Menace


Problem code: SPIDEY1
 

The nefarious Mysterio an expertise in illusions has a mind-warping hold on the City of New York,
and it’s up to Spidey to stop him before he takes over the entire city! Mysterio uses tiny cubes to create
holograms which makes up his illusions. Mysterio has disguised the whole New York City into his
own dream world. Mysterio now has created this illusive world with hologram cubes on a linear arena.
To break this illusion Spiderman has to pick up as many cubes as he can from the arena. But wait thats
not so easy!! Mysterio has disguised the arena too!!
The arena consists of rectangular rocks (of zero width) whose starting and ending x-coordinates are
given.(The y-coordinates of the rocks is immaterial). For example consider the configuration of the
rocks as follows: 2-4 ,3-8 ,4-8 ,8-9 ,9-10 here the first rock spans between x coordinate 2 to 4 and so
on. Now if Spidey steps on a rock all other rocks which have overlapping segments with it disappear
ie.,if he steps on rock 1  then rock 2 disappears as there is an overlapping segment namely the segment
3-4 but when he steps on rock 8-9 no other rock disappears as this rock has no overlapping segment
with any other rock.Assume that Spidey can jump from any rock to any other rock and if he lands on a
rock he destroys the hologram cube present on the rock. Poor Peter Parker is out of mind in this
menace! Help him find the maximum number of cubes he can destroy.
Input Format
The first line of the input consists of a single integer T(1<=T<=100) specifying the number of test
cases to follow .The first line of each test case is a single integer N(2<=N<=100000) the number of
rocks in the arena. The next N lines of each test case consist of two space separated integers X1 X2
specifying the starting X-coordinate and the ending X-coordinate of rocks. The i+1 th line of each test
case specifies the configuration of the i th rock.
0 <= X1 ,X2 <= 1000000000
Output Format
For each test case output a single integer M the maximum number of cubes that Spiderman can
destroy.
SAMPLE INPUT:
2
5
24
38
48
89
9 10 
7
26 29
23 27
25 28
30 32
32 37
27 31

1
31 35
SAMPLE OUTPUT:
4
3 The nefarious Mysterio an expertise in illusions has a mind-warping hold on the City of New York,
and it’s up to Spidey to stop him before he takes over the entire city! Mysterio uses tiny cubes to create
holograms which makes up his illusions. Mysterio has disguised the whole New York City into his
own dream world. Mysterio now has created this illusive world with hologram cubes on a linear arena.
To break this illusion Spiderman has to pick up as many cubes as he can from the arena. But wait thats
not so easy!! Mysterio has disguised the arena too!!

The nefarious Mysterio an expertise in illusions has a mind-warping hold on the City of New York,
and it’s up to Spidey to stop him before he takes over the entire city! Mysterio uses tiny cubes to create
holograms which makes up his illusions. Mysterio has disguised the whole New York City into his
own dream world. Mysterio now has created this illusive world with hologram cubes on a linear arena.
To break this illusion Spiderman has to destroy as many cubes as he can from the arena. But wait thats
not so easy!! Mysterio has disguised the arena too!!

The arena consists of rectangular rocks (of zero width) whose starting and ending x-coordinates are
given.(The y-coordinates of the rocks is immaterial). For example consider the configuration of the
rocks as follows: 2-4 ,3-8 ,4-8 ,8-9 ,9-10 here the first rock spans between x coordinate 2 to 4 and so
on. Now if Spidey steps on a rock all other rocks which have overlapping segments with it disappear
ie.,if he steps on rock 1  then rock 2 disappears as there is an overlapping segment namely the segment
3-4 but when he steps on rock 8-9 no other rock disappears as this rock has no overlapping segment
with any other rock.Assume that Spidey can jump from any rock to any other rock and if he lands on a
rock he destroys the hologram cube present on the rock. Poor Peter Parker is out of mind in this
menace! Help him find the maximum number of cubes he can destroy.

Input Format

The first line of the input consists of a single integer T(1<=T<=100) specifying the number of test
cases to follow .The first line of each test case is a single integer N(2<=N<=100000) the number of
rocks in the arena. The next N lines of each test case consist of two space separated integers X1 X2
specifying the starting X-coordinate and the ending X-coordinate of rocks. The i+1 th line of each test
case specifies the configuration of the i th rock.

0 <= X1 ,X2 <= 1000000000

Output Format

For each test case output a single integer M the maximum number of cubes that Spiderman can
destroy.

SAMPLE INPUT:

2
2
5
24
38
48
89
9 10
7
26 29
23 27
25 28
30 32
32 37
27 31
31 35

SAMPLE OUTPUT:

4
3

Added by: Rajeev Kumar.J


Date: 2009-07-01
Time limit: 3s
Source limit:50000B
Languages: All

3
SPOJ Problem Set (classical)

4554. Relax! It is just a game


Problem code: ANARC08E
You: What’s the score? Did I miss much?
Me: It’s 2-1 for elAhli and the second half just started. The first half was quite boring.
You: Who scored first? elAhli or ezZamalek?
Me: What difference does it make?
You: Big difference! I can predict the outcome of the match if I knew the order of which goals were
scored in the first half.
Me: What do you mean?
You: It’s 2-1 for elAhli, right? One of three things could have happened: elAhli scored two goals then
ezZamalek scored; Or, elAhli scored its first goal, then ezZamalek, then elAhli again; Or, ezZamalek
scored first, then elAhli scored its two goals.
Me: So?!! I still don’t understand what difference does that make? It’s still 2-1 for elAhli! Why don’t
you just relax and let us continue watching the game in peace.
You: You don’t understand!! I believe the probability of who’ll win depends on the order of how goals
were scored. Now I have to predict the outcome for 3 possibilities.
Me: And what if the score was 3-2? What would you have done then?
You: I would have to work for 5 different possibilities. No?
Me: Of course not! The number of possibilities isn’t always equal to the sum.
You: Can you tell me when will it be equal to the sum?
Me: You’re a programmer, why don’t you write a program that counts the number of possibilities and
compare it to the sum?
You: I don’t have the time, I want to watch the match. Besides, I have nine other problems to worry
about.
Me: I’ll give you a hint. The possibilities will be equal to the sum only if one of the teams scored a
certain number of goals.

Input
Your program will be tested on one or more test cases. Each test case specifies two natural numbers (A
and B ) (separated by one or more spaces) representing the score of the first half. No team will be able
to score more than 10 goals. The last line of the input file contains two -1’s (which is not part of the
test cases.)

Output
Format For each test case where the number of possibilities is equal to the sum, print:
A+B=C
Where A and B are as above and C is their sum. If the number of possibilities is not equal to the sum,
replace the ’=’ sign with ’!=’ (without the quotes.)

1
Example
Input:
2 1
1 0
-1 -1

Output:
2+1=3
1+0=1

Added by: Ahmed Aly


Date: 2009-07-04
Time limit: 1s
Source limit:50000B
Languages: All
Resource: ANARC 2008

2
SPOJ Problem Set (acm)

4566. Đe^’m hinh chu+~ nhât


Problem code: LQDRECT
Cho môt ba?ng kích thu+o+’c MxN, đu+o+.c chia thanh lu+o+’i ô vuông đo+n vi. M dong N côt.
(1<=M<=1000;1<=N<=300)
Tren các ô cu?a ba?ng ghi sô 0 hoăc 1. Các dong cu?a ba?ng đu+o+.c đánh sô 1, 2... M theo thu+’ tu+.
tu+‘ tren xuông du+o+’i va các côt cu?a ba?ng đu+o+.c đánh sô 1, 2..., N theo thu+’ tu+. tu+‘ trái qua
pha?i 
Yeu câu: 
Đe^’m sô hinh chu+~ nhât gôm các ô cu?a ba?ng thoa? man các đie^‘u kie^.n sau: 
1 - Hinh chu+~ nhât đó có 4 ô o+? 4 đi?nh la 4 ô khác nhau
2- 4 ô o+? đi?nh đe^‘u la sô 1
3- Ca.nh hinh chu+~ nhât song song vo+’i ca.nh ba?ng 

Input
Dong 1: Ghi hai sô M, N 
M dong tie^’p theo, dong thu+’ i ghi N sô ma sô thu+’ j la sô ghi tren ô (i, j) cu?a ba?ng

Output
Gôm 1 dong duy nhât ghi sô hinh chu+~ nhât tho?a man yeu câu .
Example
Input:4 41 0 0 10 1 1 11 1 1 11 1 1 1Output:14Ke^’t qua? trong pha.m vi int64 cu?a pascal va long long cu?a C,C++

Added by: Ruan Shee Zhong


Date: 2009-07-05
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

4762. Desde Hasta


Problem code: DESDEHAS
Mo and Larry have devised a way of encrypting messages. They first decide secretly on the number of
columns and write the message (letters only) down the columns, padding with extra random letters so
as to make a rectangular array of letters. For example, if the message is "There’s no place like home on
a snowy night" and there are five columns, Mo would write down
t o i o yh p k n ne l e a ir a h s ge c o n hs e m o tn l e w x

Note that Mo includes only letters and writes them all in lower case. In this example, Mo used the
character ‘x’ to pad the message out to make a rectangle, although he could have used any letter. Mo
then sends the message to Larry by writing the letters in each row, alternating left-to-right and
right-to-left. So, the above would be encrypted as
toioynnkpheleaigshareconhtomesnlewx

Your job is to recover for Larry the original message (along with any extra padding letters) from the
encrypted one.

Input
There will be multiple input sets. Input for each set will consist of two lines. The first line will contain
an integer in the range 2...20 indicating the number of columns used. The next line is a string of up to
200 lower case letters. The last input set is followed by a line containing a single 0, indicating end of
input.

Output
Each input set should generate one line of output, giving the original plaintext message, with no
spaces.

Example
Input:5toioynnkpheleaigshareconhtomesnlewx3ttyohhieneesiaabss0

Output:

theresnoplacelikehomeonasnowynightxthisistheeasyoneab

1
Added by: Coach UTN FRSF
Date: 2009-09-02
Time limit: 1s-2s
Source limit:50000B
Languages: All
Resource: Original version TO and Fro here in spoj

2
SPOJ Problem Set (tutorial)

4765. The 3n plus 1 problem V2


Problem code: PROBTRES
Background:
Problems in Computer Science are often classified as belonging to a certain class of problems (e.g.,
NP, Unsolvable, Recursive). In this problem you will be analyzing a property of an algorithm whose
classification is not known for all possible inputs.

The Problem:
Consider the following algorithm:1. input n2. print n3. if n = 1 then STOP 4. if n is odd then n = 3n + 1 5. else n = n / 26. GOTO 2

Given the input 22, the following sequence of numbers will be printed 22 11 34 17 52 26 13 40 20 10
5 16 8 4 2 1

It is conjectured that the algorithm above will terminate (when a 1 is printed) for any integral input
value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been
verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers
than this.)

Given an input n, it is possible to determine the number of numbers printed (including the 1). For a
given n this is called the cycle-length of n. In the example above, the cycle length of 22 is 16.

For any two numbers i and j you are to determine the maximum cycle length over all numbers between
i and j.

The Input:
The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers
will be less than 1,000,000 and greater than 0.

You should process all pairs of integers and for each pair determine the maximum cycle length over all
integers between and including i and j.

You can assume that no operation overflows a 32-bit integer.

The Output:
For each pair of input integers i and j you should output i, j, and the maximum cycle length for integers
between and including i and j. These three numbers should be separated by at least one space with all
three numbers on one line and with one line of output for each line of input. The integers i and j must
appear in the output in the same order in which they appeared in the input and should be followed by
the maximum cycle length (on the same line).
Sample Input:1 10100 200201 210900 1000Sample Output:1 10 20100 200 125201 210 89900 1000 174

1
Added by: Coach UTN FRSF
Date: 2009-09-02
Time limit: 1s-10s
Source limit:50000B
Languages: All except: ERL JS PERL 6

2
SPOJ Problem Set (tutorial)

4768. Cool Numbers


Problem code: COOLNUM
Eric likes interesting numbers like 64. It turns out that 64 is both a square and a cube, since 64 = 8^2
and 64 = 4^3 . Eric calls these numbers cool.

Write a program that helps Eric figure out how many integers in a given range are cool.

Input
On the first line of input, you are given an integer a such that a >= 1 and a <= 10^8 . On the second
line of input, you are given an integer b such that a <= b and b <= 10^8 .

Output
The output should be the number of cool numbers in the range a to b (inclusively: that is, a and b
would count as cool numbers in the range if they were actually cool).

Example
Input:
1
100

Output:
2

Input:
100
1000

Output:
1

Added by: Mislav Balunović


Date: 2009-09-02
Time limit: 0.100s
Source limit:50000B
Languages: All
Resource: Canadian Computing Competition

1
(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 (tutorial)

4770. Add and Reverse Sums


Problem code: ADDREVUT
The Problem

The "reverse and add" method is simple: choose a number, reverse its digits and add it to the original.
If the sum is not a palindrome (which means, it is not the same number from left to right and right to
left), repeat this procedure.

For example:
195 Initial number
591
-----
786
687
-----
1473
3741
-----
5214
4125
-----
9339 Resulting palindrome

In this particular case the palindrome 9339 appeared after the 4th addition. This method leads to
palindromes in a few step for almost all of the integers. But there are interesting exceptions. 196 is the
first number for which no palindrome has been found. It is not proven though, that there is no such a
palindrome.

Task :
You must write a program that give the resulting palindrome and the number of iterations (additions)
to compute the palindrome.

You might assume that all tests data on this problem:


- will have an answer ,
- will be computable with less than 1000 iterations (additions),
- will yield a palindrome that is not greater than 4,294,967,295.

1
The Input
The first line will have a number N with the number of test cases, the next N lines will have a number
P to compute its palindrome.

The Output
For each of the N tests you will have to write a line with the following data : minimum number of
iterations (additions) to get to the palindrome and the resulting palindrome itself separated by one
space.

Sample Input
3195265750

Sample Output
4 9339
5 45254
3 6666

Added by: Coach UTN FRSF


Date: 2009-09-03
Time limit: 2s-3s
Source limit:50000B
Languages: All except: ERL JS PERL 6
Resource: http://online-judge.uva.es/p/v100/10018.html

2
SPOJ Problem Set (main)

4786. Invertir Cadena


Problem code: PC1
Elabore un programa que dado un vector de letras, lo invierta y lo imprima.

El vector debe de manejarse con memoria dinámica y aritmética de apuntadores y la función realizada
debe de ser recursiva.
Además, el programa debe ir divido por funciones y en comentario la especificación formal de cada
una.

Input
La entrada comienza con un número t indicando los casos de prueba. En cada caso hay un número x,
siendo x el tamano del vector, seguido por x líneas donde en cada una de ellas se encuentra un caracter
del vector.

Output
Para cada caso de prueba imprimir el vector invertido seguido por un salto de línea.

Example
Input:24hola2maOutput:aloham

Added by: Fabio Avellaneda


Date: 2009-09-07
Time limit: 1s
Source limit:50000B
Languages: C++

1
SPOJ Problem Set (main)

4787. Vocales en un vector de letras


Problem code: PC2
Elabore un programa que dado un vector de letras, cuente e imprima el número de vocales que hay en
él.
El vector debe de manejarse con memoria dinámica y aritmética de apuntadores y la función realizada
debe de ser recursiva.
Además, el programa debe ir divido por funciones y en comentario la especificación formal de cada
una.

Input
La entrada comienza con un número t indicando los casos de prueba. En cada caso hay un número x,
siendo x el tamano del vector, seguido por x líneas donde en cada una de ellas se encuentra un caracter
del vector.

Output
Para cada caso de prueba imprimir el número de vocales contenidas en el vector de letras.

Example
Input:24hola2maOutput:21

Added by: Fabio Avellaneda


Date: 2009-09-07
Time limit: 1s
Source limit:50000B
Languages: C++

1
SPOJ Problem Set (tutorial)

4789. De decimal a binario


Problem code: PC4
Elabore una función que convierta un número en base decimal a base binaria. Dicha función deberá ser
recursiva.
El programa debe ir divido por funciones y en comentario la especificación formal de cada una.

Input
La entrada consiste en un número t indicando los casos de prueba. Luego vienen t lineas, cada una con
el número a convertir.

Output
Para cada caso de prueba imprimir el número ingresado en base binaria.

Example
Input:376131Output:
11111010000011

Added by: Fabio Avellaneda


Date: 2009-09-07
Time limit: 1s
Source limit:50000B
Languages: C++

1
SPOJ Problem Set (classical)

4826. JOURNEY
Problem code: TPJOUR
Cho 1 đô thi. có N đi?nh, M ca.nh 2 chie^‘u. 2 đi?nh đu+o+.c nôi vo+’i nhau nhie^‘u nhât la 1 ca.nh.

1 đu+o+‘ng đi la 1 chuôi các đi?nh sao cho các đi?nh ke^‘ nhau có ca.nh nôi vo+’i nhau.

1 đu+o+‘ng đi đe.p pha?i tho?a man :

- Chuôi đi?nh có đô dai la D.

- Các đi?nh tu+‘ 1 đe^’n K pha?i xuât hie^.n ít nhât 1 lân.

Yeu câu : Tính sô đu+o+‘ng đi đe.p mod 1000000009.

Gio+’i ha.n N<=20, D<=1000000000. K<=7.

Input

- 4 sô N,M,K,D

- M dong môi dong 2 sô u,v cho bie^’t có đu+o+‘ng đi 2 chie^‘u ca.nh nôi 2 đi?nh u va v

Output

- Sô đu+o+‘ng đi đe.p mod 1000000009.

Sample input

4423

12

23

31

24

Sample output

10

#Gia?i thích

Các đu+o+‘ng đi có the^? la :

1
- 1_2_1

- 1_2_3

- 1_2_4

- 1_3_2

- 2_1_2

- 2_1_3

- 2_3_1

- 3_1_2

- 3_2_1

- 4_2_1

Added by: dqd


Date: 2009-09-18
Time limit: 1s-5s
Source limit:50000B
Languages: All except: ERL TECS JS
Resource: Su+u tâm

2
SPOJ Problem Set (classical)

4830. Z meet
Problem code: KZWC
The Z-meet is an annual alumni meet of the department of Computer Science at PSG college of
technology,where students of different batches
meet.The batch names are named in a alphabetical order and ending with Z(hence the name
Z-meet).That is Aztecz,Byzandierz,Calitz,Dextroblitz,Espritz,
F5erz and Griffinxeritz.The event is held in a hall and the students are seated in random order.The
event co-ordinators hav a problem.They need to find
the strength of attendence of the event by different batches which is calculated as follows:
1.each person in the hall shouts out a number which is calculated as (year of Z-meet - year of pass-out
)^2 if he is a alumni or
(year of Z-meet - year of entering )^2 if he is still a student.assume the batch of the year in which
Z-meet is not passedout.
2.the numbers shouted by each person in the hall is added to get the strength of attendence.
The year of passing & year of entering of the different batches are given:
Aztecz      2001-2005
Byzandiarz   2002-2006
Calitz      2003-2007
Dextroblitz    2004-2008
Espritz    2005-2009
F5erz      2006-2010
Griffinxeritz    2007-2011
for example if the event is held in 2008 the Aztecz batch member shouts (2008-2005)^2=9
and a Dextroblitz member shouts (2008-2004)^2=16
help the event co-ordinator by writing a program to find strength of attendence.

Input
ther is a single positive integer T on the first line indicating the number of test cases to follow.
then there are T lines each containing a year in which Z-meet is held and a string giving the
seating arrangement of the alumni and students.that is A refers to Aztecz member C refers to Calitz
member
and so on.

Output
For every string,output a single line containing the strength of attendence of the event.

1
Example
Input:32008 ADECBA2006 BABACAD2009 BEGFADEGOutput:484875

Added by: balaji


Date: 2009-09-19
Time limit: 4s
Source limit:50000B
Languages: All except: TCL SCALA
Resource: kruzade 09 practice

2
SPOJ Problem Set (tutorial)

4832. Pitagoras y Fermat


Problem code: PITYFERM
FERMAT vs. PITAGORAS

Computer generated and assisted proofs and verification occupy a small niche in the realm of
Computer Science. The first proof of the four-color problem was completed with the assistance of a
computer program and current efforts in verification have succeeded in verifying the translation of
high-level code down to the chip level.

This problem deals with computing quantities relating to part of Fermat’s Last Theorem: that there are
no integer solutions of 

Given a positive integer N, you are to write a program that computes two quantities regarding the
solution of

where x, y, and z are constrained to be positive integers less than or equal to N. You are to compute the
number of triples (x,y,z) such that x<y< z, and they are relatively prime, i.e., have no common divisor
larger than 1. You are also to compute the number of values 0 < p < N such that p is not part of any
triple (not just relatively prime triples).

Input
The input consists of a sequence of positive integers, one per line. The first one is the number of test
cases. Each following integer in the input file represents N and will be less than or equal to 1,000,000.

Output
For each integer N in the input file print two integers separated by a space. The first integer is the
number of relatively prime triples (such that each component of the triple is <= N). The second
number is the number of positive integers <= N that are not part of any triple whose components are
all <=N . There should be one output line for each input line.

1
Example Input
31025100

Example Output:
1 44 916 27

Added by: Coach UTN FRSF


Date: 2009-09-19
Time limit: 2s-5s
Source limit:50000B
Languages: All except: SCALA
Resource: uva

2
SPOJ Problem Set (classical)

4834. Happy Sequence


Problem code: KZHAPPY
The Kruzade OPC team felt we should have a happy ending to the Kruzade online coding event.We
define the happy sequence as follows:
let the sum of the squares of the digits of a positive integer s0 be represented by s1. In a similar way,
let the sum of the squares of the digits of s1 be
represented by s2, and so on.If si=1 for some i>=1, then the original integer s0 is said to be happy. For
example, starting with 7 gives the sequence 7, 49,
 97, 130, 10, 1, so 7 is a happy number. The first few happy numbers are 1, 7, 10, 13, 19, 23, 28, 31,
32, 44, 49...
You have been hired to find out the nth happy number in the sequence.

Input
First line contains an integer T, representing the number of test-cases. Then T lines
follow each containing one integer n, 1 <= n <= 500.

Output
For each test case output on a line the nth happy number in the sequence.

Example
Input:

310520Output:
4419100

Added by: balaji


Date: 2009-09-19
Time limit: 4s
Source limit:50000B
Languages: All except: TCL SCALA
Resource: kruzade 09 practice

1
SPOJ Problem Set (classical)

4835. Weightlift challenge


Problem code: KZGREEDY
In a weightlifting challenge between Mr.SixPack and Mr.EightPack,the weights are arranged on a bar
in random order. On each weight, is
written a positive integer denoting the weight in kg. Players take turns removing a weight from either
end of the bar and placing the weight in his
bar(Mr.SixPack starts the game). The player whose bar add up to the highest weight wins the
challenge(assuming he is strong enough to lift it). Now
one strategy is to simply pick the weight at the end that is the largest -- we’ll call this the greedy
strategy.However, this is not always optimal,
as the following example shows: (Mr.SixPack would win if he would first pick the 3kg instead of the
4kg).
3 2 10 4
You are to determine exactly how bad the greedy strategy is for different challenges when
Mr.EightPack uses it but Mr.SixPack is free to use any
strategy he wishes.

Input
There will be multiple test cases. Each test case will be contained on one line. Each line will start with
an even integer n followed by n positive integers
denoting the weights arranged on the bar.A value of n = 0 indicates end of input. You may assume that
n is no more than 100. Furthermore, you may
assume that the sum of the weights in the list does not exceed 10,000.

Output
For each test case you should print one line of output of the form:
In challenge m, the greedy strategy might lose by as many as p kilograms.
where m is the number of the challenge (starting at challenge 1) and p is the maximum possible
difference between weight of Mr.SixPack’s bar and
weight of Mr.EightPack’s bar when Mr.EightPack uses the greedy strategy. When employing the
greedy strategy, always take the larger end.
If there is a tie, remove the left end.

Example
Input:4 3 2 10 48 1 2 3 4 5 6 7 88 2 2 1 5 3 8 7 30Output:
In challenge 1, the greedy strategy might lose by as many as 7 kilograms.In challenge 2, the greedy strategy might lose by as many as 4 kilograms.In challenge 3, the greedy strategy might lose by as many as 5 kilograms.

1
Added by: balaji
Date: 2009-09-19
Time limit: 1s
Source limit:50000B
Languages: All except: TCL SCALA
Resource: kruzade 09 practice

2
SPOJ Problem Set (main)

4872. Good Sequence


Problem code: KZGD
It is good to hav an auspicious start to any event.The kruzade OPC team felt that online coding event
should
also have an auspicious start.As a mark of auspiciousness, we define good sequence as follows:
A good number is defined as a non-negative number that has an odd number of 1s in its binary
expansion(that is when the decimal number is converted to base 2).
for eg.
1=1  num of 1s in binary equiv=1(odd) so,1 is a good number
2=10 num of 1s in binary equiv=1(odd) so,2 is a good number
3=11 num of 1s in binary equiv=2(even) so,3 is not a good number

The good sequence is the collection of good numbers.


The good sequence goes like this:
1,2,4,7,8,11,13,14,16,19...

You have been hired to find out the nth good number in the sequence.

Input
First line contains an integer T, representing the number of test-cases. Then T lines
follow each containing one integer n, 1 <= n <= 500.

Output
For each test case output on a line the nth good number in the sequence.

Example
Input:
310520

Output:
19838

Added by: balaji


Date: 2009-09-28
Time limit: 4s
Source limit:50000B
Languages: All
Resource: kruzade 09 main

1
SPOJ Problem Set (main)

4873. ABC Blocks


Problem code: KZBLK
ABC college of technology has a number of blocks which houses a number of academic departments
and other facilities.
The following are some of the blocks and the facilities there.

1  a block-admin
2  b block-book depot
3  d block-conf hall
4  f block-canteen
5  i block-industry
6  m block-applied science block
7  n block-management
8  o block-hostel
9  j block-mech block
10 t block-textile block
11 eb bock-computer science block

Each block is denote by a number.Some of these blocks are linked to each other through bridges,to
navigate easier.
You are to guide a student from a block to the destination through all possible paths.

Input
The first line consists of a single integer which is the destination.
The following lines each consist of a pair of positive
integers separated by a space and terminated by a new-line. They represent the blocks connected by a
bridge.
For example, if 1 2 appears on a line, then there is a bridge between block a and b. The final line
consists of a pair of
0’s.

Output
Your output must consist of a line for each valid route from the a block to the destination.The blocks
must
appear separated by a space, terminated by a new-line. Include only routes which do not pass through
any
blocks more than once.

1
Example
Input:
51 22 31 44 52 53 40 0
Output:
1 2 3 4 51 2 51 4 3 2 51 4 5

Added by: balaji


Date: 2009-09-28
Time limit: 4s
Source limit:50000B
Languages: All
Resource: kruzade 09 mains

2
SPOJ Problem Set (classical)

4874. KZGAME
Problem code: KZGM
Esoteric Inc. is a social gaming company that needs to
create an aplication to be run on a social networking
site.The game resembles Scramble,a popular word game
to enrich your vocabulary.The game comes with a set of
words,each word written on a piece of plastic.
Users challenge each other by picking two letters
(let’s call them C1 and C2 ) and then trying to connect
these letters by finding a sequence of one or more words
(we’ll refer to them as W1, W2,..., Wn ) where the first
word W1 starts with C1 and the last word Wn ends with C2 .
Each two consecutive words in the sequence ( Wi,Wi+1 )
 must overlap with at least two letters. Word X overlaps
by k letters with word Y if the last k letters of X
are the same as the first k letters of Y .

scramble

Take for example


 the figure, where ‘a’ was connected to ‘s’
using the two-word sequence ‘‘against" and ‘‘students".

You have been hired to write a program that takes a


dictionary of words and determines the winning
sequence connecting two given letters.

Input
The first line of input consists of an integer n followed by n lines
each containing a word for the dictionary.The next two lines should
accept the start letter and the end letter of the word sequence.

Output
Output should contain a series of words which form a sequence starting
and ending with the letters given in the input.There can be more than
one sequence.If output contains many sequences,the sequences
should be printed in lexicographic order.

1
Example
Input:
5skykyteskypepenentersr
Output:
skype pen enter

Added by: balaji


Date: 2009-09-28
Time limit: 1s
Source limit:50000B
Languages: All except: SCALA
Resource: kruzade 09 mains

2
SPOJ Problem Set (main)

4875. Scramble game


Problem code: KZGME
Esoteric Inc. is a social gaming company that needs to create an aplication to be run on a social
networking
site.The game resembles Scramble,a popular word game to enrich your vocabulary.The game comes
with a set of
words,each word written on a piece of plastic. Users challenge each other by picking two letters
(let’s call them C1 and C2 ) and then trying to connect these letters by finding a sequence of one or
more words
(we’ll refer to them as W1, W2,..., Wn ) where the first word W1 starts with C1 and the last word Wn
ends with C2 .
Each two consecutive words in the sequence ( Wi,Wi+1 ) must overlap with at least two letters. Word
X overlaps
by k letters with word Y if the last k letters of X are the same as the first k letters of Y . Take for
example
 the figure, where ‘a’ was connected to ‘s’ using the two-word sequence ‘‘against" and ‘‘students".

Scramble

You have been hired to write a program that takes a dictionary of words and determines the winning
sequence connecting two given letters.

Input
The first line of input consists of an integer n followed by n lines each containing a word for the
dictionary.The next two lines should accept the start letter and the end letter of the word sequence.

Output

Output should contain a series of words which form a sequence starting and ending with the letters
given in the input.There can be more than one sequence.If output contains many sequences,the
sequences
should be printed in lexicographic order.

Example
Input:

5skykyteskypepenentersr
Output:
skype pen enter

1
Added by: balaji
Date: 2009-09-28
Time limit: 4s
Source limit:50000B
Languages: All
Resource: Kruzade 09

2
SPOJ Problem Set (classical)

4876. Save City


Problem code: KZCITY
In 1095 A.D, the crusade war broke.At 1156 the christians were at their peak made the jews to run to
safe guard thier lives.
Their way of attack was different,they turned the cities into ashes.Think you are in the country
"almoravids" where the lands weren’t
too high from sea level,and also each city is like a square ,sliced into smaller identical squares by a
regular grid of roads.
Every square contains one of three kind of terrain buliding,grassland or industry.You are a fireman and
you are asked to safe-guard
the city from fire.You are provided only with explosives to extinguish the fire.
cruzade

If a city is blown which is either under fire or not,


a crater is formed and water from nearby sea enters in 2 minutes.The fire spreads only to horizontal or
vertical city adjacent to it
in 2 minutes.When fire boke out you can hardly waste 2 seconds with your glider in the sky.If you
drop a dynamite,
you can move to any city in random by 2 minutes.The loss by fire and dynamite are same they leave
the city without any resources left.
Safe guard as many cities as possible.

Input:

the first line of input contains the the no.of cities along a row and no.of cities along a coloumn.The
next line of input contains the row and coloumn of the city under fire(matrix representation).

Output

Output contains the cities atmost safeguarded.the next line contains the present situation of the
land.a->turned into ashes,s->land is safe ,f->flooded by water.

Example
Input:

5 4 3
Output:
1s f f a a f a a a aa a a a a a a a a a a a a a a

1
Added by: balaji
Date: 2009-09-28
Time limit: 5s
Source limit:50000B
Languages: All except: SCALA
Resource: Kruzade 09 main

2
SPOJ Problem Set (tutorial)

4892. De minúsculas a mayúsculas


Problem code: VOCMINMA
Elabore un programa que dada una cadena de caracteres reemplace todas las vocales que se encuentren
en minúscula por la misma vocal pero en mayúsculas.

Bono:  La función realizada es manejada recursivamente.

Input
La entrada comienza con un número t indicando los casos de prueba. En cada caso hay una cadena de
caracteres con 1<= n <=500000, siendo n la cantidad de caracteres. Dentro de esa cadena pueden haber
espacios, signos de puntuación, entre otros.

Output
Para cada caso de prueba imprimir la nueva cadena que contiene todas sus vocales en mayúscula.

Example
Input:3Me dan mIEdo lOs murciElagosprogramaciOn de cOmPutadOResCamiLa! cuiDado en la pLAya!Output:ME dAn mIEdO lOs mUrcIElAgOsprOgrAmAcIOn dE cOmPUtAdOREsCAmILA! cUIDAdO En lA pLAyA!

Added by: Fabio Avellaneda


Date: 2009-10-01
Time limit: 1s
Source limit:50000B
Languages: C++

1
SPOJ Problem Set (tutorial)

4893. Traductor Simple


Problem code: SIMTRANS
Un traductor consta de una cadena que contiene una palabra en un idioma y seguida a ésta, la
traducción de esa palabra a otro idioma. Si se tienen varias palabras en el traductor, su almacenamiento
sería:

Hola Hi name nombre age edad

Elabore un programa que traduzca cadenas de un idioma a otro.

 La calificación de este punto dependerá de cuantos casos de prueba sea capaz de resolver
correctamente.

Input
La entrada consta de una cadena con tamano n (1<= n <= 500000) que contiene las palabras en los dos
idiomas separadas por un espacio.

Seguida a esta cadena se presenta la cantidad c de cadenas a traducir, por lo que las siguientes c líneas
serán cadenas de caracteres, todas en un mismo idioma.

Output
Para cada cadena se debe imprimir su respectiva traducción.

Example
Input:it ello Was era at en dark oscuro looked miraron they Ellos2it Was darkthey looked at itOutput:
Ello era oscuroEllos miraron en Ello

Added by: Fabio Avellaneda


Date: 2009-10-01
Time limit: 2s
Source limit:50000B
Languages: C++ LISP clisp

1
SPOJ Problem Set (classical)

4895. N-D Intervals


Problem code: NDINTERV
In this problem you will be given a list of N (0<N<3200) intervals, followed by a second list of Q
(0<Q<510000) query intervals.  Your job is to simply return the number of query intervals which
intersect one or more of the N given intervals.   However, the intervals in this problem can have
dimension D (0<D<5).  A d-dimensional interval can be represented as [ (a1, a2, ..., ad), (b1, b2, ..,
bd) ].  A point (v1, v2, .. vd) is considered to be part of this interval if and only if min(ai, bi) <= vi <=
max(ai, bi) for all i in [1, d].  Two intervals intersect if and only if they share at least one point. All
interval coordinates are between 0 and 50.

Input
A number of inputs (<5), each starting with D, N and Q, followed by 2*N lines with D numbers on
each line. Each pair of lines represent one interval.  This is then followed by 2*Q lines with D
numbers on each line, with each pair representing a query interval

Output
For each set of inputs, return the number of query intervals which intersect at least one given interval.

Example
Input:4 2 31 1 1 15 5 5 52 2 2 26 6 6 67 7 7 78 8 8 89 9 9 910 10 10 101 2 3 44 2 2 1Output:1

Added by: Chen Xiaohong


Date: 2009-10-02
Time limit: 7s
Source limit:50000B
Languages: All except: SCALA
Resource: original

1
SPOJ Problem Set (tutorial)

4897. Meowist Networking


Problem code: MEOWIST
Kat Mandu has been living in seclusion for several years, practicing martial arts and meditating. As a
consequence, he missed the take-off of social networking. He was therefore surprised upon his return
to society that countless many are standing with signs at every street corner, eager to be followed on
Twitter; his grandmother runs one of the world’s top blogs; and chances are, even your mom has
Facebook.

Reluctantly, he joined the craze, but he quickly discovered that many of these services are lacking in
their friend sorting facilities: they will usually only allow listing friends in alphabetical order by name.
Kat Mandu would prefer sorting his friends by age, with the oldest at the top of the list. If two friends
have the same age, only then sort alphabetically. Help Kat Mandu by writing a program which
implements this functionality.

Input
Each line of input will contain a name and an age, separated by a space. Names will be unique and
consist of at most 10 uppercase letters. Ages will be between 1 and 100 inclusive.

Output
Print out the same names that were given in the input, but sorted according to Kat Mandu’s
requirements.

Example
Input:
DUCHESS 26
MARIE 8
BERLIOZ 8
TOULOUSE 7
THOMAS 28

Output:
THOMAS
DUCHESS
BERLIOZ
MARIE
TOULOUSE

1
Added by: Miorel Palii
Date: 2009-10-02
Time limit: 2s
Source limit:4096B
Languages: All except: ERL TECS
Resource: University of Florida Local Contest - September 27, 2009

2
SPOJ Problem Set (tutorial)

4906. Pythagorean Triples


Problem code: PYTHTRIP
A Pythagorean triple (A, B, C) is defined as three positive integers that satisfy the Pythagorean
Theorem: A 2 + B 2 = C 2 . Given two positive integers A and B, your task is to verify whether they are
the "legs" in a Pythagorean triple, i.e. if an integer C exists such that (A, B, C) is a Pythagorean triple.

Input
The first line will contain a single integer N (0 < N <= 10000). Each of the next N lines will contain
two integers A and B (0 < A, B <= 100).

Output
For each test case, output a single line. If a valid C exists, output a line containing the word YES and
the value of C, separated by a space. Otherwise, output the single word NO.

Example
Input:42 24 34 55 12Output:NOYES 5NOYES 13

Added by: Miorel Palii


Date: 2009-10-04
Time limit: 2s
Source limit:4096B
Languages: All except: ERL
Resource: University of Florida Local Contest - April 13, 2009

1
SPOJ Problem Set (tutorial)

4907. Most Common Letter


Problem code: MCL
Many word processors have a word count feature, which can tell you not only how many words are in
a file, but also how many characters, lines, paragraphs, and pages. But who cares about that? All you
really need to know is which of the 26 letters of the English alphabet (A - Z) you’ve used the most in
your text. Write a program which implements this feature.

Input
The input will be several lines, each representing a different test case. No test case will exceed 1024
characters in length, and each will contain at least one alphabetic character.

Output
For each test case, output one line, containing the most common letter and the number of times it
appears in the test case, separated by a space. Break ties in favor of the letter that occurs first
alphabetically. Ignore non-alphabetic characters. Counting should be case-insensitive, and output
should be uppercase.

Example
Input:
Hello World!
Never gonna give you up, never gonna let you down...
You just lost the game.
I’m going to sleep *yawn* ZZZzzz

Output:
L 3
N 7
T 3
Z 6

Added by: Miorel Palii


Date: 2009-10-04
Time limit: 2s
Source limit:4096B
Languages: All except: SCALA
Resource: University of Florida Local Contest - April 13, 2009

1
SPOJ Problem Set (tutorial)

4997. Test Básico de Listas


Problem code: LISTTEST

Input
Primero leer un número que indica cuantos casos ingresan.
Para cada caso leer la cantidad de datos que ingresan.
Para cada dato, leer el número a ingresar y si se debe insertar o anexar.

Output
Para cada caso se debe imprimir la lista resultante, cada valor separado por un espacio.

Example
Input:231 insertar2 InserTar3 anexar20 INSERTAR0 anexarOutput:2 3 1 0 0

Added by: Fabio Avellaneda


Date: 2009-10-15
Time limit: 3s
Source limit:50000B
Languages: C++

1
SPOJ Problem Set (tutorial)

5009. Alphabet Arithmetic


Problem code: ALPHMATH
In his Introduction to Digital Arts and Sciences class, Dave frequently assigns homework. It usually
consists of tedious exercises involving integer arithmetic. The students respond like true students: by
complaining. So, to make the homeworks more exciting for his students, Dave has decided to disguise
the exercises as alphabet arithmetic! This is exactly the same as integer arithmetic, except that instead
of the usual digits 0 through 9, it uses letters A through J as the digits.

Help Dave generate the key to the homework!

Input
Each test case will be on one line of the form "NUMBER OP NUMBER". Each NUMBER is positive
and less than 100000. OP is one of +, -, *, /. You will not have to divide by zero.

Output
For each test case, output the alphabet arithmetic answer on a single line.

Example
Input:
G * H
D - F
B + B
H / C

Output:
EC
-C
C
D

Added by: Miorel Palii


Date: 2009-10-16
Time limit: 1s
Source limit:4096B
Languages: All except: ERL
Resource: University of Florida Team Practice 2009

1
SPOJ Problem Set (tutorial)

5012. Spanish Conjugation


Problem code: SPANCONJ

Spanish Conjugation
As you want to go to Madrid, maybe now would be the right time to learn some Spanish grammar? Of
course, as a programmer, one way to do so is to write a program that teaches you. In this task, you are
required to write the part of a grammar trainer that checks whether you conjugated a verb correctly.

In Spanish, there are three forms of regular verbs: Those ending in -ar, -er and -ir. The verb forms are
build according to the following table:

  -ar -er -ir


  Singular Plural Singular Plural Singular Plural
First person -o -amos -o -emos -o -imos
Second Person -as -Ais -es -Eis -es -Is
Third Person -a -an -e -en -e -en

As an example, the word comer (to eat) in second person singular would be the stem (com) and the
ending (es): comes, you eat. Note that the pronoun tu (you) is implicit; unlike English, the person can
be derived from the verb alone.

In order to avoid compatibility problems between computers of different character encodings, we


substituted some letters. Throughout this problem, we will write A instead of á, E instead of é and I
instead of í. All other non-ASCII characters have been replaced by their normalized version (e.g.
n -> n).

Input
The input contains of several test cases. Each test case consists of a verb conjugation.

Each conjugation consists of the infinitiv of a verb, a comma, the person (first, second, third person),
the number (singular or plural), a colon and the conjugated verb form. Only regular verbs will occur.

Output
For each test case, print either "correct" or "incorrect, should be ___" (where ___ is replaced with the
correct conjugation).

1
Example
Input:hablar, first person singular: hablobeber, second person plural: bebEiscomer, first person plural: comemasvivir, third person singular: viveOutput:correctcorrectincorrect, should be comemoscorrect

Added by: Jonas Wagner


Date: 2009-10-17
Time limit: 1s
Source limit:50000B
Languages: All except: ERL

2
SPOJ Problem Set (classical)

5105. Hero Adventure


Problem code: HEROADV
There is a game production company that is going to develop a new adventure game. You’re very
interested and join the recruitment phase. You’re being tested to solve this simulation:
For each simulation there will be an R x C map with the following characters:
o ’#’ represents wall, hero can’t move here.
o ’S’ represents starting point of the hero.
o ’F’ represents finish point, the game ends.
o Number ’1’ to ’9’ represents the life point to be reduced if the hero moves here.
o ’E’ represents enemy that the hero need to fight if the hero want to move here.
o ’I’ represents item that will add 100 points to the hero’s life force, become ’0’ after taken (no life
force will be reduce to come back to this point).
The hero has life force (Lf), Experience (Exp), Defend power (Def) and Strength (Str).
The hero will be given extra 1 (one) point for the strength and defend power for each 25 (twenty five)
experience point gained by the hero.
Hero will die if Lf <= 0.
Rules of the fight with enemy:
o Each enemy will have Strength, Life force and Experience.
o The hero and the enemy will be given one chance to attack the other each turn start with the hero,
until either the hero or the enemy die (life force <= 0).
o If the hero attacks the enemy, the enemy’s life force will be decreased by the hero’s strength.
o If the enemy attacks the hero, the hero’s life force will be decreased by the enemy’s strength reduced
by the hero’s defend power.
o The hero will be given the enemy’s experience if the hero defeats the enemy.
o After the enemy defeated, the place will become ’0’ (no life force will be reduce to come back to this
point).
For each simulation, you’re asked to print three paths, Lf and Exp to the finish point that give:
1. The highest Lf.
2. The highest Exp. If there’s more than one highest Exp, choose the highest Lf.
3. The shortest way. If there’s more than one shortest way, choose the highest Lf.
If there is multiple path, choose the lexicographically smallest one.
Input
Input consists of several cases.
Each case begins with four integers in a line: Str (3 <= Str <= 10), Def (0 <= Def <= 5), Exp (0 <=
Exp <= 20) and Lf (10 <= Lf <= 1000).
Denoting the strength, defend, experience and life force of the hero respectively.
The next line contains C (3 <= C <= 20) and R (3 <= R <= 20) denoting the columns and rows of the
map respectively.
The next R lines contain the map as described above.
The next lines contain the description of the enemy, eStr (0 <= eStr <=10), eLf (10 <= eLf <= 100) and
eExp (1 <= eExp <= 25) denoting the enemy’s strength, life force and experience to be gained if it dies
respectively.
Each enemy data corresponds to each ‘e’ which appear first in the map.
Output

1
For each simulation print "Simulation #n" without double quote(") and #n replace by the simulation
number start with 1.
The next three lines each contain path, life force and experience. Use ‘L’ (left), ‘R’ (right), ‘D’
(down), ‘U’ (up) to describe the path that should be taken by the hero.
If it’s not possible to reach the finish point then print "No solution." without double quote (") instead
of the three lines.
Print blank line between simulation.
Sample Input
10 5 20 1000
33
### SEF ###
10 50 15
10 0 0 100
74
#######
S12E#2#
#IE456F
#######
3 10 5
10 100 20
10 0 0 10
33
###
SEF
###
10 50 15
Output for Sample Input
Simulation 1
RR 980 35

RR 980 35

RR 980 35
Simulation 2
RDURRDRRR 181 5

RDRRUDRRR 90 25

RDRRRRR 94 20
Simulation 3
No solution.

Added by: VOJ problem setters


Date: 2009-10-28
Time limit: 5s
Source limit:50000B
Languages: All except: C++ 4.3.2 TECS
Resource: ACM ICPC - Jakarta 2009

2
SPOJ Problem Set (classical)

5132. Hello Kitty


Problem code: HELLOKIT
Kitty sends a kind of original email messages to her friend Garf. To write a message, she
chooses a word W and a number n and replicates W n times horizontally. Then she repeats this
string in the next line, but rotating the characters once to the left. And she repeats this ’rotate-
and-output’ process until the word W appears displayed as the rst column of the rectangular
pattern that she produces.
As an example, when she chooses the word Hello and the number 3, she gets the pattern:

HelloHelloHello
elloHelloHelloH
lloHelloHelloHe
loHelloHelloHel
oHelloHelloHell

Kitty has been sending such emails during the last three years. Recently, Garf told her that
perhaps her work may be automatized with a software to produce Kitty’s patterns. Could you
help her?

Input
The input le contains several test cases, each one of them in a separate line. Each test case
has a word and a positive integer that should generate the corresponding rectangular pattern.
The word is a string of alphabetic characters (a..z). The number is less than 10.
A line whose contents is a single period character means the end of the input (this last line
is not to be processed).

Output
Output texts for each input case are presented in the same order that input is read. For each
test case the answer must be a left aligned Kitty pattern corresponding to the input.

Example
Input:Love 1Kitty 2.Output:LoveoveLveLoeLovKittyKittyittyKittyKttyKittyKityKittyKityKittyKitt

Added by: Daniel Gómez Didier


Date: 2009-10-31
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

5194. Robbery
Problem code: ROB
k bandits robbed a bank. They took away n gold coins. Being a progressive group of robbers they
decided to use the following procedure to divide the coins. First the most respected bandit takes 1 coin,
then the second respected takes 2 coins, ..., the least respected takes k coins, then again the most
respected takes k+1 coins, ans so on, until one of the bandits takes the remaining coins. Calculate how
much gold each of the bandits gets.

Input
The first line of the input contains number t - the amount of tests. Then t test descriptions follow. Each
test consists of two integers n and k - the amount of coins and bandits respectively.

Constraints
1 <= t <= 500
> 1 <= n<b> <= 10 9
> 2 <= k<b> <= 100

Output
For each test print the amounts of coins each bandit gets separated by spaces.

Example
Input:
3
10 2
11 3
12 4

Output:
4 6
5 3 3
3 2 3 4

Added by: Spooky


Date: 2009-11-03
Time limit: 1s
Source
50000B
limit:
Languages: All
Advancement Autumn 2009,
Resource:
http://sevolymp.uuuq.com/

1
SPOJ Problem Set (tutorial)

5195. Angry Knights


Problem code: ANGRYKN
Some angry knights want to settle on the checkmate board of n x m size. The angry knights are much
like the ordinary ones, but each can move at any time. Moreover they don’t like each other and won’t
allow any other knight on their territory. Luckily someone removed some cells from the board, so now
more knights can settle on the board without bothering each other. Count the maximal number of
angry knight that can live on the board simultaneously.

Input
The first line of the input contains number t - the amount of tests. Then t test descriptions follow. Each
test starts with two numbers n and m - the dimensions of the board. Then n lines follow each
consisting of m characters. Character ’x’ means that the corresponding cell is removed, character ’.’
that it is present.

Constraints
1 <= t <= 100
2 <= n, m <= 100

Output
For each test print the maximal number of angry knights that can settle on such board.

Example
Input:
2
2 3
...
...
3 3
...
xxx
...

Output:
4
2

1
Added by: Spooky
Date: 2009-11-03
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Advancement Autumn 2009, http://sevolymp.uuuq.com/, author: Alexey Shchepin

2
SPOJ Problem Set (tutorial)

5200. Lsu Football


Problem code: BRHFBALL
Butch unfortunately missed the most recent LSU football game, but he was luckily able to get the
score S (0 <= S <= 30) from a friend. So he got to thinking, how many possible ways could LSU have
scored this?
Remember that the ways to score are like so:
2 - Safety
3 - Field Goal
6 - Touchdown with missed extra point or failed conversion (only include one 6-point in your
calculations; see note below)
7 - Touchdown with the extra point
8 - Touchdown with a 2 point conversion
Butch would figure out how many ways himself, but he’s busy scouring the web for a replay, so he
wants you to help.
Note: The order is important. For example, if the input is 5, there would be 2 ways: LSU could score
a safety and then a field goal, or it could score a field goal and then a safety.

Note about the 6 point-ers: For example 8 points in total, the number of ways to score would be:

2-2-2-2

2-3-3

3-2-3

3-3-2

2-6

6-2

See that there is only one set of "6-2" and "2-6"; in other words, we don’t say "they scored from a
safety and they scored from a touchdown with a failed extra point" and "they scored from a safety and
they scored from a touchdown with a failed conversion", etc... From Neal, "You should not consider
scoring the touchdown and missing the extra point, and scoring the touchdown and failing the
conversion as two separate ways to score."

Another note: Values may not be precalculated and stored in an array. Any solution that does
this will be disqualified and receive 0 points.

Extra Challenge: The last test case will have S <= 10000.

1
Find the number of ways that a score S can be made in a football game, modulo 10000.

Input
Line 1: A single integer, S

Output
Line 1: A single integer, how many ways they could score

Example
Input:
8Output:
7

Added by: Damon Doucet


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

2
SPOJ Problem Set (classical)

5228. Old problem


Problem code: OLDP
Let G is the convex polygon with area S and perimeter L. We need to know volume of set of points
which distance from G is not greater than R.

Input
Number of test cases in first line and three integers S, L and R for each test case. All integers in input
are nonnegative and less than 100.

Output
Volume for each test case with 10 -2 precision.

Example
Input:
1
48 57 1

Output:
189.724

Added by: Ruslan Sennov


Date: 2009-11-07
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

5241. Alchemy
Problem code: ALCH
Many computer games implement alchemy skill. It allows the player to create different elixirs using
various ingredients. Usually players have to find out recipes for the elixirs they need. Usually they do
it by trying to mix some ingredients. Given that there are n different ingredients and any elixir can be
made by mixing three or more different ingredients, can you count the maximal number of various
elixirs that can be made using alchemy skill.

Input
The first line of the input contains number t - the amount of tests. Then t test descriptions follow. Each
test consist of a single integer n.

Constraints
1 <= t <= 10000
1 <= n <= 10 9

Output
For each test print the maximal number of different elixirs that can be made modulo 1000000007.

Example
Input:
4
3
4
100
100000

Output:
1
5
976366234
607673554

Added by: Spooky


Date: 2009-11-07
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Advancement Autumn 2009, http://sevolymp.uuuq.com/

1
SPOJ Problem Set (classical)

5297. Family Problems


Problem code: FAMILYP
Asif and Nafisa are very interested in solving puzzles.They always try to give one another puzzles to
see who is the best.So ,as usual, one day, Nafisa gave Asif a matrix.

The matrix is as follows


A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C ......
B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D ......
C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E ......
D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F .......
.........................................................................................
.
.
Assume that the matrix is very huge(both row and column wise). Nafisa describes a special sequence
as a sequence  whose first term is ’A’[element at (0,0)], second term is ’B’[element at  (0,1)],third term
is ’B’[element at (1,0)],fourth term is ’C’[element at (2,0)]. Now,she asks Asif to find the nth term of
this special sequence. Help Asif To solve the problem.

Input
There will be multiple test cases with number N(1<=N<=1000000) per line.

Output
A character [’A’-’Z’] per line for each number N representing the Nth number in the special sequence.

Example
Input:3610Output:
TERM 3 IS BTERM 6 IS CTERM 10 IS D

Added by: Hemant Verma


Date: 2009-11-14
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Alkhwarizm 2009

1
SPOJ Problem Set (tutorial)

5302. Surprising Strings


Problem code: MCPC06C
The D-pairs of a string of letters are the ordered pairs of letters that are distance D from each other. A
string is D unique if all of its D-pairs are different. A string is surprising if it is D-unique for every
possible distance D.

Consider the string ZGBG. Its 0-pairs are ZG, GB, and BG. Since these three pairs are all different,
ZGBG is 0 unique. Similarly, the 1-pairs of ZGBG are ZB and GG, and since these two pairs are
different, ZGBG is 1-unique. Finally, the only 2-pair of ZGBG is ZG, so ZGBG is 2-unique. Thus
ZGBG is surprising. (Note that the fact that ZG is both a 0-pair and a 2-pair of ZGBG is irrelevant,
because 0 and 2 are different distances.)

Input
The input consists of one or more nonempty strings of at most 79 uppercase letters, each string on a
line by itself, followed by a line containing only an asterisk that signals the end of the input. 

Output
For each string of letters, output whether or not it is surprising using the exact output format shown
below.

Example
Input:ZGBGXEEAABAABAAABBBCBABCC*
Output:
ZGBG is surprising.X is surprising.EE is surprising.AAB is surprising.AABA is surprising.AABB is NOT surprising.BCBABCC is NOT surprising.

Added by: Tamer


Date: 2009-11-15
Time limit: 3s
Source limit:50000B
Languages: All
Resource: ACM Mid-Central Programming Contest 2006

1
SPOJ Problem Set (classical)

5306. Linear Pachinko


Problem code: MCPC06B
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 1âEuro"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.

1
Example
Input:
/\.|__/\.
_._/\_|.__/\./\_
...
___
./\.
_/\_
_|.|_|.|_|.|_
____|_____
#

Output:
61
53
100
0
100
50
53
10

Added by: Tamer


Date: 2009-11-15
Time limit: 5s
Source limit:50000B
Languages: All
Resource: Mid Central Regional Contest 2006

2
SPOJ Problem Set (classical)

5313. Root of the Problem


Problem code: MCPC06G
Given positive integers B and N, find an integer A such that A^N is as close as possible to B. (The
result A is an approximation to the Nth root of B.) Note that A^N may be less than, equal to, or greater
than B.

Input
The input consists of one or more pairs of values for B and N. Each pair appears on a single line,
delimited by a single space. A line specifying the value zero for both B and N marks the end of the
input. The value of B will be in the range 1 to 1,000,000 (inclusive), and the value of N will be in the
range 1 to 9 (inclusive).

Output
For each pair B and N in the input, output A as defined above on a line by itself.

Example
Input:4 35 327 3750 51000 52000 53000 51000000 50 0

Output:
123444516

Added by: Tamer


Date: 2009-11-16
Time limit: 1s
Source limit:50000B
Languages: All
Resource: ACM Mid-Central Regional Programming Contest 2006

1
SPOJ Problem Set (tutorial)

5965. The Element of Surprise


Problem code: SURPRISE
General Tontus holds the record for most consecutive losses in military history. The emperor is not
pleased that his general holds this unique distinction and has threatened to fire him in the event of
another loss. The general is convinced that his losing streak is not due to poor strategy on his part.
Instead, he blames his messengers for allowing important orders to be intercepted by the enemy, thus
giving away the element of surprise. To alleviate this problem, the general has devised a cunning plan.
All sensitive messages will have the order of their characters reversed, so that even if they fall in
enemy hands, they will be incomprehensible! Because this scheme is too complex to be applied by
hand, the general needs some way to automate it. Help save the general’s job by writing a program to
apply this encryption algorithm.

Input
The first line will contain a single integer N (0 < N < 100). Each of the next N lines will contain a
string of at most 1024 characters which must be encrypted.

Output
For each test case, output a single line containing the encrpyted string. Beware, spaces are significant.

Example
Input:
4
Hello World!
I know 10 digits of pi after the decimal: 3.1415926535
You just lost the game.
ATTACK AT DAWN

Output:
!dlroW olleH
5356295141.3 :lamiced eht retfa ip fo stigid 01 wonk I
.emag eht tsol tsuj uoY
NWAD TA KCATTA

Added by: Miorel Palii


Date: 2010-01-24
Time limit: 1s
Source limit:4096B
Languages: All except: TECS
Resource: own problem statement; used in practice round of a few contests

1
SPOJ Problem Set (tutorial)

5966. Generalized Chess


Problem code: GENCHESS
The emperor’s younger brother, Minimus, is an excellent chess player who has never lost a game. Let
us ignore for the moment the fact that anyone who might dare defeat him would likely suffer a horrible
death. Having mastered the usual game, which is played on a board of size 8, Minimus wants to
generalize chess so that it can be played on a square board of arbitrary size. Unfortunately, Minimus
skipped class so he never learned his multiplication tables, so he’ll give you a number N, and it will be
up to you to tell him how many squares a chessboard of that size would have. Don’t worry, Minimus
can’t count higher than a million, so that’s the highest number you need to be able to handle.

Input
There will be several test cases, each consisting of a single positive integer on a separate line,
representing a possible value of N. A value of zero indicates the end of input and should not be
processed.

Output
For each test case, output a single line containing the number of squares on a chessboard of size N.

Example
Input:
8
1
42
999999
0

Output:
64
1
1764
999998000001

Added by: Miorel Palii


Date: 2010-01-24
Time limit: 1s
Source limit:4096B
Languages: All except: TECS
Resource: own problem statement; used in practice round of a few contests

1
(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)

6069. Ispiti
Problem code: ISPITI
It’s exam time in Mirko’s village. Everyone wants to pass the exam with as little effort as possible,
which is not easy. Mirko realized that it would be best for him to find someone who knows more than
him and learn from them. Everyone followed and now everyone is looking for someone to learn from.
We can model how well a student is prepared for the exam with two integers, A and B. The number A
represents how well a student understands the subject, while the number B is proportional to the
quantity of their knowledge.

As the head of the village, Mirko decided that a student will ask another student for help only if that
student has both numbers greater than or equal to the first student’s numbers (no student will ask
someone who doesn’t understand the subject as well as themselves or who knows less). Additionally,
students will try to minimize the difference in knowledge quantity (so that students don’t bother those
that are way better). If this choice is not unique, they will try to minimize the difference in
understanding.

Mirko’s village has recently become a very popular suburb and new students keep moving in (in time
for the exam). With Mirko’s strict rules, they get confused about Mirko’s rules and don’t know where
to go. They decided to ask a programmer from a neighbouring village for help.

Input

The first line of input contains an integer N (1 <= N <= 200 000), the number of queries and arrivals in
the village. Each of the following N lines contains either:
   *    "D A B", a student has moved in whose knowledge is A and B
   *    "P i", the i-th student to move in wants to know whom to ask for help
The numbers A and B are between 1 and 2.10^9. No two students have both numbers equal.

The first line of input contains an integer N (1 <= N <= 200 000), the number of queries and arrivals in
the village. Each of the following N lines contains either:

   *    "D A B", a student has moved in whose knowledge is A and B

   *    "P i", the i-th student to move in wants to know whom to ask for help

The numbers A and B are between 1 and 2.10^9. No two students have both numbers equal.

Output

For each query ("P i" line), output which student the i-th student should ask for help. The students are
numbered in the order they moved into the village (starting from 1). If a student cannot be helped,
output "NE".

1
Sample test data #1

Input
6
D 3 1
D 2 2
D 1 3
P 1
P 2
P 3

Output
NE
NE
NE

Sample test data #2

Input
6
D 8 8
D 2 4
D 5 6
P 2
D 6 2
P 4

Output
3
1

Sample test data #3

Input
7
D 5 2
D 5 3
P 1
D 7 1
D 8 7
P 3
P 2

Output
2
4
4

2
Added by: Andrés Mejía-Posada
Date: 2010-02-08
Time limit: 3s
Source limit:50000B
Languages: All except: PERL 6
Resource: COCI 2006/2007 - Contest #4

3
SPOJ Problem Set (tutorial)

6291. Problem
Problem code: PROBLEM
This problem has no statement

Input
The format of the input data in not known.

Constraints
The input file is of the reasonable size.

Output
Output the right answer for each test.

Example
Input:
4
188
432
100
765

Output:
4
0
2
1

Added by: Spooky


Date: 2010-03-09
Time limit: 1s
Source limit:50000B
Languages: All except: TECS
Resource: Advancement Spring 2010, http://sevolymp.uuuq.com/

1
(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 (tutorial)

6438. Giá tri. lo+’n nhât 4


Problem code: QMAX4
Cho 1 day S ban đâu không có phân tu+? nao. Máy tính se~ đu+a ra n le^.nh có da.ng sau :

  -  I x y : Chen sô x vao tâp s giu+~a 2 vi. trí y-1 va y (-10^9<=x<=10^9)

  Quy đi.nh : Vo+’i k la sô phân tu+? trong tâp S , y = 1 thi x đu+o+.c chen vao đâu day, y = k+1
thi x đu+o+.c chen vao cuôi day.

  -  S x y : Đôi chô vi. trí 2 phân tu+? thu+’ x va y (x<>y,1<= x,y <= k)

  -  D x : Xóa phân tu+? thu+’ x ra kho?i day S (1<=x<=k)

  -  Q x y : Tim giá tri. lo+’n nhât tu+‘ vi. trí x đe^’n vi. trí y.(1<=x<=y<=k)

Yeu câu : Cho n le^.nh. Hay tra? lo+‘i môi truy vân

Input
- Dong đâu la sô n (n <= 10^5)

- N dong tie^’p theo la các le^.nh có mâu nhu+ tren

Output
Gôm môt sô dong , môi dong tra? lo+‘i cho 1 truy vân theo thu+’ tu+. tu+‘ tren xuông

Example
Input:7I 1 1I 5 2I 2 3S 1 2Q 1 2D 1Q 1 1Output:51

Added by: Fernando Torres


Date: 2010-04-01
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All except: PERL 6

1
SPOJ Problem Set (tutorial)

6475. Da.o cho+i băng xe bus


Problem code: KMBUS
Môt tuye^’n đu+o+‘ng o+? thanh phô có các be^’n xe bus o+? tu+‘ng km tuye^’n đu+o+‘ng. Môi lân
qua be^’n, xe đe^‘u đô đe^? đón khách. Môi be^’n đe^‘u có đie^?m xuât phát. Môt xe chi? cha.y
không quá B km ke^? tu+‘ đie^?m xuât phát cu?a nó. Hanh khách khi đi xe se~ pha?i tra? tie^‘n cho
đô dai đoa.n đu+o+‘ng ma ho. ngôi tren xe. Cu+o+’c phí cân tra? đe^? đi đoa.n đu+o+‘ng đô dai i la
Ci(i=1,2..B). Môt du khách xuât phát tu+‘ 1 be^’n nao đó muôn đi da.o L km theo tuye^’n nói tren.
Ho?i ông ta pha?i len xuông xe nhu+ the^’ nao đe^? tông sô tie^‘n pha?i tra? la nho? nhât có the^?.
Du+~ lie^.u vao:Dong đâu ghi 2 sô nguyen du+o+ng B, L.Dong thu+’ i trong sô B dong tie^’p theo ghi 1 sô nguyen du+o+ng Ci ( 1 <= i <= B ).Ke^’t qu?aMôt dong duy nhât la sô tie^‘n nho? nhât pha?i tra?Gio+’i ha.n 0 <= B <= 1000 <= L <= 100000 <= Ci <= 100 Ví du. Du+~ lie^.u:5 73 46922Ke^’t qu?a14

Added by: Nguye^~n Tie^’n Hoang


Date: 2010-04-08
Time limit: 1s
Source limit:50000B
Languages: All except: TECS
Resource: Bai co+ ba?n.

1
SPOJ Problem Set (tutorial)

6501. Median
Problem code: XMEDIAN
Given an array x of n elements find the medians of its first k elements for each k from 1 to n inclusive.
The median of an array is the middle element of that array when it is sorted. If there are an even
number of elements in the array, we choose the first of the middle two elements to be the median.

Input
The first line of input contains number n (1 <= n <= 200000) - the amount of elements in the array.
The next n lines contain the elements xi (1 <= xi <= 1000000).

Output
Output n integers - the medians of the first k elements of the array for each k from 1 to n inclusive.

Example
Input:
5
1
2
3
4
5

Output:
1
1
2
2
3

Added by: Spooky


Date: 2010-04-13
Time limit: 2s
Source limit:50000B
Languages: All except: TECS

1
SPOJ Problem Set (tutorial)

6521. SuperPower
Problem code: SUPERPW

You are given two arrays a and b of size n. You are also given a number p.You are supposed to find ( a[0]^b[0] + a[1]^b[1] + ... a[n-1]^b[n-1] ) % pYou must also know that( a + b ) % c = ( a%c + b%c ) % cand( a * b ) % c = ( a%c * b%c ) % cWarning: The actual value a[i]^b[i] may not fit in any primitive data-type, infact it may not even fit in the RAM.InputFirst line contains T ( T <= 12 ) which is the number of test-cases.Then contain T-blocks having the following format.First line of each block contains a number n which is the number of elements of arrays a and b and the number p.Second line of each block contains n-integers which are the values a[0], a[1] ... a[n-1]Third line of each block contains n-integers which are the values b[0], b[1] ... b[n-1]OutputFor each block of input print the answer.
2
3 5
2 3 4
1 1 1
4 4
2 2 2 2
1 1 1 1
Example
Input:

Output:
4
0

Added by: .::: Pratik :::.


Date: 2010-04-16
Time limit: 10s
Source limit:50000B
Languages: All except: TECS

1
SPOJ Problem Set (tutorial)

6523. Digital Root Counter


Problem code: DIGRT
The digital root of a number x is calculated by summing up all digits x, then adding all digits of the
sum and so on, until we are left with only a single digit.

For example, if x = 987654, then its digital root d(x) = 9 + 8 + 7 + 6 + 5 + 4 = 39. 


Now we sum up digits of 39. d(39) = 3 + 9 = 12.
Now we sum up digits of 12. d(12) = 1 + 2 = 3.
Thus, d(987654) = 3.

For example, if x = 987654, then its digital root d(x) = 9 + 8 + 7 + 6 + 5 + 4 = 39. 

Now we sum up digits of 39. d(39) = 3 + 9 = 12.

Now we sum up digits of 12. d(12) = 1 + 2 = 3.

Thus, d(987654) = 3.

Input

The first line gives the number of test cases T (T <= 100).

Each of the next T test cases gives the value of N (N <= 50,000).

Output

For each test case, print 10 integers, each separated by a space, indicating number of digital roots in
the range of 1 to N that are equal to i (1 <= i <= 9). Seperate each test case with a new line.

Example

1
Input:21240 Output:2 2 2 1 1 1 1 1 15 5 5 5 4 4 4 4 4

Explanation:

For the first case, there are 2 numbers in the range of 1 to 12 that have digital root equal to 1 (1 and
10), 2 numbers that have digital root equal to 2 (2 and 11) and so on.

Added by: .::: Pratik :::.


Date: 2010-04-16
Time limit: 10s
Source limit:50000B
Languages: All except: TECS

2
SPOJ Problem Set (tutorial)

6524. Find the group


Problem code: FGROUP
 

You are given 2 arrays of size N and M.You have to answer Q queries where each query consists of a
number.
You have to find out in which of the two arrays is the given number in.

You are given 2 arrays of size N and M.You have to answer Q queries where each query consists of a
number.

You have to find out in which of the two arrays is the given number in.

Input
 

The first line gives the number of test cases T (T <= 10).

Then T test case follow.

The first line of each test case gives the value of N.The second line contains N space separated
integers.

The third line of each test case gives the value of M.The fourth line contains M space separated
integers.

Next line gives the value of Q, number of queries to be answered.

Q lines follow containing a number each on one line.

Output
 

For each test case, in response to the Q queries for that test-case print Q lines.

1
If the number is present in both arrays, print "both" ( without quotes ).

Else print the array in which the number is in ( 1 or 2 ).

If the number is not present in both arrays,print -1.

Print a new line after every test case.

Example
Input:
2
3
5 8 2
4
3 8 6 1
4
5
8
6
9
3
1 2 3
3
1 2 3
3
1
2
3

Output:
1
both
2
-1

both
both
both

Constraints:

 N,M <= 20000


Q <= 30000
All numbers in the input will be less than 50000.

Explanation:

For the first case, 5 is present in array 1 only, 8 is present in both arrays, 6 is present in array 2 only
while 6 is not present in either array.

2
Added by: .::: Pratik :::.
Date: 2010-04-16
Time limit: 3s-15s
Source limit:50000B
Languages: All except: TECS

3
SPOJ Problem Set (tutorial)

6528. Circle Counting


Problem code: CIRCP
In this problem, you will be given N circles, and M points. You are required to find out that inside how
many circles does each of the M points lie. None of the M points will lie on any of the N circle
boundaries (they will either lie inside a circle or outside it, but not on the circle).

Input
 

The 1st line gives the number of test cases T.


Each of the next T test cases has a format as explained below.
The 1st line of each test case contains 2 integers N and M.
Each of next N lines contains 3 integers cx, cy, r. The circle is located at center (cx, cy) and has a
radius r.
Each of the following M lines contain 2 integers (x, y), which indicate that the location of the point.

The 1st line gives the number of test cases T.

Each of the next T test cases has a format as explained below.

The 1st line of each test case contains 2 integers N and M.

Each of next N lines contains 3 integers cx, cy, r. The circle is located at center (cx, cy) and has a
radius r.

Each of the following M lines contain 2 integers (x, y), which indicate that the location of the point.

Output
 

For each of test case, print M lines, each correspoding to the no of circles inside which the
corresponding point lies.

1
Separate each test case with a blank line.

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

Output:
1
2
1

Sample diagram

Constraints
T <= 100
0 <= N <= 500
0 <= M <= 500
-1000 <= cx <= 1000
-1000 <= cy <= 1000
-1000 <= x <= 1000
-1000 <= y <= 1000
1 <= r <= 1000

Added by: .::: Pratik :::.


Date: 2010-04-17
Time limit: 10s
Source limit:50000B
Languages: All except: TECS

2
SPOJ Problem Set (challenge)

6555. F - Rompecabezas de Puzzle


Problem code: BOPUZZLE
Problema F - Rompecabezas de Puzzle

El rompecabezas de puzzle consiste en una base de 6 posiciones en los vértices de un hexágono


regular y otra posición en el centro, conectado como se muestra en la figura de abajo. Hay seis fichas
marcadas A, B, C, D, E y F. Un solo movimiento del puzzle es mover una ficha a una posición
adyacente vacía (a lo largo de una conexión permitida - los segmentos de línea en el diagrama a
continuación). La idea del rompecabezas es empezar con un arreglo inicial de fichas con el centro
vacío y, por una secuencia de movimientos, llegar a la configuración de la figura de abajo.

Una posición inicial para el rompecabezas viene dada por una permutación de las letras A a la F. La
primera letra comienza en A en la figura, el próximo es B y así sucesivamente. Una secuencia de
movimientos se especifica mediante la lista de las etiquetas de las fichas que va a mover en el orden en
que han de ser movido.

Por ejemplo, para resolver el rompecabezas FACDBE, utiliza los movimientos BEFAB.

Nota: No todas las permutaciones de partida puede ser resuelto.

Escriba un programa que, dada una permutación inicial, encuentre la menor secuencia de movimientos
para resolver el rompecabezas o determine que no existe una solución.

Entrada

La primera línea de entrada contiene un entero P, (1 <= P <= 1000), que es el número de conjuntos de
datos. Cada conjunto de datos es una línea que contiene el número de conjunto de datos, seguido de un
espacio, seguido por una permutación de las letras A a F representando la posición inicial del
rompecabezas. 

Salida

Para cada conjunto de datos hay una sola línea de salida. Si no hay solución, la línea contiene un
decimal
entero representando al número de conjunto de datos seguido de un espacio único, seguido de la
cadena NO SOLUTION. Si hay una solución, la línea contiene un entero decimal representando el
número de conjuntos de datos seguido por un espacio, seguido por el número de movimientos en la
solución, seguido de un espacio, seguido por la solución como una cadena de letras de la A a la F. Si el
número de movimientos es cero (0), tu aún deberías mostrar el espacio después del 0, a pesar de que
no existe una cadena de letras. 

1
Ejemplo de EntradaEjemplo de Salida
12 1 5 BEFAB

1 FACDBE 20

2 ABCDEF 3 19 DABFECABFEDBACDEFAB

3 ADCEFB 4 NO SOLUTION

4 ADCEBF 5 29 BCDEBCAFBCAFBCEDFAECBAFDCBAFE

5 FEDCBA 6 NO SOLUTION

6 FEDCAB 7 19 CBFACBFACDEFACDEFAB

7 ECBFAD 8 NO SOLUTION

8 ECBFDA 9 13 CDAFBEDCBEDCB

9 DCEBFA 10 NO SOLUTION

10 DCEBAF 11 21 DAEBDAEBDCFEBDCABEFAB

11 CBEADF 12 16 FAEDBCAFBCAFEDCB 

12 BDEAFC 

Added by: Alvaro


Date: 2010-04-21
Time limit: 2s
Source limit:50000B
Languages: C++ 4.0.0-8 C++ 4.3.2 JAVA

2
(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 (tutorial)

6645. SBE201 Linked List


Problem code: SBE201P2
In this problem you will be implementing a linked list of integers (int data type) in strict C language.
The main implemented operations are insertion, deletion, and printing of the list.

Input
The input consists of lines starting with a single character. The character at the beginning of each line
represents the operation to be done. Below is the description of the operations that should be
implemented.

f N: this operation is insertion at the front (head) of the linked list. The integer N is the value to be
inserted. Example: f 7 --> add 7 to the front.

i M N: this operation is insertion at index M. The index is zero-based. The value to be inserted is the
integer N. if the index is beyond the end of the list, the value should be inserted as the last element.
Negative indexes are not expected in the input so you do not have to check for it. Example: i 5 8 -->
insert 8 at index 5 such that the element at 5 is 8 after successful insertion.

r: this operation is deletion at the front. If the list is empty, nothing should happen to the list.

d M: this operation is deletion at an index M. The index is zero-based. If the specified index is beyond
the end of the list, nothing should happen to the list. Negative indexes are not expected in the input so
you do not have to check for it. Example: d 5 --> means to delete the element at index 5.

q: this operation is to stop the program and exit

HINT: do not forget to perform scanf("%c",&tmp) at the end of each input line to read the ’\n’
character and remove it from the input buffer.

1
 

Output
The output of the program is one line for each line of the input. This line should print the complete
linked list, node by node, separated by single spaces. For example, the linked list 5->7->2->8->NULL
should be printed as 5 7 2 8. If the list is empty, the program should print the string "empty" all in
lower case with no spaces in one line.

Example
Input:rf 3f 9i 1 5i 9 7rd 1d 0rf 13rrrrqOutput:empty3 9 3 9 5 3 9 5 3 7 5 3 7 5 7 7 empty13 emptyemptyemptyempty

Added by: Islam Samir Badreldin


Date: 2010-05-13
Time limit: 1s
Source limit:100000B
Languages: C99 strict

2
SPOJ Problem Set (acm)

6647. Tu+’ giác đe.p


Problem code: NICEQUAD
Có N đie^?m to.a đô nguyen tren măt phăng, môt tu+’ giác ABCD vo+’i 4 đi?nh trong N đie^?m tren
go.i la đe.p ne^’u Ax > 0 va Ay > 0; Bx > 0 va By < 0; Cx < 0 va Cy < 0; Dx < 0 va Dy > 0; ABCD có
die^.n tích nguyen. Nhie^.m vu. cu?a ba.n la đe^’m tât ca? các cách cho.n 4 đi?nh ta.o nen tu+’ giác
đe.p.

Du+~ lie^.u
Dong đâu tien la sô bô test T (T < 11).
T nhóm dong tie^’p theo, môi nhóm dong gôm sô đie^?m N (N < 30001), sau đó la N dong, môi
dong gôm to.a đô 1 đie^?m (x, y) (-3000 < x, y < 30000).

Ke^’t qu?a
Ghi tren T dong, môi dong la ke^’t qua? tu+o+ng u+’ng cu?a tu+‘ng test.

Ví du.

Du+~ lie^.u:
1
6
1 1
2 2
-1 -1
-2 2
2 -1
-3 -4
Ke^’t qu?a
2

Added by: Tran Hai Dang


Date: 2010-05-14
Time limit: 1s
Source limit:50000B
Languages: All except: TCL SCALA ERL TECS JS
Resource: Codechef MAY 2010

1
SPOJ Problem Set (tutorial)

6651. Snapper Chain


Problem code: GCJ2010

Problem
The Snapper is a clever little device that, on one side, plugs its input plug into an output socket, and,
on the other side, exposes an output socket for plugging in a light or other device.

When a Snapper is in the ON state and is receiving power from its input plug, then the device
connected to its output socket is receiving power as well. When you snap your fingers -- making a
clicking sound -- any Snapper receiving power at the time of the snap toggles between the ON and
OFF states.

In hopes of destroying the universe by means of a singularity, I have purchased N Snapper devices and
chained them together by plugging the first one into a power socket, the second one into the first one,
and so on. The light is plugged into the Nth Snapper.

Initially, all the Snappers are in the OFF state, so only the first one is receiving power from the socket,
and the light is off. I snap my fingers once, which toggles the first Snapper into the ON state and gives
power to the second one. I snap my fingers again, which toggles both Snappers and then promptly cuts
power off from the second one, leaving it in the ON state, but with no power. I snap my fingers the
third time, which toggles the first Snapper again and gives power to the second one. Now both
Snappers are in the ON state, and if my light is plugged into the second Snapper it will be on.

I keep doing this for hours. Will the light be on or off after I have snapped my fingers K times? The
light is on if and only if it’s receiving power from the Snapper it’s plugged into.

Input
The first line of the input gives the number of test cases, T. T lines follow. Each one contains two
integers, N and K.

Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from
1) and y is either "ON" or "OFF", indicating the state of the light bulb.

Limits
1 <= T <= 10,000.

1
Small dataset
1 <= N <= 10;
0 <= K <= 100;

Large dataset
1 <= N <= 30;
0 <= K <= 10 8 ;

Sample
4

10

11

40

4 47

Output:

Case #1: OFF

Case #2:  ON

Case #3: OFF

Case #4: ON

Added by: Kumar Anurag


Date: 2010-05-14
Time limit: 1s
Source limit:500B
Languages: All except: TECS
Resource: Google Code Jam 2010 Qualifying round

2
SPOJ Problem Set (tutorial)

6653. Lexicographic Order 1


Problem code: LEXI1
An ordering for the Cartesian product x of any two sets A and B with order relations <A and <B,
respectively, such that if (a1, b1) and (a2, b2) both belong to AxB, then (a1, b1) < (a2, b2) iff either

a1 <A a2, or
a1 = a2 and b1 <B b2.

The lexicographic order can be readily extended to cartesian products of arbitrary length by
recursively applying this definition, i.e., by observing that AxBxC = Ax(BxC).

When applied to permutations, lexicographic order is increasing numerical order. For example, the
permutations of {1,2,3} in lexicographic order are 123, 132, 213, 231, 312, and 321.

You will be given a permutation of n first natural numbers. You need to find k-th lexicographically
next permutaion. Also we will consider that the lexicographically last permutaion is followed by the
first one in the ordering.

Input
The first line is number t - the amount of test cases. Each test case starts with numbers n and k. Then n
natural numbers follow which are the elements of the given permutation.

Constraints
1 <= t <= 5
1 <= n <= 50000
0 <= k <= 100

Output
For each test case output the k-th lexicographically next permutation after the given one.

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

1
Output:
2 3 1
3 1 2
3 2 1

Added by: Spooky


Date: 2010-05-15
Time limit: 2s
Source limit:50000B
Languages: All except: TECS

2
SPOJ Problem Set (tutorial)

6654. Lexicographic Order 2


Problem code: LEXI2
An ordering for the Cartesian product x of any two sets A and B with order relations <A and <B,
respectively, such that if (a1, b1) and (a2, b2) both belong to AxB, then (a1, b1) < (a2, b2) iff either

a1 <A a2, or
a1 = a2 and b1 <B b2.

The lexicographic order can be readily extended to cartesian products of arbitrary length by
recursively applying this definition, i.e., by observing that AxBxC = Ax(BxC).

When applied to permutations, lexicographic order is increasing numerical order. For example, the
permutations of {1,2,3} in lexicographic order are 123, 132, 213, 231, 312, and 321.

You will be given a permutation of n first natural numbers. You need to find k-th lexicographically
next permutaion. Also we will consider that the lexicographically last permutaion is followed by the
first one in the ordering.

Input
The first line is number t - the amount of test cases. Each test case starts with numbers n and k. Then n
natural numbers follow which are the elements of the given permutation.

Constraints
1 <= t <= 100
1 <= n <= 20
0 <= k < n!

Output
For each test case output the k-th lexicographically next permutation after the given one.

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

1
Output:
2 3 1
3 1 2
2 1 3

Added by: Spooky


Date: 2010-05-15
Time limit: 1s
Source limit:50000B
Languages: All except: TECS

2
SPOJ Problem Set (tutorial)

6655. Lexicographic Order 3


Problem code: LEXI3
An ordering for the Cartesian product x of any two sets A and B with order relations <A and <B,
respectively, such that if (a1, b1) and (a2, b2) both belong to AxB, then (a1, b1) < (a2, b2) iff either

a1 <A a2, or
a1 = a2 and b1 <B b2.

The lexicographic order can be readily extended to cartesian products of arbitrary length by
recursively applying this definition, i.e., by observing that AxBxC = Ax(BxC).

When applied to permutations, lexicographic order is increasing numerical order. For example, the
permutations of {1,2,3} in lexicographic order are 123, 132, 213, 231, 312, and 321.

You will be given a permutation of n first natural numbers. You need to find k-th lexicographically
next permutaion. Also we will consider that the lexicographically last permutaion is followed by the
first one in the ordering.

Input
The first line is number t - the amount of test cases. Each test case starts with numbers n and k. Then n
natural numbers follow which are the elements of the given permutation.

Constraints
1 <= t <= 100
1 <= n <= 250
0 <= k < n!

Output
For each test case output the k-th lexicographically next permutation after the given one.

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

1
Output:
2 3 1
3 1 2
3 2 1

Added by: Spooky


Date: 2010-05-15
Time limit: 2s
Source limit:50000B
Languages: All except: TECS

2
SPOJ Problem Set (tutorial)

6656. Lexicographic Order 4


Problem code: LEXI4
An ordering for the Cartesian product x of any two sets A and B with order relations <A and <B,
respectively, such that if (a1, b1) and (a2, b2) both belong to AxB, then (a1, b1) < (a2, b2) iff either

a1 <A a2, or
a1 = a2 and b1 <B b2.

The lexicographic order can be readily extended to cartesian products of arbitrary length by
recursively applying this definition, i.e., by observing that AxBxC = Ax(BxC).

When applied to subsets, two subsets are ordered by their smallest elements. For example, the subsets
of {1,2,3} in lexicographic order are {}, {1}, {1,2}, {1,2,3}, {1,3}, {2}, {2,3}, {3}.

You will be given a subset of a set of first n natural numbers. You need to find k-th lexicographically
next subset. Also we will consider that lexicographically last subset is followed by the first one in the
ordering.

Input
The first line is number t - the amount of test cases. Each test case starts with numbers n and k. The
next line describes the given subset. The description starts with number q - the amount of elements in
the subset, followed by q natural numbers - the elements of the subset.

Constraints
1 <= t <= 5
1 <= n <= 50000
0 <= k <= 10000
0 <= q <= n

Output
For each test case output the k-th lexicographically next subset after the given one. If the result is an
empty set then print "empty".

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

1
Output:
empty
3
1 2 3 4 5

Added by: Spooky


Date: 2010-05-16
Time limit: 1s
Source limit:50000B
Languages: All except: TECS

2
SPOJ Problem Set (tutorial)

6677. Rope Intranet


Problem code: GCJ2K10

Problem
A company is located in two very tall buildings. The company intranet connecting the buildings
consists of many wires, each connecting a window on the first building to a window on the second
building.

You are looking at those buildings from the side, so that one of the buildings is to the left and one is to
the right. The windows on the left building are seen as points on its right wall, and the windows on the
right building are seen as points on its left wall. Wires are straight segments connecting a window on
the left building to a window on the right building.

You’ve noticed that no two wires share an endpoint (in other words, there’s at most one wire going out
of each window). However, from your viewpoint, some of the wires intersect midway. You’ve also
noticed that exactly two wires meet at each intersection point.

On the above picture, the intersection points are the black circles, while the windows are the white
circles.

How many intersection points do you see?

Input
The first line of the input gives the number of test cases, T. T test cases follow. Each case begins with
a line containing an integer N, denoting the number of wires you see.

The next N lines each describe one wire with two integers A i and B i . These describe the windows
that this wire connects: A i is the height of the window on the left building, and B i is the height of the
window on the right building.

Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from
1) and y is the number of intersection points you see.

Limits
1 <= T <= 15.
1 <= A i <= 10 4 .
1 <= B i <= 10 4 .
Within each test case, all A i are different.
Within each test case, all B i are different.

1
No three wires intersect at the same point.

Small dataset
1 <= N <= 2.

Large dataset
1 <= N <= 1000.

Inputs:

2
3
1 10
55
77
2
11
22

output:

Case #1: 2
Case #2: 0

 
 

Added by: Kumar Anurag


Date: 2010-05-23
Time limit: 1s
Source limit:5000B
Languages: All except: TECS
Resource: Google Code Jam 2010 Round 1

2
SPOJ Problem Set (challenge)

6696. F - The Sweeper in Cleanland


Problem code: BOSWEEP
PROBLEM F

THE SWEEPER IN CLEANLAND

Cleanland is a city well-known for the civility of its inhabitants. There is no crime, the streets are
clean, drivers respect speed limits. In spite of its cleanliness, every day, during the early hours of the
morning, a machine is used to clean the curb sides of each street. The city is not too large, so every
street is a two-way street, and there is only one machine available to do the job of sweeping the streets.
Both sides of each street must be swept. The operator of the sweeping machine is a inhabitant of the
city, therefore the curb is traversed in the direction the traffic flows, so each street must be traversed in
both directions, cleaning one side at a time.

Your job is to provide the operator with an optimal route, so that no street is traversed more than
twice, once in each direction. Of course, one may drive from any point in the city to any other point in
that same town. For simplicity, we assume that every street is one block in length, connecting two
distinct corners. The figure below gives a small example one such town, where is an optimal route.

Input

The input contains several test cases, each case consists of two or more lines. The first line contains
two integers, n and m, separated by one space. Integer n, (2<=n<=100), is the number of corners,
which are identified by the integers 0, 1, . . . , n-1. Integer m, (0 < m <= n(n-1)/2), is the number of
streets. The next m lines describe the m streets: every line contains two integers v and w, separated by
one space, corresponding to the corners connected by the street. Note that no two corners are
connected by two or more streets. Note also that the ends of each street are distinct. The end of the
input is indicated by a line containing precisely two zeros, separated by one space.

Output

For each test case, your program should output one line. The line contains case c: followed by one
space, where c is the case number, without leading zeros (the first case is case number 1). Then,
separated by precisely one space, an optimal route, described by its corners, in the order they appear in
the route. You should not repeat the initial corner as the last corner. All these integers should be
printed in the same line, separated by exactly one space. 

Sample Input

67

01

05

1
12

15

23

24

34

21

01

0 0 

Sample Output

case 1: 2 3 4 2 4 3 2 1 0 5 1 5 0 1

case 2: 0 1

Notice:

Imagen3

Figure 1: An optimal route: 2 3 4 2 4 3 2 1 0 5 1 5 0 1

Added by: Alvaro


Date: 2010-05-25
Time limit: 1s
Source limit:50000B
Languages: C C++ 4.0.0-8 C++ 4.3.2 JAVA

2
(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)

6703. SBE201 Palindromes


Problem code: SBE201P3
A palindrome is a word, phrase, number or other sequence of units that can be read the same way in
either direction. Example words: rotator, racecar, level, radar, ... etc. More information on palindromes
can be found on Wikipedia, http://en.wikipedia.org/wiki/Palindrome. A typical application of the
Stacks and Queues is to detect Palindromes, by pushing the string to be tested in a stack and enqueuing
it in a queue character by character. Then, it is possible to detect whether the string under test is a
Palindrome or not by popping it from the stack and dequeuing it from the queue and comparing the
output characters.
In this problem you will implement a simple palindrome detection using stacks and queues, either
static or dynamic. It is obligatory to use at least one stack and one queue in your problem. Failing to
meet this requirement will result in your answer being disqualified and rejected.

Input
The input consists of N test cases. The first line of the input contains only the positive number N.
There are exactly N lines of input following the first line. Each of those lines contains exactly one
string to be tested for being a palindrome. The test strings are guaranteed to be free of all white spaces.
Also, the test strings are guaranteed to be less than 50 characters in length, excluding the
null-terminating character.

Output
For each test string, print exactly one line containing exactly one number. This number should be 1 if
the test string is a palindrome and should be 0 if the test string is not a palindrome.

Example
Input:5radarexamwysiwyglevelrotatorOutput:10011

Added by: Islam Samir Badreldin


Date: 2010-05-26
Time limit: 0.5s
Source limit:50000B
Languages: C99 strict

1
SPOJ Problem Set (classical)

6734. Crossing the bridge


Problem code: CRUCE
n people wish to cross a bridge at night. A group of at most two people may cross at any time, and
each group must have a flashlight. Only one flashlight is available among the n people, so some sort of
shuttle arrangement must be arranged in order to return the flashlight so that more people may cross.

Each person has a different crossing speed; the speed of a group is determined by the speed of the
slower member. Your job is to determine a strategy that gets all n people across the bridge in the
minimum time.

Input
The input begins with a single positive integer on a line by itself indicating the number of the
cases following, each of them as described below. This line is followed by a blank line, and there
is also a blank line between two consecutive inputs.

The line of input contains n, followed by n lines giving the crossing times for each of the people.
There are not more than 1000 people and nobody takes more than 100 seconds to cross the bridge.

Output
For each test case, the output must follow the description below. The outputs of two consecutive
cases will be separated by a blank line.

The line of output must contain the total number of seconds required for all n people to cross the
bridge. 

Example
Input:

1
4
1
2
5
10

Output

17

1
Added by: Coach UTN FRSF
Date: 2010-06-03
Time limit: 1s-3s
Source limit:50000B
Languages: All except: TECS
Resource: http://uva.onlinejudge.org/external/100/10037.html

2
SPOJ Problem Set (classical)

7129. Happy Telephones


Problem code: TTREAT
In the land of Eden, all phone conversations are happy ones. People com-plaining on the phone
are immediately put in jail. To enforce this law, the police taps all phone conversations. The
police wants to hire the approriate number of operators to listen to all conversations in a given
period of time. Unfortunately, each of their operators can listen to one conversation only before
needing a really long break to rest from the eort. As a contractor of the police department, you
have been asked to provide a program capable of determining the required number of
operators. If the program does not work correctly, you will be put in jail as well, along with
all the unhappy complainers. Do you really want to end up there? Telephone operators. Photo:
Seattle Municipal Archives.

Input

Each test case starts with two integers denoting the number of phone calls N (1<=N<=10 000) and
the number of intervals M (1<=M<=100). This is followed by N lines describing the telephone calls,
each one consisting of four integers Source, Destination, Start and Duration. Source and Destination
identify the pair of telephone numbers establishing the connection (0<=Source;Destination<=10 000
000). Start and Duration are the start time and duration of the call in seconds (1<=Duration<=10000
and Start>=0). You can safely assume that the sum of Start and Duration ts into a 32-bit signed
integer. Afterwards follow M lines containing the time intervals the police are interested in, each on
described by two integers Start and Duration, in the same format and with the same meaning and
constraints as those in the telephone calls. The last test case is represented by N = M = 0 and must not
be processed.

Output

For each of the M intervals of each test case, print the number of calls that are active during at least
one second of the interval.

Sample input:

32

3425

1 2 0 10

6558

06

82

1
12

8 9 0 10

91

10 1

00

Sample output:

Added by: Pfifing


Date: 2010-08-14
Time limit: 1s
Source limit:50000B
Languages: All except: PERL 6 TECS
Resource: SWERC 2009

2
SPOJ Problem Set (classical)

7207. Alchemy
Problem code: ALCHE
Alchemy is a discipline that is believed to span at least 2500 years of human history.
It is most known for its intention of transforming matter, typically trying to come up
with a recipe to make gold based on much less valued metals, aided by some non-metal
components.
Most scientists and scholars think that alchemy has failed. They surely do not know that
a particular alchemist named Albert Ainstain, managed to create gold from a simple
combination of ordinary iron (much more common and cheap than gold) and some good-
old-fashioned water. However, the combination must have the exact proportion of grams
of iron and centiliters of water to work, otherwise the alchemist would end up with useless
rusty iron.
Many alchemists and bussinessman had tried to recreate Albert Ainstain’s findings to
achieve recognition, fame, prestige or economical welfare, but none of them have suceeded.
Since you know very little about chemistry, alchemy and ancient practices, you believe
that your chances for success in this task are bounded to using a computer in your benefit.
Therefore, you decide to create a program that automatically tests a given combination
of iron and water, and informs whether that combination has the correct proportion
to produce gold. Of course, once you find the right proportion, you can double both
amounts and get double the gold, cut both in half and get half the gold, or multiply both
by any other real number to obtain the amount of gold you want. Your task is then,
given the number of grams of iron and the number of centiliters of water, say whether
the proportion between both components is the right one.

Input
The input contains several test cases, each one described in a single line. The line
contains two integers I and W separated by a single space, representing grams of iron
and centiliters of water, respectively (1 <= I, W <= 10 6 ). The last line of the input contains
the number -1 twice separated by a single space and should not be processed as a test
case.

Output
For each test case output a single line containing an uppercase "Y" if the combination
produces gold, or an uppercase "N" otherwise.

Example
Input:1000 37999 3710000 37010001 370-1 -1Output:YNYN

1
Added by: Pablo Ariel Heiber
Date: 2010-08-22
Time limit: 1s
Source limit:50000B
Languages: All except: PERL 6 TECS
Resource: FCEyN UBA ICPC Selection 2009

2
SPOJ Problem Set (tutorial)

7431. Vikram & Betaal


Problem code: RANJAN03
In order to pass through the wood, Vikram have to solve the following puzzle of Betaal:
Betaal has captured the Vikram’ family in the location pointed by the co-ordinate (x, y), while Vikram
is on (0,0). Now Vikram has to count the total no. of increasing lattice paths from his initial position to
his family and tell it to Betaal in order to set his family free. As Vikram is a loser in mathematics from
childhood, he demanded you to solve this puzzle and message it secretely to him.

Problem:
Given the no. of test cases, t, followed by t lines. Each line contain a no., n, representing the
co-ordinate (n, n), where Vikram’ family has been imprisioned. Find the number of increasing lattice
paths from (0, 0) to (n, n) and print in separate lines. A path is increasing if it goes up or to the right
only, i.e., a path can go from (x, y) to either (x+1, y) or (x, y+1).
Constraint:

a. 0 < n < 31
b. number of ways < 2^64

Example
Input:512345Output:262070252

Added by: lost


Date: 2010-09-28
Time limit: 2s
Source limit:50000B
Languages: All
Resource: IIITM Local Contest

1
SPOJ Problem Set (tutorial)

7677. Frequent Values


Problem code: CPCRC1D
Given a non-decreasing series of integers a 1 ,a 2 ,...,a n and indices 1<=i<=j<=n, what is the maximum
number of repeated numbers within a i ,a i+1 ,...,a j ?

Input
Input contains several test cases.

Each case begins with two integers 1<=n,q<=10 5 .

Next line contains n integers (a 1 ,a 2 ,...,a n ), each one having a size of lower than or equal to 10 5 .

In next q lines, there are queries. Each one contains two integers 1<=i<=j<=n.

Input terminates when n,q are zero.

Output
For each query, print the maximum number of repetitions within numbers a i ,a i+1 ,...,a j .

Example
Input:
10 31 1 3 3 3 3 5 10 10 102 31 105 100 0Output:
143

Added by: Tii


Date: 2010-10-25
Time limit: 1s-3s
Source limit:50000B
Languages: All
Resource: ULM Local contest 2007

1
SPOJ Problem Set (tutorial)

7910. PECOS STRING


Problem code: PECOSSTR
As many of you are not aware of the Pecos, let me introduce him. Pecos is the Jerry’s guitar playing
Uncle with a henkerin’s for Cat Whiskers.

Whenever a string of his guitar broke, he replace it with one the Tom’s whiskers. Finding no other
solution, Tom asks Uncle Pecos to let him play the music for him.

As Uncle Pecos is a creative mouse since his last life, he provide Tom his music notes, and ask him to
play notes only at n th position. On noticing that it’s very easy, he added that the Tom had to miss
every n th note, from the notes which he is supposed to play.

Input
There are one test case per line. Test cases ends with a ’-1’ (qoutes for clearity). Each test case
contains a number, n, followed by the musical notes, charaters from [a-z] and is upto length of 1000, in
the same line.

Output
For each test case, print the required note in separate line.

Example
Input:3 abcdefghijklm4 pqrstuvwxyzsm-1Output:cflswsExplanation for test case # 1: abcdefghijklmInitially Tom is supposed to play every note at 3*n (n e Z + ) position : cfilBut after the second restriction, he had to miss every 3*n’ (n’ e Z + ) note, so new notes are : cfl

Added by: lost


Date: 2010-11-18
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

7925. Fibonnaci Parity


Problem code: FIBPARIT
In the quest to take over the world, the Pinky falls from the table, upside down. Miracle!!! Now he is
intelligent. and the conversation goes like:

Brains : Pinky, are you pondering what I’m pondering?


Pinky : I think so, what would be the remainder when the n th fibonacci number is divided by k?

Help Brain, solving this mystery.

Statement : Given n and k, find the remainder when the n th fibonacci number is divided by k.
Constraints :
1 <= n <= 10 4
1 < k <= 10 5

n th fibonnaci numbers are defined by :

fib n = 1                       if n = 1 or n = 2
  = fib n-1 + fib n-2   for n > 2

Fibonacci series goes like : 1 1 2 3 5 8 13...

Input
The first line contains t, number of test cases. In following t lines, there are two space separated
numbers, n k.

Output
For each test cases, print the solution to the Pinky’s quest in new line.

Example
Input:55 24 310 44 511 12Output:10335

Added by: lost


Date: 2010-11-19
Time limit: 2s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

8191. Gold distribution


Problem code: GOLDCOIN
 

Ankul and Rohil have been awarded with N gold coins in a recent programming competition. Now
they want
to divide these N coins. But there is a problem, weight of each coin is not equal.Both of them know
that
dividing these coins optimally is an NP-Complete problem. So they have decided to put all the coins
on a stack and
divide them in the following manner:
They both take their turn alternatively and in each turn atmost K coins from the top of stack can be
taken.
Ankul always start first. Consider that both of them are infinitely intelligent so they will always take
the
best possible move. you have to find the maxinum weight which Ankul and Rohil will be able to get.

Ankul and Rohil have been awarded with N gold coins in a recent programming competition. Now
they want to divide these N coins. But there is a problem, weight of each coin is not equal.Both of
them know that dividing these coins optimally is an NP-Complete problem. So they have decided to
put all the coins on a stack and divide them in the following manner: 

They both take their turn alternatively and in each turn atmost K coins from the top of stack can be
taken. Ankul always start first. Consider that both of them are infinitely intelligent so they will always
take the best possible move. you have to find the maximum weight which Ankul and Rohil will be
able to get.

Input
First line of input contains T,(1<=T<=30) the number of test cases then T test cases follow. First line
of each test cases contains two space separated integers N and K (1<=N<=10000 and
1<=K<=10). 2nd line contains N space separated integers (w1, w2,...wn), wi if the weight of ith gold
coins from the top.(0<=wi<=1000)

Output
For each test case print one line which contains 2 space separated integers A and R. A and R are the
maximum weight of gold which Ankul and Rohil will be able to take respectively.

Example
Input:
2
3 2
1 2 3

1
10 4
2 1 0 1 3 9 2 0 1 5

Output:
3 3
14 10

Added by: Mahesh Chandra Sharma


Date: 2011-01-20
Time limit: 2s
Source limit:50000B
Languages: All
Resource: Own problem

2
SPOJ Problem Set (main)

8214. Problem 1
Problem code: NOVICE21
Given three Integers A, B, and N. Find how many integers between A and B( inclusive ) are divisible
by N. 0<=A<=B<=10^18, 1<=N<=10^18.

Input
First line contains T the number of test cases. Each of next T lines contains 3 integer A, B, N.

Output
For each test case print the answer in a new line.

Example
Input:21 4 310 20 6Output:12

Added by: Mahesh Chandra Sharma


Date: 2011-01-25
Time limit: 1s
Source limit:50000B
Languages: C C# C++ 4.0.0-8 C++ 4.3.2 C99 strict JAVA
Resource: NSIT Noivce contest #2

1
SPOJ Problem Set (tutorial)

8216. Problem 3
Problem code: NOVICE23
For a given positive integer N, you have to find how many prime numbers are there upto N.

Input
First line contains T the number of test cases, (about 1000). Each of next T lines contains 1 integer N
(1<=N<=1000000).

Output
For each test case print the answer in a new line.

Example
Input:
2510Output:
34

Added by: Mahesh Chandra Sharma


Date: 2011-01-25
Time limit: 1s
Source limit:50000B
Languages: All
Resource: NSIT Noivce contest #2

1
SPOJ Problem Set (tutorial)

8218. Problem 4
Problem code: NOVICE24
Given an integer N you have to find smallest prime number which comes after N, means smalltest
prime which is greater than N.

Input
First line contains T the number of test cases. Each of next T lines contain one integer N. 1<=N<=10^9

Output
For each test case print the answer in a new line.

Example
Input:
2521Output:
723

Added by: Mahesh Chandra Sharma


Date: 2011-01-26
Time limit: 1s
Source limit:50000B
Languages: All
Resource: NSIT Noivce contest #2

1
SPOJ Problem Set (tutorial)

8219. Problem 5
Problem code: NOVICE25
A natural number k is divisor of another natural number if K completely divides N, means N % k = 0.
For example 6 has 4 positive divisors 1, 2, 3, and 6. Now given a natural number N you have to find
number of its positive divisors.

Input
First line contains T the number of test cases. Each of next T lines contain one integer N. 1<=N<=10^9

Output
For each test case print the answer in a new line.

Example
Input:
267Output:
42

Added by: Mahesh Chandra Sharma


Date: 2011-01-26
Time limit: 1s
Source limit:50000B
Languages: All
Resource: NSIT Noivce contest #2

1
SPOJ Problem Set (tutorial)

8289. Find the unique Number


Problem code: REPEAT
There will be odd number of element in array, and each number has a pair except one element. Find
that unique element

Input
T = number of test cases

N = size of array

a1, a2, ... an array element

Output
Unique number

Example
Input:
252 1 2 3 173 3 5 4 5 4 5Output:
35 limit:T<=100N<=10^5ai <= 10^10

Added by: pankaj


Date: 2011-02-10
Time limit: 1s-2s
Source limit:50000B
Languages: All
Resource: own

1
SPOJ Problem Set (tutorial)

8293. Bit count


Problem code: BITCNT
Count the number of ones in bit repesentation of number.

Generate N number using formula (a*i+b)%c for all 1<=i<=n

limit: 1<=N<=1000000

0<=a*N, b*N<2^64

1<=c<2^64

Input
N

abc

Output
[N numbers]

c1

c2

..

cn

Example
Input:
55 6 7Output:
11022ExplanationGenerated numbers are 4, 2, 0, 5, 3 and bit counts are 1, 1, 0, 2, 2 respectivelyhints:use unsigned long long

Added by: pankaj


Date: 2011-02-10
Time limit: 1s-2s
Source limit:50000B
Languages: All
Resource: own

1
SPOJ Problem Set (tutorial)

8360. Prime After N


Problem code: AU12
Given an integer N you have to find smallest prime number which comes after N, means smalltest
prime which is greater than N.

Input
First line contains T(1<=T<=1000) the number of test cases. Each of next T lines contain one integer
N. 1<=N<=10^9

Output
For each test case print the answer in a new line.

Example
Input:2521

Output:

723

Added by: amit karmakar


Date: 2011-02-17
Time limit: 3s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (classical)

8373. AVION
Problem code: AVION1
 

Mirko and Slavko are USKOK agents tracking the movements of an unnamed corrupt government 
official. Anonymous sources have tipped them about his upcoming escape attempt. They now know
he 
plans to use his diplomatic liaisons to try and hitch a ride on a CIA blimp leaving from Severin na
Kupi 
blimp port. 
It’s common knowledge that all CIA blimps have the  string "FBI" somewhere in their registration 
codes. They obtained a list of all blimps scheduled for the designated day. There are exactly 5 blimps 
on the list. Write a program that will point out all CIA blimps. 
INPUT 
There are exactly 5 rows of input, each row representing one blimp registration code from the list. A 
registration code is a sequence of at most 10 uppercase letters of the English alphabet, digits ‘0’ to
‘9’, 
or dashes ‘.’. 
OUTPUT 
The first and only line of output must contain a space separated list of integers, sorted in increasing 
order, indicating the corresponding input rows containing registrations of CIA blimps. 
If there are no CIA blimps, output the string "HE GOT AWAY!"

Mirko and Slavko are USKOK agents tracking the movements of an unnamed corrupt government 

official. Anonymous sources have tipped them about his upcoming escape attempt. They now know
he 

plans to use his diplomatic liaisons to try and hitch a ride on a CIA blimp leaving from Severin na
Kupi 

blimp port. 

It’s common knowledge that all CIA blimps have the  string "FBI" somewhere in their registration 

codes. They obtained a list of all blimps scheduled for the designated day. There are exactly 5 blimps 

on the list. Write a program that will point out all CIA blimps. 

INPUT 

1
There are exactly 5 rows of input, each row representing one blimp registration code from the list. A 

registration code is a sequence of at most 10 uppercase letters of the English alphabet, digits ‘0’ to
‘9’, 

or dashes ‘.’. 

OUTPUT 

The first and only line of output must contain a space separated list of integers, sorted in increasing 

order, indicating the corresponding input rows containing registrations of CIA blimps. 

If there are no CIA blimps, output the string "HE GOT AWAY!"

input 

N-FBI1 

9A-USKOK 

I-NTERPOL 

G-MI6 

RF-KGB1 

output 

input 

N321-CIA 

F3-B12I 

F-BI-12 

OVO-JE-CIA 

KRIJUMCAR1 

output 

HE GOT AWAY!

2
 

Added by: kawmia institutes problem setters


Date: 2011-02-18
Time limit: 1s
Source limit:50000B
Languages: All
Resource: COCI

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 (tutorial)

8377. PRAYER QUEUE


Problem code: PRQUEUE
In Jhonny’ class, there are unlimited students of different heights, including Jhonny.But on a specific
day there are only n students are present. Everyday Jhonny remains anxious to find who will stand
behind him in the prayer queue, a boy or a girl. He wants his best friend, Kelly, to find the same for
him.

Given the height of n students and Jhonny, too, find the height of student who will stand behind him in
the queue.

Constraints:

 - 1 <= number of students, n <= 1000

 - 1 <= height of i’th student, h i <= 10000   for i = {1, 2, ..., n}

 - Each height will be different.

 - Students stand in the queue in the increasing order of their height.

 - Jhonny is not the longest boy present that day.

Input
The first line of the input contains t, number of test case. Then follows t test cases.

Each test case contains two lines. The first line has two numbers, n h, the number of students and
height of Jhonny.

In the next line there are n numbers, h 1 h 2 h 3 ...  h n ,  representing the height of all the n students,
including Jhonny’s height.

There are about 150 test cases.

Output
Find the height of the person who will stand behind Jhonny in the queue.

1
Example
Input:35 64 2 6 8 73 21 2 36 553 44 55 11 75 12Output:7375Explanation for test case #1:5 64 2 6 8 7Jhonny’s height = 6The boy with height 7 will stand behind him in the queue.

Added by: lost


Date: 2011-02-19
Time limit: 1s
Source limit:50000B
Languages: C C# C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource: IIITM Local Contest

2
SPOJ Problem Set (classical)

8378. find seat in dope cup


Problem code: DOPECUP
N friends go to watch the 2011 DOPE-cup. Unfortunately for them, they reach late to the venue and as
a result, could not get the seats together. Suppose that the seats are arranged in R rows and C columns.
Your job is to write a program to find seats as close to each other as possible. The nearness is defined
as the area of the smallest rectangle with sides parallel to the seats that contains all seats for the
group.Area is measured as the number of seats contained in it.

Input
Each test case will consist on several lines.
The first line will contain three positive integers R, C and N as explained above
 (1 <= R,C <= 300, 1 <= N <= R × C).
The next R lines will contain exactly C characters each. The j-th character of the i-th line
will be ‘X’ if the j-th seat on the i-th row is taken or ‘.’ if it is available.
There will always be at least N available seats in total. input ends with R,C,N is 0 0 0.

Output
Area is measured as the number of seats contained in it.

Example
Input:
433
..X
X.X
...
XXX
546
XX..
..X.
XX..
...X

XXXX
000
Output:
3
8

1
Added by: pankaj
Date: 2011-02-19
Time limit: 5s-15s
Source limit:50000B
Languages: All
Resource: FSEAT, DOPE 2011

2
SPOJ Problem Set (main)

8379. count frequency of digits


Problem code: DOPECNT
Young Dope was bored of finding whether a given number is palindromic or not.So he started another
exercise described as follows. Given a number consisting of n digits, find the number of pairs of digits
such that position[i] equals position[j] 1<=i,j<=n.

Input
First line contains T, the number of test cases <100
Each test case contains a number with 1=<length <= 10^5 and
digits only between 0 and 9 both inclusive.

Output
Number of pairs of such digits.

Example
Input:

2
1234
777

Output:

4
9

Added by: pankaj


Date: 2011-02-19
Time limit: 2s-3s
Source limit:50000B
Languages: C C++ 4.0.0-8 C++ 4.3.2
Resource: harsh, DOPE 2011

1
(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 (tutorial)

8380. COUNT ATTENDANCE


Problem code: ATTENDC
You had been provided the task to count the actual attendace in the class, given the list of students who
called the attendace in order they called it.

Note: There may be proxy attendance.

Constraint:

- Each name consist of letters between ’a’-’z’, inclusive.

- Each student has a different name.

- Lengh of each name is 5 characters.

- 1 <= n <= 100

Input
Test case begins with t, the number of test cases. The value of t will be between 100-150 Then follows
t test-cases.

Each test case begins with a number n, number of students who had marked the attendace (attendace
proxies can be there). Then in the following n lines, the are the name of student who called the
attendace, in the order they  called it.

Output
For each test case, print the actual number of present students in separate line.

Example
Input:34pcsinneetaphanivinod5ankitshyamghyamshyamankit3adnanarpanarpanOutput:432Explanation for test case #2:Only three students are present: ankit, shyam and ghyam.

Added by: lost


Date: 2011-02-20
Time limit: 1s
Source limit:50000B
Languages: C C# C++ 4.3.2 C++ 4.0.0-8 JAVA

1
SPOJ Problem Set (tutorial)

8395. ZBROJ
Problem code: ZBROJ
After he got tired of rotating tables, the teacher gave Perica another problem. She wrote two integers,
A
and B, on the blackboard and asked him to add them.
Perica is never wrong with his calculation, but sometimes he doesn’t copy the numbers correctly. The
only mistake he ever makes is copying a 5 as a 6, and viceversa.
Given two numbers, A and B, calculate the minimum and the maximum sum Perica could possibly
get.

Input
The first and only line of input contains positive integers A and B (1 <= A, B <= 1 000 000).

Output
In single line of output, print two space separated integers, minimum and maximum sum Perica could
get.

Example
Input:11 25Output:36 37

Added by: akaki


Date: 2011-02-22
Time limit: 1s
Source limit:50000B
Languages: All
Resource: coci

1
SPOJ Problem Set (tutorial)

8412. Greedy Government


Problem code: GRDGOVT
The Government of Greedistan has just found out that there is a lot of gold beneath some land area in
their country. They quickly surveyed the land area and found that some people are living there, and
surprisingly the houses are organized in a M x N grid, each cell having exactly one house.

To acquire all the gold beneath this area, the government has planned to make up a rumor ( a volcano
is about to erupt near by ) and let the people vacate their houses themselves. They start the rumor at
only one house on day 1. It takes exactly one day for the rumor to spread from a house to any of its
neighbors ( top, left, bottom, right ). They all vacate their houses as soon as they know about the
volcano.

The government wants to choose the starting house for the rumor in such a way that it takes minimum
number of days for all the people to vacate their houses. Find this minimum time.

Input
The first line contains T, the number of test cases. Each of the next T lines contain two integers M and
N. If one of M or N is zero, other one will also be zero, and this means, there are no houses at all.

T <= 1,000

0 <= M <= 1,000,000

0 <= N <= 1,000,000

Output
The minimum number of days it takes to spread the rumor to all houses.

Example

3 2 3 4

2 1 2 3
3 2 3 4

1
Added by: Anil Kishore
Date: 2011-02-25
Time limit: 1s
Source limit:50000B
Languages: All
Resource: CodeMutants 2011 , DA-IICT, India

2
SPOJ Problem Set (tutorial)

8413. Clean the Forum Posts


Problem code: CLNFORUM
Long ago during the Jurassic Park age, there was a company TopHunters, which used to conduct
hunting competitions for the Dinosaurs around the world. Petrosaurus was believed to be the greatest
hunter of that time and all other dinosaurs enjoyed watching the hunting videos posted by him in the
forums ( yes, they had a website :) ).

Many Indian dinosaurs used to post in sms language in the forums and annoy others. Vexosaurus was
so annoyed reading the posts with numbers used in place of letters. He decided to correct all those
posts, before the forums get Rusty. Could you please code for him and replace the following words in
1st column with their corresponding words in 2nd column

8 ate
w8 wait
gr8 great            
4 for
b4 before

Lets not make this complex and just replace the words when they appear entirely as a word
themselves, and not as a subpart of bigger words ( see examples for clarity ). A word is a continuous
sequence of non-space characters.

Disclaimer : This is just a fictional story. Any resemblance to real persons or company or dinosaurs is
purely coincidental :|

Input
First line contains T [ number of test cases, around 50 ]. Each of the next T lines contains a sentence
with not more than 100 characters [ ’a’ - ’z’ , ’0’ - ’9’ , space ]. There can be 2 or more continuous
spaces and you have to preserve them, in the output. Input sentence will not begin or end with a space.

1
Output
For each test case, output the corrected sentence, in a new line.

Example
Input:3i 8 food b4gr8 2 see you w8ing1234 5678 9Output:i ate food beforegreat 2 see you w8ing1234 5678 9

Added by: Anil Kishore


Date: 2011-02-25
Time limit: 1s
Source limit:50000B
Languages: All
Resource: CodeMutants 2011 , DA-IICT, India

2
(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 (tutorial)

8437. MODULUS
Problem code: PROBLEM1
Problem1: MODULUS

Problem

Given an integer n print all the possibilities of a%n where a can be any positive integer.

Input

The first line consists of an integer t, the number of test cases followed by t lines containing an integer
n.

Output

For each test case print all the possibilities of a%n in descending order separated by a single space.
After each test case print a new line character. If there are no possibilities print "NOT POSSIBLE\n".

Input specifications:

0<t<=100

0<=N<=100

Time limit: 1 second

Example

Sample Input

1
Sample Output

10

Added by: cegprakash


Date: 2011-03-01
Time limit: 1s
Source limit:250B
Languages: All

2
(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 (tutorial)

8439. VijayAndAjith
Problem code: PROBLEM2
 

Problem2: Vijay & Ajith

Vijay and Ajith are close friends. They used to send messages to each other. They wanted privacy and
so they communicate in a different language which others can’t understand.  Simbu, the hacker learns
their language and cracks their messages. Being in the position of Simbu your task is to crack what
Vijay and Ajith communicates.

INPUT

The first lines consists of an positive integer t, the number of test cases followed by t lines. Each line
consists of two positive integers m and n which denotes the number of lines and the length of their
message.

OUTPUT

For each testcase print the message cracked by Mr.Simbu.

Input Speciffications:

1<=t<=100

1<=m<=100

1<=n<=100

Time constraint: 1 second

EXAMPLE

SAMPLE INPUT:

1
2

54

tnse

hrie

eina

ssts

ueht

22

bo

ok

SAMPLE OUTPUT:

thesunrisesintheeast

book

Added by: cegprakash


Date: 2011-03-01
Time limit: 1s
Source limit:50000B
Languages: AWK C C++ 4.3.2 C++ 4.0.0-8 JAVA SED

2
SPOJ Problem Set (tutorial)

8440. Problem 1
Problem code: NOVICE41
On a board on size N*N. Johar has placed N stones such that in every row and every column there is
exactly one stone. Moreover in every diagonal and anti diagonal there is at most one stone.Now
Kandarp want to check his solution because he does not trust Johar. So he want you to check whether
he has placed these N stones correctly or not.

Input
First line contains T, the number of test cases. then T test cases follow. First line of each test case
contains N (1<=N<=50) then each of next N lines contains an string of N characters. jth character of
ith string is ’#’ is there is an stone at position (i,j) otherwise it is ’.’.

Output
For each test case print YES if it is a valid arrangement or NO if it is invalid.

Example
Input:
22
3
..#
#..
.#.
4
.#..
...#
#...
..#.

Output:
NO
YES

Added by: Mahesh Chandra Sharma


Date: 2011-03-01
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own problem

1
SPOJ Problem Set (tutorial)

8441. Problem 2
Problem code: NOVICE42
 

This contest is based on brute force, and where better to apply this technique than in a day to day
newspaper game. Hemanshu Bansal has a knack for solving puzzles and he claims that he is very fast
always saying that he can solve the problem even before I can start to code. Help me beat him once in
for all in this famous game of Sudoku.
The objective of Su Doku puzzles is to replace the blanks in a 9 by 9 grid in such that each row,
column, and 3 by 3 box contains each of the digits 1 to 9.
You will be given a Sudoku puzzle and your program has to print its solution.

This contest is based on brute force, and where better to apply this technique than in a day to day
newspaper game. Hemanshu Bansal has a knack for solving puzzles and he claims that he is very fast
always saying that he can solve the problem even before I can start to code. Help me beat him once in
for all in this famous game of Sudoku. The objective of Su Doku puzzles is to replace the blanks in a
9 by 9 grid in such that each row, column, and 3 by 3 box contains each of the digits 1 to 9.

You will be given a Sudoku puzzle and your program has to print its solution.

Input
 

line 1:T(no. of test cases)

line 2: Grid 01

line 3-11: grid of 9x9

line 12: Grid 02

line 13-21: grid of 9x9

....

....

so on.

1
 

Output
 

line 1: Grid 01(should be same as input)

line 2-10: grid of 9x9(the solution)

line 11: <blank line>

line 12: Grid 02

.......

so on.

In case of multiple solutions print lexicographically minimum solution. Refer to wikipedia for the
definition of lexicographical order.

Example
Input:
2
Grid 01
003020600
900305001
001806400
008102900
700000008
006708200
002609500
800203009
005010300
Grid 02
200080300
060070084
030500209
000105408
000000000
402706000
301007040
720040060
004010003

Output:
Grid 01
483921657
967345821
251876493
548132976
729564138
136798245
372689514
814253769

2
695417382

Grid 02
245981376
169273584
837564219
976125438
513498627
482736951
391657842
728349165
654812793

Added by: Mahesh Chandra Sharma


Date: 2011-03-01
Time limit: 20s
Source limit:50000B
Languages: All

3
SPOJ Problem Set (tutorial)

8443. Problem 4
Problem code: NOVICE44
 

Piyush is a very inteligent chap, he has a facination for maths and is never convinced without proof of
anything. Last time I told him that sqrt(2) can be written as an expansion of a series as sqrt(2) = 1 +
1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
Now i need to prove this to him. Being a fan of finding all solutions i have descided to use a program
to find all possible fractions that can be formed using this series with depth = N and show it to piyush,
I need your help to do this.
example:
N=1 : 1 + 1/2 = 3/2
N=2 : 1 + 1/(2 + 1/2) = 7/5
N=3 : 1 + 1/(2 + 1/(2 + 1/2)) = 17/12
and so on...
Given a value of N(<=40) print the fraction in lowest form. Lowest form means that
GCD(numerator,denominator) = 1

Piyush is a very inteligent chap, he has a facination for maths and is never convinced without proof of
anything. Last time I told him that sqrt(2) can be written as an expansion of a series as sqrt(2) = 1 +
1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...

Now I need to prove this to him. Being a fan of finding all solutions I have descided to use a program
to find all possible fractions that can be formed using this series with depth = N and show it to piyush,
I need your help to do this.

example:

N=1 : 1 + 1/2 = 3/2

N=2 : 1 + 1/(2 + 1/2) = 7/5

N=3 : 1 + 1/(2 + 1/(2 + 1/2)) = 17/12

and so on...

Given a value of N(<=40) print the fraction in lowest form. Lowest form means that
GCD(numerator,denominator) = 1

Input
line 1: T(number of test cases)

1
line 2 to T+1: vaue of N for each test case

Output
numerator/denominator in the lowest form for each test case

Example
Input:
4
1
2
3
4

Output:
3/2
7/5
17/12
41/29

Added by: Mahesh Chandra Sharma


Date: 2011-03-01
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own problem

2
SPOJ Problem Set (tutorial)

8444. Problem 5
Problem code: NOVICE45
 

Mahesh and I are always at conflict, Where I am a lazy person who would rather apply bruteforce and
compute all possibilities of a problem to find the answer, he would rather solve it on paper to find a
mathematical formula and reduce computational time. Fed up of his daily taunts I formulated the
following problem, lets see who wins here bruteforce or mathematical precalculation:
Given two positive integers N and K you have to find the number of distinct ways of writing N as the
sum of integers(possibly only 1) in range of [1,K] (inclusive).
For example if N = 4 and K = 2, we have these 3 ways => (2+2), (2+1+1), (1+1+1+1).

Mahesh and I are always at conflict, Where I am a lazy person who would rather apply bruteforce and
compute all possibilities of a problem to find the answer, he would rather solve it on paper to find a
mathematical formula and reduce computational time. Fed up of his daily taunts I formulated the
following problem, lets see who wins here bruteforce or mathematical precalculation:

Given two positive integers N and K you have to find the number of distinct ways of writing N as the
sum of integers(possibly only 1) in range of [1,K] (inclusive).

For example if N = 4 and K = 2, we have these 3 ways => (2+2), (2+1+1), (1+1+1+1).

Input
 

Line 1: T(number of test cases)

Line 2 to T+1: 2 space seprated integers N,K. (1<=N<=10000 and 1<=K<=100) 

Output
1 line per test case telling the number of ways. Since the answer can be very large print it modulo
1000000007.

1
Example
Input:
3
1 10
2 1
4 2

Output:
1
1
3

Added by: Mahesh Chandra Sharma


Date: 2011-03-01
Time limit: 2s
Source limit:50000B
Languages: All
Resource: Own problem

2
SPOJ Problem Set (tutorial)

8450. C ONE
Problem code: C1
Write a C program to print "Hello World"

Output
Hello World

Example
Output:Hello World

Added by: styrofox


Date: 2011-03-03
Time limit: 1s
Source limit:50000B
Languages: C
Resource: C

1
SPOJ Problem Set (tutorial)

8455. C TWO
Problem code: CTWO
Write a C program to accept two consecutive numbers from the user and print their sum.

Input
The two numbers entered by the user.

Output
The sum of the numbers.

Example
Test Case 0Input:
1 2 Output:
3Test Case 1Input:2 3Output:5Test Case 2Input:3 4Output:7Test Case 3Input:5 6Output11

Added by: styrofox


Date: 2011-03-04
Time limit: 1s
Source limit:50000B
Languages: C C99 strict
Resource: C

1
(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 (tutorial)

8458. ALIGNSUBRACT
Problem code: PROBLEM5
Problem 5:  ALIGNSUBTRACT

Problem Statement:

Given an expression you’ve to print the result in the required format.

Input:

The first line is an integer t which denotes the number of test cases. Each test case consists of an
expression which has a number followed by ‘-‘  followed by another number(no space in between
them)

Output:

For each test case print the result as shown in the example test case. Your solution will not be accepted
even if you print an unnecessary trialing space. After printing the two numbers there should be a line
containing ‘-‘(dashes) which is equal to the maximum of number of non-space characters in the line
above it and below it. Everything should be right aligned. There is a blank line after each test case.

Input constraint:

Both numbers can have an at most of 100 characters.

Example:

Sample Input:

52345233-11111

9999-9999

82938-79934

Sample Output:

1
52345233

  -11111

--------

52334122

 9999

-9999

-----

 0

 82930

-79934

------

  2996

 To view the exact formatting see http://ideone.com/meGqK

Added by: cegprakash


Date: 2011-03-04
Time limit: 1s-3s
Source limit:50000B
Languages: AWK C C++ 4.3.2 C++ 4.0.0-8 JAVA SED

2
(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 (tutorial)

8459. AVERYEASYPROBLEM
Problem code: PROBLEM6
PROBLEM6:  AVERYEASYPROBLEM

Problem Statement:

Given two numbers a and b find the value of a!/b!

Input:

The first line consists of an integer t, the number of test cases. Then the next t lines consists of two
integers a and b.

Output:

For each test case print the value of factorial(a)/ factorial(b) provided b is always less than a.

Input Constraints:

1<=t<=100

0<=b<=a<=15

Example

Sample Input:

15 0

13 2

10

Sample Output:

1307674368000

1
3113510400

1
 

Added by: cegprakash


Date: 2011-03-04
Time limit: 2s
Source limit:200B
Languages: All

2
SPOJ Problem Set (classical)

8465. C THREE
Problem code: C3
Write a C program to accept any two numbers from the user and print their sum using a function.

Input
The two numbers entered by the user.

Output
The sum of the numbers calculated by the function

Example
  Test Case 0
Input:
1 3
Output:
4

Added by: styrofox


Date: 2011-03-05
Time limit: 1s
Source limit:50000B
Languages: C C99 strict
Resource: C

1
(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 (tutorial)

8468. AVERAGE
Problem code: AVG
Problem: AVERAGE

Problem Statement:

Given n numbers find the average of them.

Input:

The first line consists of an integer t, the number of test cases. Each test case consists of 2 lines. In
each test case the first line consists of an integer n, the count of numbers. The next line consists of n
integers.

Output:

For each test case print the average of the numbers without decimal places

Sample Input:

12345

211

Sample Output:

1
Added by: cegprakash
Date: 2011-03-06
Time limit: 1s
Source limit:50000B
Languages: AWK C C++ 4.3.2 C++ 4.0.0-8 JAVA SED

2
SPOJ Problem Set (tutorial)

8492. Intersecting Circles


Problem code: CIRCINT
 

Given two circles with centers at (x1, y1) and (x2,y2) and having radius r1 and r2 respectively, find if
they intersect or not. If two circles touch then they are considered to be intersecting.

Given two circles with centers at (x1, y1) and (x2,y2) and having radius r1 and r2 respectively, find if
they intersect or not. Two circles are considered to be intersecting if they have a common area. Even if
two circles touch at a point then they are considered to be intersecting.

Input

First line contains an integer T. Then follow T lines each line containing integers x1, y1, x2, y2, r1, r2
in that order.

Constraints:
T <= 10,000
All other integers will have an absolute value <= 1000,000,000

Output
Print "YES" (without quotes) if they intersect and "NO" if they don’t intersect.

Example
Input:
3
0 0 2 2 1 1
0 0 2 2 3 3
0 0 1000000000 0 600000000 400000000

Output:
NO
YES
YES

1
Added by: .:: Pratik ::.
Date: 2011-03-07
Time limit: 10s
Source limit:50000B
Languages: All

2
SPOJ Problem Set (tutorial)

8493. Colorful Blocks


Problem code: COLORF
 

Rith, the student of the month has received k sets of colored blocks. Each set is of a different color and
each block in a set is identical to any other block. Rith has n-types of colors and has a1, a2, a3 ... an
number of blocks for each color respectively. He arranges these blocks in a straight line, and wants to
know the number of ways he can arrange it. Please help him find out the number of ways. Oh and Rith
knows that this number will be very large, and hence asks you to find it modulo 1,000,000,009 (A
number modulo P is the remainder that is left after dividing that number by P)
For example if Rith has 2 types of colors and {a1,a2} = {1,2}
Then the following arrangemenets are possible
(Digit here means the color)
122
212
221
Hence the answer is 3.

Rith, the student of the month has received k sets of colored blocks. Each set is of a different color and
each block in a set is identical to any other block. Rith has n-types of colors and has a1, a2, a3 ... an
number of blocks for each color respectively. He arranges these blocks in a straight line, and wants to
know the number of ways he can arrange it. Please help him find out the number of ways. Oh and Rith
knows that this number will be very large, and hence asks you to find it modulo 1,000,000,009 (A
number modulo P is the remainder that is left after dividing that number by P)

For example if Rith has 2 types of colors and {a1,a2} = {1,2}

Then the following arrangemenets are possible

(Digit here means the color)

122

212

221

1
 

Hence the answer is 3.

Input
 

The first line contains an integer T, which is the number of test cases. Then there are T-test case blocks
which follow.

Each test-case block starts with an integer n, which is the number of types of colors.

The next line contains n-integers a1, a2, a3 ... an as described in the statement.

T <= 100

1 <= n <= 100

a1 + a2 + a3 .. + an <= 200,000

Output
Print the number of ways as described modulo 1,000,000,009

Example
Input:
3
2
1 2
3
1 1 1
5
200 200 200 200 200

Output:
3
6
706392408

2
Added by: .:: Pratik ::.
Date: 2011-03-07
Time limit: 12s
Source limit:50000B
Languages: All

3
SPOJ Problem Set (tutorial)

8494. Lucky Numbers


Problem code: LUCKYN
 

Shrek and Kung Fu Panda once met after having no forthcoming prequels. They quickly noticed that
both of them were superstitious and this helped them bond a lot.
Shrek believes that the number 4 is lucky and Kung Fu Panda believes that number 7 is lucky. You
being their friend want to list down numbers in increasing order that consist only of 4 or 7.
The first few elements of the list are 4, 7, 44, 47, 74, 77, 444 ... You must answer the n-th (1-based, 4
is the 1st term of the sequence)

Shrek and Kung Fu Panda once met after having no forthcoming prequels. They quickly noticed that
both of them were superstitious and this helped them bond a lot.

Shrek believes that the number 4 is lucky and Kung Fu Panda believes that number 7 is lucky. You
being their friend want to list down numbers in increasing order that consist only of 4 or 7.

The first few elements of the list are 4, 7, 44, 47, 74, 77, 444 ... You must answer the n-th (1-based, 4
is the 1st term of the sequence)

Input
 

The first line contains the number of test-cases T 

The following T-lines contains an integer n.

T <= 10,000

n <= 1000,000,000

Output
 

1
Print the n-th term in the sequence of lucky numbers

Example
Input:
6
1
20
300
4000
50000
1000000000

Output:
4
4747
44747747
77774744447
744447747474447
77477744774747744747444444447

Added by: .:: Pratik ::.


Date: 2011-03-07
Time limit: 8s
Source limit:50000B
Languages: All

2
(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 (tutorial)

8530. Skew Binary


Problem code: SKEWB
When a number is expressed in decimal, the k-th digit represents a multiple of 10 k . (Digits are
numbered from right to left, where the least significant digit is number 0.) For example, 

When a number is expressed in binary, the k-th digit represents a multiple of 2 k . For example, 

In skew binary, the k-th digit represents a multiple of 2 k+1  - 1. The only possible digits are 0 and 1,
except that the least-significant nonzero digit can be a 2. For example, 

The first 10 numbers in skew binary are 0, 1, 2, 10, 11, 12, 20, 100, 101, and 102. (Skew binary is
useful in some applications because it is possible to add 1 with at most one carry. However, this has
nothing to do with the current problem.)

Input
The input file contains one or more lines, each of which contains an integer

Output
For each number, output the decimal equivalent. The decimal value of n will be at most 2 31  - 1 =
2147483647.

1
 

Example
Input:

10120
200000000000000000000000000000
10
1000000000000000000000000000000
11
100
11111000001110000101101102000
0

Output:

44
2147483646
3
2147483647
4
7
1041110737

Added by: Coach UTN FRSF


Date: 2011-03-11
Time limit: 1s-4s
Source limit:50000B
Languages: All
Resource: (UVa ACM) http://online-judge.uva.es/p/v5/575.html

2
(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 (tutorial)

8749. Waiting for Easter


Problem code: TEASTER
Given a date, calculate the number of days until next Easter according to canonical (western) rule
using the Gregorian Calendar.

Input
First line of input is a positive integer t<100, the number of testcases. Each of the following t lines
contains a single date (1600<year<2100). The example below shows the date format.

Output
For every date print the number of days until next Easter.

Example
Input:
3
18 April 2011
27 February 1954
7 July 1777

Output:
6
50
286

Added by: numerix


Date: 2011-04-18
Time limit: 2s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: own problem

1
SPOJ Problem Set (tutorial)

8790. Find summits


Problem code: SUMMIT
Given an altitudinal map (0 <= altitudes <= 100000) find the summits i.e. all points which are bigger
than all their neighbours. There is at least one summit in each map.

Score is source length.

Input
The number n of maps (n<=50) in the first line.
Then for each map one line with its width w and heigth h (3<=w,h<=20) separated by a space. After
this the h rows of the map.

Output
The space-separated summits in ascending order.

Example
Input:
23 371034 8558 6594118265 1226 7407671003 75481 284463 322360 72964 4789175416 7746 8043295606 4613 83341

Output:
71034 7548183341 95606

Added by: HWK


Date: 2011-05-02
Time limit: 10s
Source limit:50000B
Languages: All

1
(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 (tutorial)

8792. N - DIGIT NUMBERS


Problem code: NDIGITS
How many n-digit whole numbers are there?

Input
The first line of input consists of an integer t denotes the number of testcases. Then for the next t lines
each line consists of an integer n. 

Output

For each n output the number of n-digit whole numbers.

Example

Input:

Output:

10

Input Specification:

1<=t<=100

1<=n<=1000

Added by: cegprakash


Date: 2011-05-03
Time limit: 1s
Source limit:50000B
Languages: All except: BF

1
SPOJ Problem Set (classical)

8847. Google is Feeling Lucky


Problem code: FEELUCK
Google is one of the most famous Internet search engines which hosts and develops a number of
Internet-based services and products. On its search engine website, an interesting button "I’m feeling
lucky"attracts our eyes. This feature could allow the user skip the search result page and goes directly
to the first ranked page. Amazing! It saves a lot of time.

The question is, when one types some keywords and presses "I’m feeling lucky" button, which web
page will appear? Google does a lot and comes up with excellent approaches to deal with it. In this
simplified problem, let us just consider that Google assigns every web page an integer-valued
relevance. The most related page will be chosen. If there is a tie, all the pages with the highest
relevance are possible to be chosen.

Your task is simple, given 10 web pages and their relevance. Just pick out all the possible candidates
which will be served to the user when "I’m feeling lucky".

Input
The input contains multiple test cases. The number of test cases is in the first line of the input file.

For each test case, there are 10 lines, describing the web page and the relevance. Each line contains a
character string without any blank characters denoting the URL of this web page and an integer V i
denoting the relevance of this web page. The length of the URL is between 1 and 100 inclusively. (1
<= V i <= 100)

Output
For each test case, output several lines which are the URLs of the web pages which are possible to be
chosen. The order of the URLs is the same as the input.

Please look at the sample output for further information of output format.

Example
Input:
2
www.youtube.com 1
www.google.com 2
www.google.com.hk 3
www.alibaba.com 10
www.taobao.com 5
www.bad.com 10
www.good.com 7
www.fudan.edu.cn 8
www.university.edu.cn 9
acm.university.edu.cn 10
www.youtube.com 1

1
www.google.com 2
www.google.com.hk 3
www.alibaba.com 11
www.taobao.com 5
www.bad.com 10
www.good.com 7
www.fudan.edu.cn 8
acm.university.edu.cn 9
acm.university.edu.cn 10

Output:
Case #1:
www.alibaba.com
www.bad.com
acm.university.edu.cn
Case #2:
www.alibaba.com

Added by: [Trichromatic] XilinX


Date: 2011-05-10
Time limit: 2s
Source limit:50000B
Languages: All
Resource: Fudan University Local Contest #2, by g201513

2
SPOJ Problem Set (tutorial)

8865. Brackets
Problem code: BRKTS
Your task is to determine if a sequence of opening and closing brackets is a valid expression. A valid
expression is one where every opening bracket has a corresponding closing bracket.

Input
The input consists of several test cases. The first line of the input is an integer 0< n < 500. n lines
follow, each one consisting of a sequence of brackets, which represents an expression.

Output
For each sequence in the input, print ":)" if the sequence is a valid expression, and ":(" otherwise.

Example
Input:
4{}}}{{{{{{{}{}}{}{{}}}}}Output:
:):(:):(

Added by: Simón Santiago Soriano Pérez


Date: 2011-05-12
Time limit:1s
Source
50000B
limit:
Languages:C++ 4.3.2 JAVA
Resource: https://docs.google.com/document/d/1WYMA9kda4g9zH7in5AsHjctKvkx8Nowc-V6FbMIpM_k/edit?hl=en&authkey=CMjAyJQO#

1
(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 (tutorial)

8897. Vadivu vs Kanth


Problem code: VKANTH

Problem Statement: Mr.Vadivu  has a decimal chemical. To kill Mr.Kanth, he creates a poison chemical by the following steps.For example if he has a decimal chemical A: 152Step 1: He converts it to a binary chemical BB:  10011000  (denoted by the index 0 to 7 from left to right)Step 2: Then he dilutes it into a poison chemical D such thatFor i in 0 to lengthD[i]=D[i-1]+B[i]  and  D[-1]=0In the above case  the poison isD: 11123333Mr.Vadivu mixed this poison in Mr.Kanth’s food and Mr.Kanth ate it. After he ate it Mr.Vadivu said Mr.Kanth, "Ha, you just ate the poison D. If you dont eat the anti-poison A, you will die"Assume you are Mr.Kanth and decide whether to die or not to die.INPUT:The first line consists of an integer t, denotes the number of test cases. Next t lines consists of poison chemicals D.(length of the poison chemical is <64 and D[i]<=9)OUTPUT:For each poison chemical D, print the anti-poison chemical A.EXAMPLE:Sample Input:411123333111222333344440000000112345555551111122222333334444455555Sample Output:1529352150417318416WARNING: note that the length of the poison chemical is < 64 .

Added by: cegprakash


Date: 2011-05-17
Time limit: 3s-4s
Source limit:50000B
Languages: All except: BF

1
(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 (tutorial)

8900. LUCKYNINE
Problem code: NITHY
 

Problem Statement:

  Mr.Nithyanandan likes number 9 very much. So he wanted to represent any number as a


sum of numbers ending with 9.

For example he represents

28 as 19+9

48 as 39+9  or  19+29

99 as 99 or 9+9+9+9+9+9+9+9+9+9+9  

But he wants to minimize the number of summations since he’s weak in mathematics.

INPUT:

 The first line consists of an integer t representing the number of test cases. Then for next t lines each
line consists of an integer n(0<=n<=10000).

OUTPUT:

For each test case output the minimum number of summations required. If it’s impossible to represent
then print Impossible

EXAMPLE:

1
SAMPLE INPUT:

28

48

99

15

1000

SAMPLE OUTPUT:

Impossible

10

Added by: cegprakash


Date: 2011-05-18
Time limit: 1s
Source limit:50000B
Languages: All except: BF

2
(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 (tutorial)

8901. BRAINF__K DESIGN


Problem code: BF

1
Problem statement:   Brainf**k is a programming language with only 8 symbols  {  ,.<>+-[] }. Ms.Sashwath thought of creating an OS with only 5 symbols among them { .<>+- }. In her language 0 refers to A, 1 refers to B and so on upto Z. The functionalities of the symbols are as followsInitially  i=0.   :   print the value at current i>  :  move one position right (i++)<   :  move one position left (i--)+   :  increment the value at current i-  :  decrement the value at current iIf any other character is found it is considered as a comment and is ignored.For example  ++++.>+++.<++.  will print "EDG"  Because initially i=0 and value at i=0.  Incrementing four times value at 0 becomes 4 which refers to E.Then position of i is incremented. i=1 and now value at 1 is incremented 3 times and D is printedAgain the position of i is decremented. i=0. Already the value at 0 is 4 and we further increment it twice.So it becomes 6 and it is printed as G.INPUT:The first line consists of an integer t, denotes the number of test cases. Then next t lines consists of a string of length <=100OUTPUT:For each test case print the required result in an individual line.EXAMPLE:SAMPLE INPUT:8+++++.++++.>>>>.+++.<<<+++.++.<++KKKHJKHKHJJLKJH12132.++++.++++.++.+...>>>.<+.HJ<+.>+.>+.+++.---.+-+->.<.++--+++.++++++++UIIU++-----.>...-+><><+..+++>++++.SAMPLE OUTPUT:FJADDFLEIKLLLABBCBDAAADFAAABAE WARNING: Note that you’ve to handle the comments (symbols other than the specified five symbols may present in the input case).

Added by: cegprakash


Date: 2011-05-18
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All except: AWK NODEJS SED

2
(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 (tutorial)

8903. DRAWING IT
Problem code: ARTIST
Problem Statement:

Write a code to print the following text..

?I love %s %d I|\|Formation SC/\iEnce And %%T?ech^&nology@!!2:D"

This is just to test how much u love your programming language.

INPUT:

There is no input.

OUTPUT:

?I love %s %d I|\|Formation SC/\iEnce And %%T?ech^&nology@!!2:D"

Note: Print including all the symbols

Added by: cegprakash


Date: 2011-05-19
Time limit: 1s
Source limit:300B
Languages: AWK C C++ 4.3.2 C++ 4.0.0-8 JAVA PERL PERL 6 PYTH 2.5 PYTH 3.1.2 SED

1
(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 (tutorial)

8911. FREE PATHS


Problem code: WAYS2

Problem Statement:Consider a block of m rows and n columns. At each step you can moveone step to the right or one step to bottom or one step to bottom-right.i.e.   if you are currently at (x,y)   : x-row, y-columnu can either move to (x,y+1) or (x+1,y) or (x+1,y+1) You’ve to find the number of possibilities to reach the point (A,B) from (0,0). Unluckily you cannot step into some places where bombs are placed denoted by "@". Input: The first line consists of 2 integers m and n denotes the number of rows and columns.Then the description of the m x n block is given.(‘0’- if the path is free to move and ‘@’-if the path has bombs and u cannot move to that place)Then an integer t follows which denotes the number of test cases.Then for next t lines each line consists of 2 integers A and B. Output:For each test case print the number of possibilities of reaching (A,B) from (0,0) in separate lines. Input Constraints:2<=m<=102<=n<=10m>A>=0n>B>=0 EXAMPLE:SAMPLE INPUT:3 6000@@@@@00@@@@000@80 10 41 32 32 41 22 22 5 SAMPLE OUTPUT:103710220 EXPLANATION OF THE TESTCASE:  From the figure clearly u can see that there are 3 paths to (1,3), 7 paths to (2,3), 10 paths to (2,4) and so..Note: if u can’t see the image clearly goto the following link:https://docs.google.com/uc?id=0B0rk3iRD6D_JYjAxMzAxNTEtYjU3YS00OWVhLWEyNzgtOWUzN2NmMmRmZDJh&export=download&authkey=CK-7vYoI&hl=en_US

Added by: cegprakash


Date: 2011-05-20
Time limit: 1s-3s
Source limit:50000B
Languages: All
Resource: own problem

1
(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 (tutorial)

8931. PATHS( no source code limit)


Problem code: WAYS3
Problem Statement:

Consider a square matrix of order m(m rows and m columns). At each step you can move one step to the right or one step to the top. How many possibilities are to reach (m,m) from (0,0)?

 Input:The first line consists of an integer t, the number of testcases.  Each testcase consists of a single integer m, the order of square matrix. Output:For each case print the number of possibilities of reaching the point (m,m) from (0,0) Input Constraints:1<=t<=101<=m<=14

Example:Sample Input:3123

Sample Output:

2620

Explanation of test case #2:

There are 6 possible ways of reaching (2,2) from (0,0)

Added by: cegprakash


Date: 2011-05-22
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (oi)

9015. FARMER
Problem code: LQDFARM
A farmer has a set of fields, each of which is surrounded by cypress trees. Also, the farmer has a set of
strips of land, each of which has a row of cypress trees. In both fields and strips, between every two
consecutive  cypress trees is a single olive tree. All of the farmer’s cypress trees either surround a
field or are in a strip and all of the farmer’s olive trees are between two consecutive cypress trees in a
field or in a strip.

One day the farmer became very ill and he felt that he was going to die. A few days before he passed
away he called his eldest son and told him, "I give you any Q cypress trees of your choice and all the
olive trees which are between any two consecutive cypress trees you have chosen."  >From each field
and from each strip the son can pick any combination of cypress trees. Since the eldest son loves
olives he wants to pick the Q cypress trees which will allow him to inherit as many olive trees as
possible.

In Figure 1, assume that the son is given Q=17 cypress trees. To maximize his olive inheritance he
should choose all the cypress trees in Field 1 and Field 2, inheriting 17 olive trees. 

You are to write a program which, given the information about the fields and the strips and the number
of cypress trees the son can pick, determines the largest possible number of olive trees the son may
inherit. 

1
INPUT 

The input file name is farmer.in. The first line contains first the integer Q: the number 

of cypress trees the son is to select; then the integer M, the number of fields; and then the integer K,
the number of strips. The second line contains M integers N1, N2,... NM, : the numbers of cypress trees
in  fields. The third line contains K integers R1, R2,... RK: the numbers of cypress trees in
strips. (0<=Q<=150000, 3<= Ni<=150, 2<= Ri<= 150)

OUTPUT 

The output file name is farmer.out. The file is to contain one line with one integer: the largest possible
number of olive trees the son may inherit. 

EXAMPLE INPUTS AND OUTPUTS 

Input                                    Output

17 3 3   17

13 4 8

486

Added by: qu-t!-r?poO


Date: 2011-06-11
Time limit: 0.300s-1.100s
Source limit:50000B
Languages: All except: CLOJ ERL F# GO PERL 6 PYTH 3.1.2 SCALA TCL
Resource: IOI 04

2
SPOJ Problem Set (classical)

9025. String Search


Problem code: STRINGS
A rectangular board with R rows and C columns is given. Each cell of the board contains an
alphabet.Now Q queries  are asked. In each query a word is provided and you have to identify the
word in the board. A word can be made by continuous alphabet cells on board in any direction. It is
not neccesary to follow a particular direction only... What this means is that cells may not lie on a
straight line and adjacent alphabets in given word must also be adjacent on the board.Each cell is
adjacent to all its neibhour cells (diagonally also).Also each cell is counted only once. You have to tell
starting and ending cell co-ordinates on the board for the given string. All coordinates in this problem
are 0-indexed and in the form (row, column).

Input
First line contains integers R and C ,number of rows and columns in the board.Following R lines with
C characters describes the board. Then next line contains an integer Q number of queries. Q lines
follows. Each line contains a string of alphabets.Input is such that it is possible to get a unique solution
within time contraints.

0<R,C<=20

0<Q<=30

String length<R*C.

Output
For each query output the starting and ending co-ordinates of the cells forming the string on the board
in the format (x1,y1) (x2,y2) ,where (x1,y1) and (x2,y2) are co-ordinates of the starting cell and
ending cell respectively.

If there are more than one solution then output that points for which distance between them is
minimum.

Example
Input:
4 44 4
acgt
tdtd
fcyy
ithc
2
catch
if
acgttdtd
fcyyInput:Input:Output:

1
(0,1) (3,2)
(3,0) (2,0)

Added by: Manohar Singh


Date: 2011-06-13
Time limit: 5s
Source limit:50000B
Languages: All
Resource: Manohar Singh

2
SPOJ Problem Set (classical)

9044. Magic Square!


Problem code: MAGICSQU
Given an nxn matrix, if it satisfy the next constraints it could be called a "Magic Square".

Constraints:

* The sum of the n rows, n columns and the two main diagonals of the matrix must be equal to the
same number m, called magic constant
* the n 2 positions of the matrix must contains natural numbers between 1 to n 2 , with no repetitions.

Input
Each test case consist in a natural number n (0 < n <= 20) denoting the matrix dimension. Then, the
next n 2 natural numbers will represent the values that initially contains the matrix.
For each position a ij (1 <= i,j <= n) of the matrix, we have:  0 <= a ij <= n 2 , for all ij.
A value of 0 in an initial position aij of the matrix means that you must find a number to complete that
place. A non-zero value means that you cannot change that value for the given position.

Output
For each case you must print the case number (starting from 1).
Then, in the next n lines you must print the magic square if exists or the phrase ’’No Solution’’
(without the quotes) if doesn’t exist a solution for the given initial configuration.
See the output example.
If for a given initial configuration exists more than one solution, you should give the lower one
assuming a lexicographic order. For lexicographic comparison you should consider lines in first place.
Print a blank line between test cases.

For example:
2 7 6    
9 5 1    
4 3 8    
it’s lexicographically before than:
438
951
276

1
Example
Input:38 0 00 0 00 0 021 10 0

Output:

Case #18 1 6 3 5 7 4 9 2 Case #2No Solution

Added by: Coach UTN FRSF


Date: 2011-06-17
Time limit: 3s
Source limit:50000B
Languages: All

2
SPOJ Problem Set (classical)

9067. Đông hô cát


Problem code: DHCAT
Ca?i tie^’n tu+‘ 1 bai thi UVA.

 Đông hô cát có da.ng 2 tam giác đe^‘u chung đi?nh, gôm 2n-1 dong. Lân lu+o+.t môi dong có n sô,
n-1 sô,....,1,2...,n sô (n<21). Môi ô o+? dong tren chi? có the^? di xuông ô pha?i du+o+’i ( R ) hoăc ô
trái du+o+’i ( L ).

YEU câu :

Tim đu+o+‘ng đi có tro.ng sô nho? nhât. Đu+o+‘ng đi đu+o+.c mô ta? la ô xuât phát o+? hang 1 ( các
ô đu+o+.c đánh sô tu+‘ 0 to+’i n-1 ) va chuôi LR mô ta? đu+o+‘ng đi.

Cho sô S<=5000, đe^’m sô đu+o+‘ng đi có tro.ng sô S va mô ta? đu+o+‘ng đi có thu+’ tu+. tu+‘
đie^?n nho? nhât u+’ng vo+’i S.

Input
Dong đâu tien la 2 sô n va S.    

2n-1 dong tie^’p theo sô a mô ta? đông hô cát. ( a<=5000)

Output

Gôm 4 dong : 

Tro.ng sô nho? nhât tu+‘ hang 1  to+’i hang cuôi .

Mô ta? đu+o+‘ng đi u+’ng vo+’i tro.ng sô nho? nhât ( ne^’u có nhie^‘u đu+o+‘ng đi, in ra đu+o+‘ng
đi có thu+’ tu+. tu+‘ đie^?n nho? nhât )

Sô đu+o+‘ng đi có tro.ng sô la S. Ne^’u không có đu+o+‘ng thi in ra -1.

Đu+o+‘ng đi u+’ng vo+’i tro.ng sô S tho?a man.

Example
Input:

3 17

1 2 3

4 5

1
6

5 4

3 2 1

Output:

16

0 RRRR

0 RRRL

Added by: battieudieu


Date: 2011-06-24
Time limit: 1s
Source limit:50000B
Languages: All

2
SPOJ Problem Set (tutorial)

9078. Graph basics concepts


Problem code: GRAPHS11
Description:

In this problem, your program will have to read a weighted graph (directed or non directed), and
perform some basic algorithms on the graph:

- Visualization of the graph (in the same format of the input)

- BFS traversal and show the paths from the node 1 (the root node), to the rest of the nodes.

- DFS traversal and show the paths from the node 1 (the root node), to the rest of the nodes.

- Visualization of connected components

- Visualization of bridges

Input
The graph to be read comes in several lines: in the first line, you will have a value d: 0 (if the graph is
a non directed graph), or 1 (if it is a directed one).

In the second line you will have a pair of numbers: n and e, the first is the quantity of nodes in the
graph, and the second is the quantity of edges in the graph.

Then, you will have e lines, with triplets: o, t and w, where o is the source node of an edge, t is the
target node, and w is the weight.

The triplets are ordered from the edges with origin at the root node (number 1), in an ascending way.
Also, if there are more than one edge starting from one node, they are ordered by target node.

The numbers of the nodes are consecutive: 1, 2, ...n

Output
You will have to show all the information in the list showed above (in the Description) section. Take
a look at the Example below to see the format to follow.

Example
Input:07 81 2 11 3 12 4 13 4 14 5 14 6 15 7 16 7 1Output:07 81 2 11 3 12 4 13 4 14 5 14 6 15 7 16 7 1BFS: 1 2 3 4 5 6 7BFS Paths:11 21 31 2 41 2 4 51 2 4 61 2 4 5 7DFS:1 2 4 3 5 7 6DFS Paths:11 21 2 4 31 2 41 2 4 51 2 4 5 7 61 2 4 5 7Connected Components:C1: 1 2 3 4 5 6 7Bridges:0

1
Added by: Coach UTN FRSF
Date: 2011-06-27
Time limit: 1s-2s
Source limit:50000B
Languages: All

2
SPOJ Problem Set (tutorial)

9082. Graph basics concepts


Problem code: GRAPHS12
Description:

In this problem, your program will have to read a weighted graph (directed or non directed), and
perform some basic algorithms on the graph:

- Visualization of the graph (in the same format of the input)

- BFS traversal and show the paths from the node 1 (the root node), to the rest of the nodes.

- DFS traversal and show the paths from the node 1 (the root node), to the rest of the nodes.

- Visualization of connected components

- Visualization of articulation vertices (the numbers of the vertices that are articulation points)

Input
The graph to be read comes in several lines: in the first line, you will have a value d: 0 (if the graph is
a non directed graph), or 1 (if it is a directed one).

In the second line you will have a pair of numbers: n and e, the first is the quantity of nodes in the
graph, and the second is the quantity of edges in the graph.

Then, you will have e lines, with triplets: o, t and w, where o is the source node of an edge, t is the
target node, and w is the weight.

The triplets are ordered from the edges with origin at the root node (number 1), in an ascending way.
Also, if there are more than one edge starting from one node, they are ordered by target node.

The numbers of the nodes are consecutive: 1, 2, ...n

Output
You will have to show all the information in the list showed above (in the Description) section. Take
a look at the Example below to see the format to follow.

Example
Input:07 81 2 11 3 12 4 13 4 14 5 14 6 15 7 16 7 1Output:07 81 2 11 3 12 4 13 4 14 5 14 6 15 7 16 7 1BFS: 1 2 3 4 5 6 7BFS Paths:11 21 31 2 41 2 4 51 2 4 61 2 4 5 7DFS:1 2 4 3 5 7 6DFS Paths:11 21 2 4 31 2 41 2 4 51 2 4 5 7 61 2 4 5 7Connected Components:C1: 1 2 3 4 5 6 7Articulation Vertices:4

1
Added by: Coach UTN FRSF
Date: 2011-06-28
Time limit: 1s-2s
Source limit:50000B
Languages: All

2
SPOJ Problem Set (classical)

9085. HIGH
Problem code: C11HIGH
Mô?t ngay "đe.p" tro+‘i no., Khánh nha ta đe?n thách đâ?u team ILS băng mô?t bai toán râ?t la... nhu+
sau:

Chie^‘u dai cu?a môt sô tu+. nhien la sô chu+~ sô cu?a sô đó. Đô cao cu?a môt sô tu+. nhien la tông
các chu+~ sô cu?a sô đó. Cho sô tu+. nhien x ghi trong he^. đe^’m 10, có chie^‘u dai 5. Tim sô tu+.
nhien y sát sau x có cung chie^‘u dai, cung đô cao va cung he^. đe^’m vo+’i x.

Tâ?t nhien, team ILS toan nhu+~ng cao thu? (late hero) nen vie?c gia?i bai toán tren không có gi la
khó khăn, ho. đa thách đô? la.i Khánh vo+’i gio+’i ha.n lo+’n ho+n râ?t nhie?u : vo+’i he? đe?m b va
sô? chu+~ sô? la 10 6  ??? Khánh ma không lam đu+o+.c thi che?t ngu+o+.c vo+’i bo.n nó chu+’ cha?
cho+i đâu, các ba.n giúp nhanh vo+’i không Khánh se~ bi. hô?i đô?ng trong 0,5s nu+~a :(

Input
Dong đâu tien: hai sô tu+. nhien b va N, 2 <= b <= 10, 2 <= N <= 10 6 .
Dong thu+’ hai: sô x

Output
Duy nhât sô y. Ne^’u không có nghie^.m ghi ra 0.

Example

Output:
24089

Added by: Nguye^~n Duy Khánh


Date: 2011-06-29
Time limit: 0.5s
Source limit:50000B
Languages: All
Resource: ILS

1
SPOJ Problem Set (tutorial)

9106. REARRANGE
Problem code: NOVICE61
Adam’s parents put up a sign that says "COMBINATORICS". The sign is so big that exactly one letter
fits on each panel. Some of Adam’s younger cousins got bored during the reception and decided to
rearrange the panels. How many unique ways can the panels be arranged (counting the original
arrangement)?

Input
First line contains a single integer T(less than 1000) denoting the total number of test cases.

Each test case contains a string S having atmost 15 characters from A to Z.

Output
For each word, output the number of unique ways that the letters can be rearranged (counting the
original arrangement). Use the format shown in Sample Output, below.

Example
Input:
3
HAPPY
WEDDING
ADAM

Output:
Case 1: 60
Case 2: 2520
Case 3: 12

Added by: amit karmakar


Date: 2011-07-02
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

9108. SHAKE
Problem code: NOVICE66
Consider a meeting of n businessmen sitting around a circular table. To start the meeting, they must
shake hands. We say that the shake is perfect if no arms cross each other and each businessman shakes
the hand of exactly one other businessman. All handshakes happen simultaneously.

Input
First line contains an integer T(less than 5000) denoting the total number of test cases.

Each test case consists of a single integer n(1 <= n <= 5000) in one line.

Output
For each tese case, print the number of perfect shakes that exist for n businessmen modulo
1000000007.

Example
Input:
1

Output:

Added by: amit karmakar


Date: 2011-07-03
Time limit: 3s-4s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

9109. NTH WORD


Problem code: NOVICE67
It is possible to number all the words that could be formed from a specified alphabet. One way to do it
is to put the words in order based on length, with words of common length ordered alphabetically.
Using this scheme, if we use the alphabet consisting of just the 3 letters ’a’, ’b’, and ’c’ then the words
are numbered:

1:a 2:b 3:c 4:aa 5:ab 6:ac 7:ba 8:bb etc.

There are an infinite number of possible words, but each has its own positive number. We want to be
able to find the word that corresponds to any given number N. The alphabet to be used is the first A
letters of the normal lowercase alphabet, with their usual alphabetical ordering.

Input
First line contains an integer T(less than 1000) denoting the total number of test cases. Each test case
consists of a single line of input having two integer A(2<=A<=26) and N(1<=N<=2000000000). 

Output
For each test case print the required string in a single line.

Example
Input:
2
3 13
26 2000000000

Output:
aaa
flhomvx

Added by: amit karmakar


Date: 2011-07-03
Time limit: 2s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

9110. TILE IT
Problem code: NOVICE68
In how many ways can you tile a 3xn rectangle with 2x1 dominoes? Here is a sample tiling of a 3x12
rectangle. Input consists of several test cases followed by a line containing -1. Each test case is a line
containing an integer 0 <= n <= 30. For each test case, output one integer number giving the number of
possible tilings.

SAMPLE INPUT
2
8
12
-1

SAMPLE OUTPUT
3
153
2131

Added by: amit karmakar


Date: 2011-07-03
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

9111. Prime Time


Problem code: NSUJ02A
Maria really loves prime times. In her definition, a time is called prime time, if both numbers in hour
and minute are primes. For example 07:11 is a prime time, since both of them are prime numbers, but
04:17 or 07:09 are not prime time.
You decided to write a bot that will call her in prime times, now you have to write a program that can
understand if a time is a prime time or not.

Input
First number in the input is t, number of test cases.
After that t lines will follow each with a time in hh:mm format, where hh will mean the hour and mm
will mean the minute. hh will be an integer within 0 to 23, and mm will be an integer within 0 to 59.

Output
Print "Yes" (without quotes) if it’s a prime time, "No" (without quotes) if it’s not.

Example
Input:
307:1104:1707:09

Output:
YesNoNo

Added by: Iqram Mahmud


Date: 2011-07-03
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own

1
SPOJ Problem Set (tutorial)

9113. Digibomb!
Problem code: NSUJ03C
Nayeem rushed to you with a sad, helpless look in his eyes. One part of his program needs to multiply
two integers and find the number of digit it has. Now the problem is these numbers can be very big - as
big as 18 digits. Everytime Nayeem tries to multiply them they overflow - since long long can only
handle numbers less then 2^63-1, which is roughly 19 digits.
Nayeem believes you are super smart and you can help him this time. Can you write him that part of
the program?

Input
First line will contain number of test cases t.
Each case will have two integers a and b. Both are less than 10^19.

Output
For each case output how many digits will be there in the product of a,b.

Example
Input:
4100 10010000 10000100000 1000001000000001804289383 1000000000846930886

Output:
591137

Added by: Iqram Mahmud


Date: 2011-07-03
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own

1
SPOJ Problem Set (tutorial)

9114. String Game


Problem code: NSUJ02D
Natasha is playing an innocent game since she is very very bored. She initially wrote a string that only
contains ’a’ or ’b’. After in each turn, that she replaces all the ’b’ with ’ab’ and all the ’a’ with ’b’.
For example if she starts with "abba". Next time she’d write "bababb", by replacing ’a’s with ’b’ and
’b’s with ’ab’. But in that way, after a while the string gets really really big. Now she wonders if she
does this work for n times, what would be the length of the string?

Input
First line contains number of test cases - t. After that t lines will follow, each will have an initial string
and n. You can assume the given string won’t have more than 100 characters and n will be a positive
integer not more than 50.

Output
For each case output the length of the string after n turns.

Example
Input:
3abba 1abba 2abbaabbababaabba 50
Output:
610426530329384

Added by: Iqram Mahmud


Date: 2011-07-03
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own

1
SPOJ Problem Set (tutorial)

9115. Prime Kitties


Problem code: NSUJ02E
In NumboLand, all the houses have kitties. The house numbered n will have a kitty of type k, if and
only if house k doesn’t have more than 1 type of kitty and the number n is divisible by k. For example
house 30 can only have kitties of type 2, 3 and 5. If you wonder why 1 is not there, note that house 1 is
the kitty playground and you can find all type of kitties there.
House 3 will have only kitty of type 3. Because 3 divides 3 and it’s not possible to have another type
of kitty in that house maintaining the criterias. Same thing is true for house 5,11,19. Euclid proved that
there are infinite number of houses who will have exactly one kitty. Everyone of NumboLand were
excited when he did that. They threw a BIG party for that!
The owner of house n wants to visit other houses with all his kitties. He will not go to any house that
has bigger number than his house. But there is a big problem, if he goes to any house that has the same
type of kitties that he has, they’ll start playing together and leave for kitty playground. And he doesn’t
want that to happen.
Can you tell the owner of house n, how many houses he can visit without having this incident?

Input
A single number t, number of test cases. After that there will be t lines, each containing one number n
(2<=n<=1000000).

Output
For each case, output how many houses that owner can visit without losing any of his kitties.

Example
Input:
523417100
Output:
0111539

Added by: Iqram Mahmud


Date: 2011-07-03
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

9173. Repetitions
Problem code: REPTTS

A sequence of words over alphabet is given. The length of longest word occuring as a
coherent fragment in every word given is to be found.

Input
In the first line of the standard input there is an integer , where is the number of words.
In each of the next lines there is one word formed from small letters of English alphabet
. The length of each word is at least , but not greater than .

Output
The text of standard output should consist of exactly one line containing a single integer equal to the
length of the longest word occuring as the coherent fragment in every word given.

Example
Input:

3
abcb
bca
acbc

Output: 2

Added by: Krzysztof Lewko


Date: 2011-07-13
Time limit: 1s
Source limit:50000B
Languages: All
Resource: VII POI

1
(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 (tutorial)

9333. Student Proxy


Problem code: AUCSE012
 

There are N students in a class.


All the students have different expertise in giving proxies(I hope this term is clear).
Precisely, we associate an integer P with every student which denotes the number of proxies he can
make. 
All students are capable of making proxies for any other student.A 

A Proxy in context of class attendance refers to the act when a student who is present in a class makes
attendance for a student who is absent in the same class.

There are N students in a class.

All the students have different expertise in giving proxies.

Precisely, we associate an integer P with every student which denotes the number of proxies he can
make. 

All students are capable of making proxies for any other student.

Input
 

First line contains an integer N(1 <= N <= 1000000) denoting the total number of students.

Then, N lines follow each containing an integer Ai(1 <= Ai <= 100). The integer Ai on the ith line
denotes the number of proxies that the ith student can make.

1
Output
 

Print the minimum number of students that can be present in the class such that by giving proxies the
recorded attendance can be 100%.

Example
Input:
5

Output:
2

Explanation, one possible solution is that the first and second student are present. Now first student
can give 1 proxy and second can give 2 proxies making the recorded attendance 5.

Added by: amit karmakar


Date: 2011-08-06
Time limit: 2s
Source limit:50000B
Languages: All

2
SPOJ Problem Set (tutorial)

9339. Contains Prime


Problem code: AUCSE015
We will try investigating if a number contains a prime within it.

Input
The first line contains an integer T(1 <= T <= 100) which denotes the number of test cases.

Each test case contains a single integer N(100 <= N <= 1000000000).

Output
For each test case print "YES" if its possible to choose a subsequence of length 3 of the number which
is a prime else print "NO" (without quotes).

Note: Consider the given number as a string of digits. So subsequences of this number refer to the
numbers that can be formed by deleting zero or more digits from the original number and
concatenating the left ones.

For eg,

Subsequence of 1234 having a length 3 are,

123

124

234

134

Example
Input:
2

141

1411856718567

Output:
NO

YES

1
For the second test case, we can choose the subsequences, 157, 167 etc which are prime

Added by: amit karmakar


Date: 2011-08-07
Time limit: 3s
Source limit:50000B
Languages: All

2
SPOJ Problem Set (classical)

9397. Memoria
Problem code: PS11F
You might have played the game called Memoria. In this game, there is a board consisting of N rows
containing M cells each. Each of the cells has a symbol on its back. Each symbol occurs on exactly
two cells on the board.

A move means turning a pair of cells one by one to see the symbols behind them. When the symbols
differ, both of the cells are turned on their faces, thus hiding the symbols again. The player should
remember the symbols. If the symbols on the backs of the turned cells coincide, the cells stay that way,
i.e., don’t turn back again. The player takes the last cell on the board, are declare to be the winner.

Alice and Bob are play Memoria on the ground, after several times, Alice found that for some N,M,
this game isn’t fair, Cause Alice Can’t calculate the ??, she asks Bob for help. But Bob can’t solve this
either.

So now is your turns. ..

Input
There is only one line contains two integers N and M as above ...

Output
Output the ?? for Alice , note that because Alice is a girl, so she always move first.

Example
Input 1:
2 2

Output 1:
1/3Input 2:
3 2

Output 1:
2/3

Added by: xiaodao


Date: 2011-08-16
Time limit: 1s
Source limit:50000B
Languages: All

1
(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 (tutorial)

9465. Spectrum of colours


Problem code: SPECTRUM
For a given x-coordinate find the RGB-colour in this spectrum of colours.

Score is source length.

Input
In the first line the number of test cases t<100. Then t lines with a x-coordinate (0<=x<=767).

Output
t lines with a colour #RRGGBB (0x00<=RR,GG,BB<=0xFF).

Example
Input:
30256767

Output:
#FF00FF#00FFFF#FF00FE

Added by: HWK


Date: 2011-08-28
Time limit: 10s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

9500. Bit counts


Problem code: BITCNTR
You are a detective working with Scotland Yard on a high-profile bank robbery case. The robber has
left some trails in the form of numbers, which you believe will give you important clues about the
robbery. Since you are genius, you know that the clues can obtained by converting the number in
binary and counting the number of 1’s. 

Input
The first line has a number t followed by t lines. Each line contains a number < 512.

Output
Output t lines corresponding to each number, such that each of the line contains the clue obtained from
the number.

Example
Input:
5231011

Output:
12103

Added by: Siddharth Kothari


Date: 2011-09-07
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own

1
SPOJ Problem Set (tutorial)

9501. Best balanced diet


Problem code: SETRR
Nutritionists have been struggling since a long time to determine what would constitute the best
balance diet. You are famous for your fine programming skills, and hence as a test to prove your
talent, you take up this challenge. You are given the nutrition value of all the possible items for
producing the best balanced diet. Your task is to figure out which of these items to use and which to
remove to produce the best balanced diet.

Input
The first line contains the number of items E. The next line contains E space separated integers, the
actual nutrition value of each of the items. Value of E <= 10. Each nutrition value is in the range of
[-2^31, 2^31).

Output
Output a single line in the following format "S N1 N2 .. NS", where S is the number of items in the
best balanced diet, and N1, .., NS are the nutrition values of each of these items.

Example
Input:
4-4 0 4 1

Output:
2 4 1

Added by: Siddharth Kothari


Date: 2011-09-07
Time limit: 1s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

9514. Parsing URL


Problem code: TETRSIGM
In computing, a Uniform Resource Locator or Universal Resource Locator (URL) is a character string
that specifies where a known resource is available on the Internet and the mechanism for retrieving it.

The syntax of a typical URL is:


scheme://domain:port/path?query_string#fragment_id

In this problem, the scheme, domain is required by all URL and other components are optional. That
is, for example, the following are all correct urls:
http://dict.bing.com.cn/#%E5%B0%8F%E6%95%B0%E7%82%B9
http://www.mariowiki.com/Mushroom
https://mail.google.com/mail/?shva=1#inbox
http://en.wikipedia.org/wiki/Bowser_(character)
ftp://fs.fudan.edu.cn/
telnet://bbs.fudan.edu.cn/
http://mail.bashu.cn:8080/BsOnline/

Your task is to find the domain for all given URLs.

Input
There are multiple test cases in this problem. The first line of input contains a single integer denoting
the number of test cases.

For each of test case, there is only one line contains a valid URL.

Output
For each test case, you should output the domain of the given URL.

Example
Input:
3
http://dict.bing.com.cn/#%E5%B0%8F%E6%95%B0%E7%82%B9
http://www.mariowiki.com/Mushroom
https://mail.google.com/mail/?shva=1#inbox

Output:
Case #1: dict.bing.com.cn
Case #2: www.mariowiki.com
Case #3: mail.google.com

1
Added by: [Trichromatic] XilinX
Date: 2011-09-08
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Fudan University Local Contest #3, by g201513

2
SPOJ Problem Set (classical)

9526. Department
Problem code: DEPART
The Department of Security has a new headquarters building. The building has several floors, and on
each floor there are rooms numbered xxyywhere yy stands for the room number and xx for the floor
number, 0 < xx, yy < 10. The building has ‘pater-noster’ elevator, i.e. elevator build up from several
cabins running all around. From time to time the agents must visit the headquarters. During their visit
they want to visit several rooms and in each room they want to stay for some time. Due to the security
reasons, there can be only one agent in the same room at the same time, The same rule applies to the
elevators. The visits are planned in the way ensuring they can be accomplished within one day. Each
agent visits the headquarters at most once a day.

Each agent enters the building at the 1st floor, passes the reception and then starts to visit the rooms
according to his/her list. Agents always visit the rooms by the increasing room numbers. The agents
form a linear hierarchy according to which they have assigned their one letter personal codes. The
agents with higher seniority have lexicographically smaller codes. No two agents have the same code.

If more then one agent want to enter a room, or an elevator, the agents have to form a queue. In each
queue, they always stand according to their codes. The higher the seniority of the agent, the closer to
the top of the queue he stands. Every 5 s (seconds) the first agent in the queue in front of the elevator
enters the elevator. After visiting the last room in the headquarters each agent uses if necessary
elevator to the first floor and exits the building.

The times necessary to move from a certain point in the headquarters to another are set as follows:
Entering the building, i.e. passing the reception and reaching the elevator, or a room on the first floor
takes 30 s. Exiting the building, i.e. stepping out of the elevator or a room on the first floor and passing
the reception takes also 30 s. On the same floor, the transfer from the elevator to the room (or to the
queue in front of the room), or from the room to the elevator (or to the queue in front of the elevator),
or from one room to another (or to the queue in front of the room) takes 10 s. The transfer from one
floor to the next floor above or below in an elevator takes 30 s. Write a program that determines time
course of agent’s visits in the headquarters.

Input
The input file contains the descriptions of   visits of different agents. The first line of the

description of each visit consists of agent’s one character code C, C =A   , ..., Z, and the time
when the agent enters the headquarters. The time is in the format HH:MM:SS (hours, minutes,
seconds). The next lines (there will be at least one) contain the room number, and the length of time
intended to stay in the room, time is in seconds. Each room is in a separate line. The list of rooms is
sorted according to the increasing room number. The list of rooms ends by the line containing 0. The
list of the descriptions of visits ends by the line containing the character dot.

1
 

Output
The output contains detailed records of each agent’s visit in the headquarters. For each agent, there
will be a block. Blocks are ordered in the order of increasing agent’s codes. The first line of a block
contains the code of agent. Next lines contain the starting and ending time (in format HH:MM:SS) and
the descriptions of his/her activity. Time data will be separated by one blank character. Description
will be separated from time by one blank character. Description will have a form Entry, Exit or
Message. The Message can be one of the following: Waiting in elevator queue,
Waiting in front of room RoomNumber, Transfer from room RoomNumber to
room RoomNumber,Transfer from elevator to room RoomNumber, transfer
from RoomNumber to elevator, Stay in room RoomNumber, Stay in elevator.
Print a blank line after each block.

Sample Input
A 10:00:00
0101 100
0110 50
0202 90
0205 50
0
B 10:01:00
0105 100
0201 5
0205 200
0
.

Sample Output
A
10:00:00 10:00:30 Entry
10:00:30 10:02:10 Stay in room 0101
10:02:10 10:02:20 Transfer from room 0101 to room 0110
10:02:20 10:03:10 Stay in room 0110
10:03:10 10:03:20 Transfer from room 0110 to elevator
10:03:20 10:03:50 Stay in elevator
10:03:50 10:04:00 Transfer from elevator to room 0202
10:04:00 10:05:30 Stay in room 0202
10:05:30 10:05:40 Transfer from room 0202 to room 0205
10:05:40 10:07:40 Waiting in front of room 0205
10:07:40 10:08:30 Stay in room 0205
10:08:30 10:08:40 Transfer from room 0205 to elevator
10:08:40 10:09:10 Stay in elevator
10:09:10 10:09:40 Exit

B
10:01:00 10:01:30 Entry
10:01:30 10:03:10 Stay in room 0105
10:03:10 10:03:20 Transfer from room 0105 to elevator

2
10:03:20 10:03:25 Waiting in elevator queue
10:03:25 10:03:55 Stay in elevator
10:03:55 10:04:05 Transfer from elevator to room 0201
10:04:05 10:04:10 Stay in room 0201
10:04:10 10:04:20 Transfer from room 0201 to room 0205
10:04:20 10:07:40 Stay in room 0205
10:07:40 10:07:50 Transfer from room 0205 to elevator
10:07:50 10:08:20 Stay in elevator
10:08:20 10:08:50 Exit

Added by: Andres Tellez


Date: 2011-09-12
Time limit: 1s
Source limit:50000B
Languages: All

3
SPOJ Problem Set (classical)

9530. Pipe
Problem code: PIPEJ
The GX Light Pipeline Company started to prepare bent pipes for the new transgalactic light pipeline.
During the design phase of the new pipe shape the company ran into the problem of determining how
far the light can reach inside each component of the pipe. Note that the material which the pipe is
made from is not transparent and not light reflecting.

Each pipe component consists of many straight pipes connected tightly together. For the programming
purposes, the company developed the description of each component as a sequence of points 
 , where   . These are the upper points

of the pipe contour. The bottom points of the pipe contour consist of points with y-coordinate
decreased by 1. To each upper point  there is a corresponding bottom

point   (see picture above). The company wants to find, for each pipe component, the

point with maximal x-coordinate that the light will reach. The light is emitted by a segment source
with endpoints   and  (  endpoints are emitting light too). Assume that the light

is not bent at the pipe bent points and the bent points do not stop the light beam.

Input
The input file contains several blocks each describing one pipe component. Each block starts with the
number of bent points   on separate line. Each of the next n lines contains a pair of

1
real values   separated by space. The last block is denoted with n = 0.

Output
The output file contains lines corresponding to blocks in input file. To each block in the input file there
is one line in the output file. Each such line contains either a real value, written with precision of two
decimal places, or the message Through all the pipe.. The real value is the desired
maximal x-coordinate of the point where the light can reach from the source for corresponding pipe
component. If this value equals to  , then the message Through all the pipe. will appear
in the output file.

Sample Input
4
0 1
2 2
4 1
6 4
6
0 1
2 -0.6
5 -4.45
7 -5.57
12 -10.8
17 -16.55
0

Sample Output
4.67
Through all the pipe.

Added by: Andres Tellez


Date: 2011-09-12
Time limit: 3s
Source limit:50000B
Languages: All

2
SPOJ Problem Set (classical)

9531. Sticks
Problem code: STIJ
George took sticks of the same length and cut them randomly until all parts became at most 50 units
long. Now he wants to return sticks to the original state, but he forgot how many sticks he had
originally and how long they were originally. Please help him and design a program which computes
the smallest possible original length of those sticks. All lengths expressed in units are integers greater
than zero.

Input
The input file contains blocks of 2 lines. The first line contains the number of sticks parts after cutting.
The second line contains the lengths of those parts separated by the space. The last line of the file
contains zero.

Output
The output file contains the smallest possible length of original sticks, one per line.

Sample Input
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0

Sample Output
6
5

Added by: Andres Tellez


Date: 2011-09-12
Time limit: 3s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (classical)

9533. Kindergarten Counting Game


Problem code: KINDJ
Everybody sit down in a circle. Ok. Listen to me carefully.

‘‘Woooooo, you scwewy wabbit!’’

Now, could someone tell me how many words I just said?

Input and Output


Input to your program will consist of a series of lines, each line containing multiple words (at least
one). A ‘‘word’’ is defined as a consecutive sequence of letters (upper and/or lower case).

Your program should output a word count for each line of input. Each word count should be printed on
a separate line.

Sample Input
Meep Meep!
I tot I taw a putty tat.
I did! I did! I did taw a putty tat.
Shsssssssssh ... I am hunting wabbits. Heh Heh Heh Heh ...

Sample Output
2
7
10
9

Added by: Andres Tellez


Date: 2011-09-12
Time limit: 3s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (tutorial)

9536. Calculating very big numbers very quickly


Problem code: MODPOW
Given numbers A, B, C, calculate (A to the power of B) mod C.

Input
The first line will contain an integer x, the number of test cases. x lines follow, each with three integers
A, B, and C, the A, B, and C mentioned above.

Conditions:

A is no more than 1e5

B is no more than 1e18

C is no more than 1e7

Output
For each test case, print (A^B) mod C.

Example
Input:
11 1 2Output:
1

Added by: hua


Date: 2011-09-12
Time limit: 8s
Source limit:50000B
Languages: All
Resource: Alex Anderson

1
SPOJ Problem Set (tutorial)

9573. Spot the largest string


Problem code: SPOTIT
 

Rat Ronnie is very intelligent. Recently she got interested in the binary number system. Seeing this Rat
Rocky decided to give her a problem to solve. If she solves it then she gets a big piece of cheese as a
prize :). 
A binary string of length N is a string that contains N characters. Each of these characters is either 0 or
1. Given a binary string S of length N and another input integer L, find a substring of length exactly L
whose decimal value is largest amongst all substrings of length L in S. Print this largest value. (See
notes and examples for further clarification)
Now Rat Ronnie is unable to think of anything else but cheese. As you are a brilliant programmer, she
wants you to solve the problem. She promises to share the piece of cheese if you succeed.

Rat Ronnie is very intelligent. Recently she got interested in the binary number system. Seeing this Rat
Rocky decided to give her a problem to solve. If she solves it then she gets a big piece of cheese as a
prize :). 

A binary string of length N is a string that contains N characters. Each of these characters is either 0 or
1. Given a binary string S of length N and another input integer L, find a substring of length exactly L
whose decimal value is largest amongst all substrings of length L in S. Print this largest value. (See
notes and examples for further clarification)

Now Rat Ronnie is unable to think of anything else but cheese. As you are a brilliant programmer, she
wants you to solve the problem. She promises to share the piece of cheese if you succeed.

Notes
A substring of a string S, is any contiguous sequence of characters in the string. For example,
"cde" is a substring of "abcdef" but "ce" is not a substring of "abcdef".

A value of a binary substring is the value after converting it to a decimal number. For example-
Decimal value of "1101" = (2^0)*1 + (2^1)*0 + (2^2)*1 + (2^3)*1 = 13

Input
 

The first line is T, the number of test cases.

T test case follows. The first line of every test case contains two integers N and L. The second line of
every test case contains a binary string of length N.

1
 

1<=T<=100

1<=N<=100

1<=L<=50

N>=L

Output
Output the maximum decimal value of the substring of length L. As the output may be large, use an
appropriate data type.

Example
Input:
3
7 3
0110111
5 3
10110
4 4
1000

Output:
7
6
8

Explanation of Example
In the second test case, possible substrings of length 3 are "101" , "011", "110" . Out of these, "110" has the highest value in decimal, i.e, 6.

Added by: Ishani Parekh


Date: 2011-09-22
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own

2
SPOJ Problem Set (tutorial)

9594. Count the strings


Problem code: NUMSTR
 

Alphabets made of cheese are available in the market these days. Rat Ronnie bought many alphabets
from the market. After placing these alphabets one after another in a straight line (i.e a string of
alphabets) Rat Ronnie went to sleep. 
Rat Rocky who is always hungry, ate some of the cheese alphabets and escaped. Now Rat Ronnie is
very furious. The string of alphabets that she had created was to be used in one of her science
experiments. She doesnt remember the original string anymore. All she remembers is that each
alphabet was a lower case english character. She wants you to find out the number of possible strings
that she could have formed before Rat Rocky ate some of the characters.
(SeeA letter is a lower case english alphabet (i.e it can be any symbol from ’a’ to ’z’).
Letters made of cheese are available in the market these days. Rat Ronnie bought many letters from
the market. After placing these letters one after another in a straight line (i.e a string of letters) Rat
Ronnie went to sleep. 
Rat Rocky who is always hungry, ate some of the cheese letters and escaped. Now Rat Ronnie is very
furious. The string of letters that she had created was to be used in one of her science experiments. She
doesnt remember the original string anymore. She wants you to find out the number of possible strings
that she could have formed before Rat Rocky ate some of the characters.
(See examples and Notes for more clarification)A letter is a lower case english alphabet (i.e it can be
any symbol from ’a’ to ’z’).
Letters made of cheese are available in the market these days. Rat Ronnie bought many letters from
the market. After placing these letters one after another in a straight line (i.e a string of letters) Rat
Ronnie went to sleep. 
Rat Rocky who is always hungry, ate some of the cheese letters and escaped. Now Rat Ronnie is very
furious. The string of letters that she had created was to be used in one of her science experiments. She
doesnt remember the original string anymore. She wants you to find out the number of possible strings
that she could have formed before Rat Rocky ate some of the characters.
(See examples and Notes for more clarification)

A letter is a lower case english alphabet (i.e it can be any symbol from ’a’ to ’z’).

Letters made of cheese are available in the market these days. Rat Ronnie bought many letters from
the market. After placing these letters one after another in a straight line (i.e a string of letters) Rat
Ronnie went to sleep. 

Rat Rocky who is always hungry, ate some of the cheese letters and escaped. Now Rat Ronnie is very
furious. The string of letters that she had created was to be used in one of her science experiments. She
doesnt remember the original string anymore. She wants you to find out the number of possible strings
that she could have formed before Rat Rocky ate some of the characters.

(See examples and Notes for more clarification)

1
Input
First line contains T , number of test cases. Next T lines will contain a string of characters which may
have any number of spaces anywhere in the string (including the beginning). The last character of the
input string will not be a space. Each input string terminates with a newline character.

A space in the input string denotes an unknown character (i.e a character that Rat Rocky ate)

T<=100

Each string will not exceed 100 characters.

Output
 For each test case output the number of strings that Rat Ronnie could have formed on a new line. As
the answer may be huge, output the answer modulo 10000007. 

Notes
 a modulo m : means the remainder after a is divided by m. It is also denoted by a%m.

If a,b are non negative integers, then the following hold

(a+b)%m = ( (a%m) + (b%m) )%m


(a*b)%m = ( (a%m) * (b%m) )%m

Example

Input:4abc dega cz d Output:12626676


ExplanationFor the first test case, as there are no spaces in the string, it is the only possible string Rat Ronnie could have written.For the third test case "a c" the middle character can be any of the lower case 26 english alphabets.

Added by: Ishani Parekh


Date: 2011-09-27
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own

2
SPOJ Problem Set (tutorial)

9595. Fast addition


Problem code: MEGAUSS
Your friend Wannabe_Gauss thinks he is quite fast at mathematics. When his teacher asked him to
find out whether the sum of all numbers in a given set of numbers was divisible by 2 or not, he
answered it all quite fast.

Annoyed by this, his teacher gives him a big list of such sets of numbers, and he realizes he is after all
a wannabe. He is relying on your programming prowess to get past this hurdle. Don’t disappoint him!

Input
A number t on the first line, showing number of test cases.
Each test case begins with a number n on first line showing number of numbers in that test case. The
next n lines contain one exactly one number each.

Output
T lines in output, one for each test case. "Y" if sum of that set is divisible by 2, else "N".

Example
Input:

3
2
1
2
4
1
2
3
4
3
1
2
2

Output:

N
Y
N

Constraints: 0 < t <= 50, 1 <= n <= 5000, each number is guaranteed to fit into a 32 bit integer.

1
Added by: Siddharth Kothari
Date: 2011-09-27
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Chinmay Modi

2
SPOJ Problem Set (tutorial)

9598. Get me correct


Problem code: GETCORR
We already know the answer to Life, the universe and everything. It’s the number 42. Now, we would
like to know if a set of numbers satisfy this answer or not. We say the set satisfies if all the members
of the set are divisible by this answer.

Input
There are going to be 6 members in the set to be tested. Each line specifies one member by an integer
which fits into 32-bits.

Output
Print "Yes" if it satisfies, "No" otherwise.

Example
Input:
42428401261764 

Output:
Yes

Added by: Siddharth Kothari


Date: 2011-09-28
Time limit: 1s
Source limit:50000B
Languages: All
Resource: own

1
(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 (tutorial)

9605. Warmup Problem A


Problem code: C2011AA
One of the trickiest problems in computer programming is sorting. You will spend hours of effort
trying to obtain a sort that runs both quickly and correctly. Sometimes the latter is challenging. Write a
program that determines if an input sequence is indeed sorted in ascending order.

Input Specification
On the first line of the input is [math]T[/math], the number of test cases. For each test case, the first
line is [math]N[/math], the number of list elements. [math]N[/math] elements follow, each an integer.

Output Specification
On a separate line for each test case, in order, output "PASS" if the input is indeed sorted in ascending
order; otherwise, output "FAIL".

Constraints
[math]0 \le T \le 100[/math]

[math]0 \le N \le 10000[/math]

Each integer is in the range of signed 32-bit integers.

Example Input
3
1
5
2
5
2
3
1
2
3

1
Example Output
PASS
FAIL
PASS

Explanation
Sequence #1 only has one element. It is trivially sorted. Sequence #2 is (5,2), which is sorted, but not
in ascending order. No number for Jakucha. Sequence #3 is (1, 2, 3). If you don’t think this is sorted,
you should probably not be participating in this class.

Added by: octalc0de


Date: 2011-09-29
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: self

2
SPOJ Problem Set (classical)

9639. Doing Nothing


Problem code: DONOTHIN
Original statement in spanish at
http://www.dc.uba.ar/events/icpc/download/problems/taip2011-problems.pdf

A young couple uses to make their time as productive as possible. This activity is quite stressful, so
they decided to "waste" some time watching their favorite TV series.

The series has N seasons, and each season has a possibly different number of chapters according to its
success, actors availability, production time and other external factors. Each chapter has a duration of
exactly M minutes.

To keep up with the plot, before watching each new season, they watch, without any rest, all the
chapters of all the previous seasons. This has just made them concern about how much time they will
be spending with this hobby, which should keep them calm. They need your help so they don’t get
back to the stressful situation they had.

Input
The input contains several test cases. Each test case is described in two lines. The first line has two
integers N and M representing respectively how many seasons the series has and the duration in
minutes of each chapter (1 <= N <= 10 5 , 1 <= M <= 10 6 ). The next line has N integers C_i
representing how many chapters each season has sorted chronologically. (1 <= C_i <= 100 for 1 <= i
<= N). The last line of the input contains the number -1 twice and should not be processed as a test
case.

Output
For each test case output a single line with an integer representing the number of minutes the couple
spends in watching the whole series.

Example
Input:
6 20
24 23 15 22 24 17
1 100
100
10 1000000
99 99 99 99 99 99 99 99 99 99
-1 -1

Output:

1
9000
10000
5445000000

Added by: Pablo Ariel Heiber


Date: 2011-10-04
Time limit: 4s
Source limit:50000B
Languages: All
Resource: Argentinian Programming Tournament 2011

2
SPOJ Problem Set (classical)

9654. Prime Count


Problem code: PCOUNT
How many primes are there between 1 and n where 1<=n<=10^8. Remember that 1 is not prime.

Input
The number n.

Output
Output the number of primes between 1 and n (inclusive).

Example
Input: 5 Output: 3

Added by: Paul Draper


Date: 2011-10-06
Time limit: 0.5s-10s
Source limit:50000B
Languages: All

1
SPOJ Problem Set (classical)

9682. Bí hie^?m
Problem code: RIDDLE
Ba cu?a Ellenora thu+o+‘ng ra cho cháu gái minh nhu+~ng bai toán đô ma Elly coi la bí hie^?m. Buôi
tôi vu+‘a rôi ba đô Elly bai toán sau:

"O+? cu+?a hang ca.nh nha ta có k măt hang vo+’i giá khác nhau tu+‘ 1 đe^’n k. Ba có n đông
tie^‘n me^.nh giá a 1 , a 2 , . . ., a n . Ba đi.nh sang ben đây mua môt măt hang nao đó, tra? đúng giá
cu?a nó ma không pha?i nhân la.i tie^‘n thu+‘a. Nhu+ng ba đa gia quá rôi. Ba không muôn mang tât
ca? tie^‘n cu?a minh đi, có the^? lân hoăc ro+i mât, vi vây ba chi? mang theo môt sô đông đâu tien.
Vây ba pha?i mang theo ít nhât bao nhieu đông tie^‘n đe^? mua đu+o+.c măt hang bât ky‘?"

Chi? mât vai giây Elly đa đu+a ra đu+o+.c câu tra? lo+‘i va nghi thâm trong bu.ng: "Ôi, ba o+i, la.i
nhu+~ng bai toán gia?i thuât quá chuân!".

Ba.n có the^? đua tai vo+’i Elly băng cách vie^’t chu+o+ng trinh gia?i bai toán nay đu+o+.c không?

Du+~ lie^.u: Vao tu+‘ file văn ba?n RIDDLE.INP:

Dong đâu tien chu+’a sô nguyen T - sô lu+o+.ng tests trong file,


Môi test cho tren 2 dong:
Dong thu+’ nhât chu+’a 2 sô nguyen n va k (1 <= n <= 10 5 , 1 <= k <= 10 6 ),
Dong thu+’ 2 chu+’a n sô nguyen a 1 , a 2 , . . ., a n , (0 < ai <= 10 5 , "i = 1 ÷ n).

Ke^’t qua?: Đu+a ra file văn ba?n RIDDLE.OUT, ke^’t qua? môi test đu+a ra tren môt dong du+o+’i
da.ng sô nguyen. Ne^’u không có cách mang thi đu+a ra sô -1.

Ví du.:

RIDDLE.INP  RIDDLE.OUT
3   4

7 10 3

1234567 -1 

33

241

36

3 1 4 

1
Added by: Nguye^~n Duy Khánh
Date: 2011-10-09
Time limit: 1s
Source limit:50000B
Languages: All

2
(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 (tutorial)

9716. Binary Palindromes Set


Problem code: BINPALI
 

Write a program to find out all the numbers whose binary value is a palindrome . Your input will be
the number of test cases and for each test case the range of numbers to check for palindrome i.e. the
start and end value of the range. Your output will display all the numbers whose binary value is a
palindrome. One line of output for each test case.

Given two integers A and B, write a program to find out all the numbers whose binary value is a
palindrome in that range. Your input will be the range of numbers to check for palindrome i.e. the start
and end value of the range. Your output will display all the numbers whose binary value is a
palindrome. It is also important to note that you shall treat a binary number as palindrome, only while
considering the minimum no of bits required to represent the number. In other words, ignore all
leading zeros. E.g. 6, which can be represented as 0110 is not a palindrome, because if you ignore the
leading zeroes, you have only 110.

Input
First line of input is no. of test cases T. T lines of input follow, each having 2 integers A and B. A and
B denote the upper and lower limit of your range (both inclusive) for the problem.

0<=T<=10000

0<=A,B<=2147483647

Output
For each test case, print it’s output in a new line. When there are more than 1 integers in the answer,
print them separated by a single space in ascending order. If there is no answer, just print "none".

1
(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 (tutorial)

9816. Lake of the dead


Problem code: WPC4B
Mario is falling into a valley with a lake of fire at the bottom. The lake has a number of islands where
Mario can stand without getting burnt. There are k islands in total. Mario has n objects that act as a
source of power, whereas m objects that act as a sink for power. He sees a troop of enemies advancing
towards him. He wants to place those objects, such that there is at most one object on any island. Also,
two islands are said to be connected if Mario is able to directly jump from one to another.

It is constrained that he must be able to directly jump from an island having a source to each island
having the sink. You need to find the number of such arrangements.

Input
First line contains integers n and second line contains integer m. (1 <= n,m <= 8)
Third line contains k, the number of islands (1 <= k <= 30)
The next k lines contain a string of k characters, representing which of the islands are connected
Each element of the string is Y or N.
Character i of jth string is Y if islands i and j are connected. Hence, character j of ith string will also be
Y.
Also ith character of ith string is always N.
Output
Number of possible ways of placing the objects.
Sample I/O
Input
2
1
3
NYY
YNY
YYN

Output
3

1
Added by: Walrus
Date: 2011-10-24
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: Local Contest: WPC 4

2
(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 (tutorial)

10174. Túi Fibonacci


Problem code: QTKNAP
He vu+‘a rôi các ba.n tru+o+‘ng xyz tô chu+’c môt buôi đi cho+i va tham quan o+? môt đi.a đie^?m
đó la ...... Sa-ha-ra (sa ma.c lo+’n nhât the^’ gio+’i) đe^? tim hie^?u ve^‘ các đi.a danh tren the^’
gio+’i. Tro+‘i rât nóng bu+’c nen các ba.n đe^‘u khát nu+o+’c, vi vây môt sô ba.n quye^’t đi.nh đi tim
nu+o+’c, va may măn ho. đa tim thây môt ôc đa?o. Tuy nhien ôc đa?o ây la.i không có nu+o+’c ma
thay vao đó la môt kho báu cu?a Paraong đe^? la.i. Trong kho báu đó có rât nhie^‘u loa.i nhu+ vang,
ba.c, đa quý, kim cu+o+ng,....(nhu+~ng vât có giá tri.) hoăc đá, so?i, cát,..(nhu+ng vât không có giá
tri.). Vi su+. to mo các ba.n ây đa quye^’t đi.nh trôm môt ít ve^‘. Tuy nhien ho. chi? có 1 cái túi rât
"bé" nen chi? chu+’a đc môt sô lu+o+.ng kho báu nhât đi.nh. Va các ba.n ây đang cô tính toán xem
cân pha?i lây lam sao đe^? đu+o+.c giá tri. la lo+’n nhât. Đie^‘u đăc bie^.t o+? đây la ai câp rât gio?i
ve^‘ toán ho.c nen khôi lu+o+.ng cu?a các vât trong kho báu đe^‘u la môt sô fibonacci. Ne^’u la ba.n,
ba.n se~ tính đu+o+.c không ???

Yeu câu: cho khôi lu+o+.ng lo+’n nhât có the^? bo? vao túi, khôi lu+o+.ng va giá tri. cu?a các vât
trong kho báu ( các vât rât cu+’ng va không the^? đâp be^? ra ma pha?i tro.n nguyen ca? vât ). Hay
tính giá tri. lo+’n nhât ma các ba.n ây có đu+o+.c.

Input
Dong đâu tien: N (sô loa.i vât trong kho báu), M (khôi lu+o+.ng lo+’n nhât có the^? bo? vao túi):
N<=70, 0<=M<=10 16 .

Dong thu+’ i trong N dong tie^’p theo gôm 2 sô: W i (khôi lu+o+.ng cu?a vât trong kho báu), V i  (giá
tri. cu?a vât): 0<=W i <=10 16 , 0<=V i <=10 16 .

Output
Môt dong duy nhât la giá tri. lo+’n nhât có the^? lây đu+o+.c.

Example
Input:
3 163 16

5 10

8 15

1
13 20
Output:
25

Lu+u ý:

Added by: Pig Yellow


Date: 2011-12-05
Time limit: 0.5s
Source
50000B
limit:
Cluster: Pyramid (Intel Pentium III 733 MHz)
AWK C C# C++ 4.3.2 C++ 4.0.0-8 JAR JAVA NODEJS PAS fpc PAS gpc PYTH 3.2.3
Languages:
n SED
Resource: Trân Tú Nam - Khóa 8

2
(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 (tutorial)

10198. Tro cho+i 0 1


Problem code: QTBIT
Happy my birthday ^.^ 09/12/1995

Cho môt day nhi. phân đô dai N nguyen (1<=N<=1000). Xét tro cho+i giu+~a hai ngu+o+‘i nhu+ sau:
đe^’n lu+o+.t minh, ngu+o+‘i cho+i xóa K sô 1 lien tie^’p nhau trong day (1<=k<=10). Tro cho+i
ke^’t thúc khi có môt ngu+o+‘i không the^? xóa đu+o+.c nu+~a, đó la ngu+o+‘i thua cuôc.

Lu+u ý: Ne^’u nhu+ ngay ta.i bu+o+’c đâu ngu+o+‘i cho+i sô 1 đa không xóa đu+o+.c thi xem nhu+
la ngu+o+‘i thua cuôc va tro cho+i ke^’t thúc.

Yeu câu: Xác đi.nh xem ai chăc chăn la ngu+o+‘i thăng cuôc. Bie^’t mo.i nu+o+’c đi đe^‘u la tôi u+u.

Input
Dong đâu tien la sô nguyen du+o+ng T - sô test (1<=T<=100).

T căp dong tie^’p theo gôm :

- Dong thu+’ nhât la sô K.

- Dong thu+’ hai la xâu bie^?u die^~n day nhi. phân.

Output
Gôm T dong môi dong ghi ra ngu+o+‘i chie^’n thăng (1 hoăc 2) cu?a test đó.

Example
Input:
2

0011101101

11111111111

Output:
2

1
1

Added by: Pig Yellow


Date: 2011-12-12
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: AWK C C# C++ 4.3.2 C++ 4.0.0-8 JAR JAVA NODEJS PAS gpc PAS fpc SED
Resource: Trân Tú Nam - Khóa 8

2
(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 (tutorial)

10208. Overestimate
Problem code: OVFL
Mr. M and Mr. O are discussing putting a problem. They found that the effort to write a problem is a *
b + c for some a,b,c. Since, Mr. O is evil, he wants to maximize the effort that Mr. M will do writing
the problems.

help Mr. O to do this

Input
Given a, b and c (0 <= a, b, c <= 1,000,000) Find an ordering for them such that a * b + c is maximum.

Output
The maximum effort Mr M can do.

Example
Input:2 3 4Output:
14
Explanation of sample input:There are 6 different ways to order the numbers2 * 3 + 4 2 * 4 + 3 3 * 2 + 4 3 * 4 + 2 4 * 2 + 3 4 * 3 + 2But the max value we can reach is 14 which can be achieved by 3 * 4 + 2

Added by: Omar ElAzazy


Date: 2011-12-13
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own Problem

1
(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 (tutorial)

10209. Theory of Computation


Problem code: STRSPL
One day M and O were attedning a Theory of Computation lecture when Dr H asked: "What is the
maximum number of consecutive 1s in the following binary string ?". Of course, that was an
introduction to some turing machine related problem. Now M and O wonders how to solve that.

A binary string is a string formed only of 0s and 1s.

Input
A binary string split on several lines, concatenate all the lines to get the input which will be of a length
N (1 <= N <= 100).

Output
The maximum number of consecutive 1s.

Example
Input:
111100101011111

Output:
5

Added by: Omar ElAzazy


Date: 2011-12-13
Time limit: 2s
Source limit:50000B
Languages: All
Resource: Own Problem

1
(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 (tutorial)

10324. Rock-paper-scissors I
Problem code: JANKEN
You play the game of rock-paper-scissors (for those who don’t know it, you and your opponent show
signs of rock/paper/scissors at the same time; rock beats scissors, scissors beat paper and paper beats
rock; you score a point if your sign beats the opponent’s signs) against a little kid. The winner is the
first one to gain 3 points. Kids usually play in a simple manner - they think that they randomly choose
either of the signs, but experience shows that unconsciously, people tend to choose scissors most often
for the first game (a ’game’ here is showing one sign and possibly getting one point, not a sequence of
showing signs until one of you gets 3 points). Other than that, the kid’s choice is random.

So, you get a sequence of last N<=1000000 games (note that, by definition, it’s possible for no one to
score a point during a game), and have to choose the sign you have to show to have the greatest chance
of winning the next game.

You can assume there will be only one best choice (the one when you’re most likely to win the next
game), and that no one has scored 3 points yet in this game.

Input
On the first line, there is the number of test cases (t <= 10). For every test case, there is a number N,
and N lines, each containing your sign and your opponent’s sign from one past game.

Output
Read out a string, which is this time strictly from the set {"rock","paper","scissors"}, denoting your
sign for the next game.

Example
Input:
10

Output:
rock(obviously, if your opponent is most likely to start with scissors, you want to start with rock)

Added by: Jakub Šafin


Date: 2012-01-02
Time limit: 1s
Source limit:50000B
Languages: All
Resource: alcohol brings inspiration

1
(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 (tutorial)

10333. DIFFICULT INTERVIEW


Problem code: DIFFICUL
 

DIFFICULT INTERVIEW

Interviewer: Tell me about yourself

Student: I’m so and so.. bla bla bla.. I do have 6.2 cgpa with 10 current arrears

Interviewer: Tell me about your achievements

Student: Actually I’ve achieved nothing so far except getting selected for this interview

Interviewer: What are your hobbies?

Student: Uh.. Films, songs, roaming, being in facebook..

Interviewer: What kind of software are you familiar with?

Student: Hmm.. I’m good at MS word and MS paint and a little excel

Interviewer: Do you know something in Programming and Data Structures?

Student: Yeah.. They taught me some sorting algorithms..

Interviewer: Just sort the given strings and get into our company.

Input Specification:

The first line consists of an integer n, the no. of strings followed by n lines with one
string(1<=length<=12) in each line.

Output Specification:

Just print the sorted order of strings one per line.


Input constraints:

 1<=n<=500000

1
Sample Input:

apple

mango

banana

orange

Sample Output:

apple

banana

mango

orange

Added by: cegprakash


Date: 2012-01-03
Time limit: 15s
Source limit:50000B
Languages: All

2
(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 (tutorial)

10347. Roman Numerals


Problem code: ROMANN
One day, Eloy the byte was helping his son with his homework... The homework consist in a list of
roman numerals that you should convert to arabic numbers. Eloy doesn’t remember very much of the
transformations, and he is very confused. He wants help! Now, the task is simple: Build a program that
given a list of Roman Numerals, output the equivalent on arabic numbers.

Eloy knows that each letter means:

I=1

V=5

X = 10

L = 50

C = 100

D = 500

M = 1000

INPUT:

The first line of the input will be an integer K (1<=K<=1000) representing the number of test cases of
the program, then, the next K lines will consist in a VALID Roman Numeral. (that means a string with
capital letters)

OUTPUT:

Will consist of K lines denoting the equivalent in arabic number of the given string with the following
system: "Case #i: tk" where i is the test case number starting with 1 and tk is the transformation of the
i-th number.

1
SAMPLE:

Input:

XLVIII

MDCLXVI

Output:

Case #1: 10

Case #2: 48

Case #3: 1666

Added by: David Moran


Date: 2012-01-06
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own Problem

2
(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 (tutorial)

10359. How many words(SHELL)


Problem code: QWERTY01

How many times(SHELL)


Problem Statement:

You are provided with a word to search. You have to search how many times that word appears in the
given list of words.

Input Specification:

The first line contains a word which should be searched. Then the words in the list are provided one
per line. "end" denotes the end of the list.

Output Specification:

Just print the number of occurances of the searched word in the given list

Input Constraints:

Length of any word <=30

Number of words in the search list <=100

The word to search != "end"

Sample Input:

i++

i++

1
is

awesome

i++

is

amazing

love

i++

end

Output:

Added by: cegprakash


Date: 2012-01-09
Time limit: 1s
Source limit:500B
Languages: BASH

2
(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 (tutorial)

10360. BF writing
Problem code: QWERTY02

BF WRITING
Problem Statement:

If you love brainf**k then prove yourself by printing "I love Brainf**k"

Output:

I love Brainf**k

Added by: cegprakash


Date: 2012-01-09
Time limit: 1s
Source limit:500B
Languages: BF

1
(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 (tutorial)

10361. JAVA COUNTING


Problem code: QWERTY03

Java counting
Problem Statement:

You are given a list of characters in English alphabets (ASCII>=97). Sort the characters and give the
number of occurrences of every character.

Input Specification:

The first line contains an integer n, the number of characters, followed by n lines with a character in
every line.

Output Specification:

Print the characters in sorted order with no duplicates.

Output format : "character < space > no_of_occurances"

Input Constraints:

1<=n<=100

Sample Input:

1
Sample Output:

a2

b1

f2

Added by: cegprakash


Date: 2012-01-09
Time limit: 1s
Source limit:500B
Languages: JAVA

2
(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 (tutorial)

10362. TRIVIADOR
Problem code: QWERTY04
TRIVIADOR

Triviador is a war between two Kings. A king can attack an enemy region at each step. When a king
attacks a region, he conquers all the enemy regions connected to it. Every region is connected to the
region immediately next or previous to it. The kings get alternate chances to attack. King1 gets the
chance to attack first. Assume both kings are intelligent and find who will conquer the whole territory
at the end of the war. It can be proved that one of the Kings can win for sure if he is intelligent!

Input Specification:

The first line is an integer t, denotes the number of test cases. In each test case the first line consists
one integers denoting the number of regions in the territory. Then the description of each cell follows.
Every region contains a character ‘X’ if it is owned by king1 or ‘O’ otherwise.
Output Specification:
For each test case output the result in a single line ‘X’ if king1 wins or ‘O’ if king2 wins.

Input Constraints:

T<=100

1<=regions<=100

Sample input:

1
XXXXOOOO

OXOXXXXO

XOXOXOXO

Sample Output:

Added by: cegprakash


Date: 2012-01-09
Time limit: 1s
Source limit:1000B
Languages: All

2
(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 (tutorial)

10364. TREE SHAPES


Problem code: CODEIT01
TREE SHAPES

Problem Statement:

Given n, the number of nodes, find the number of different possible binary trees that can be
constructed. A tree differs from another tree if it’s shape looks different.

Input Specification:

The first line is an integer t, denoting the number of test cases. Then each test case consists of one
integer n, the number of nodes.

Output Specification:

For each test case print the number of possible trees that can be constructed using n nodes in a separate
line.

Print the answer mod 10^9+7.

Input Constraints:

1<=t<=100

1<=n<=50

Image link:
https://docs.google.com/leaf?id=0B0rk3iRD6D_JOGNmMGFmNTEtYmZhNC00NDgxLWEyNjYtYTQxNDllNjA0YzZm&hl=en_US

Sample Input:

1
2

Sample Output:

14

Added by: cegprakash


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

2
(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 (tutorial)

10365. PICK UP DROP ESCAPE


Problem code: CODEIT02
PICK UP DROP ESCAPE

You are given with an array of n numbers. You must pick K elements from the array such that XOR of
all the chosen elements is maximum.

http://en.wikipedia.org/wiki/Bitwise_operation#XOR

Input Specification:

The first line consists of an integer t representing the number of test cases. For each test case the first
line consists of two numbers n and K denoting the number of elements in the array and the number of
elements to be chosen respectively. Then in the next n lines, the elements in the array are given.

Output Specification:

For each test case print a line containing one integer denoting the maximum XOR value of the chosen
K elements.

Input Constraints:

1<=t<=100

1<=n<=25

1<=k<=n

1<=element value<=10000

Sample Input:

1
53

53

Sample Output:

Added by: cegprakash


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

2
(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 (tutorial)

10379. Number Divisiblity


Problem code: IPLUS4
If an integer is not divisible by 2 or 5, some multiple of that number in decimal notation is a sequence
of only a digit. Now you are given the number and the only allowable digit, you should report the
number of digits of such multiple.

For example you have to find a multiple of 3 which contains only 1’s. Then the result is 3 because is
111 (3-digit) divisible by 3. Similarly if you are finding some multiple of 7 which contains only 3’s
then, the result is 6, because 333333 is divisible by 7.

Input
Input starts with an integer T (<= 1000), denoting the number of test cases.

Each case will contain two integers n (0 < n <= 10 6  and n will not be divisible by 2 or 5) and the
allowable digit (1 <= digit <= 9).

Output
For each case, print the case number and the number of digits of such multiple. If several solutions are
there; report the minimum one.

Example
Input:

33 17 39901 1Output:

Case 1: 3Case 2: 6Case 3: 12

Added by: cegprakash


Date: 2012-01-11
Time limit: 1s-3s
Source limit:50000B
Languages: All
Resource: IPLUS

1
(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)

10426. Check
Problem code: CHECK2
The objective of this program is given a configuration of the board to find out if the king is in check or
not.

Chess is a two-player board game played on a chessboard, a square-checkered board with 64 squares
arranged in an eight-by-eight grid. It is one of the world’s most popular games, played by millions of
people worldwide at home, in clubs, online, by correspondence, and in tournaments.

The objective of this program is given a configuration of the board to find out if the king is in check or
not.

Each player begins the game with sixteen pieces: one king, one queen, two rooks, two knights, two
bishops, and eight pawns, each of these types of pieces moving differently. Pieces are used to attack
and capture the opponent’s pieces. The object of the game is to checkmate the opponent’s king by
placing it under threat of capture ("check") which cannot be avoided.

Input
The first line of input contains the number of test cases. In each case the first line has two numbers
representing the amount of white and black pieces. Subsequent lines contain a letter that represents the
piece and its corresponding coordinate. Consider that the king is always in first line.

Output
he output consists of a single line answering whether or not the King is in check, consider that your
pieces are white and it is your turn.

Example
Input:
31 1K f 8K a 11 2K f 8B e 7K e 21 2K h 8B f 6K a 1

Output:
No CheckCheckNo Check

1
Added by: Paulo Costa
Date: 2012-01-17
Time limit: 1s
Source limit:50000B
Languages: All
Resource: EACH/USP - Brazilian ICPC Training Camp, Jan-Feb/2012

2
(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 ()

10427. Lost in Perian


Problem code: PERIAN
John is lost in Klinglon city in the state of Perian, the only thing he knows is the position of cities (X
and Y coordinates) but does not know the roads or routes between cities. Fortunately this is a statewide
plan and the roads from one city to another follow a well-defined scheme.

Between two cities there is a road that is the shortest , but the roads do not intersect, then a road only 
exists if there is not  a shorter possible road that cross it. Every road can be traveled in both directions.

John wants to know the shortest path between cities A and B, considering the state planning.

Input
The input consists of several test cases.

Each case begins with a line with an integer N (2 <= N <= 1000) that determines the number of cities
in the state. N The next line contains the location of cities, each line consists of two integers X and Y
(0 <= X, Y <= 10 10 - 1) representing the N th city position . The city first of a test case  represents the
city A and the last represents the city B.

The last test case contains only one 0 and indicates the end of input.

Output
For each test case your program should print one line containing a decimal number rounded to two
decimal places, indicating the distance between cities A and B.

Example
Input:
20 03 440 01 01 44 430 01 04 420 0999999999 9999999990

Output:
5.006.005.661414213560.96

Added by: Paulo Costa


Date: 2012-01-17
Time limit: 1s
Source limit:50000B
Languages: All
Resource: EACH/USP - Brazilian ICPC Training Camp, Jan-Feb/2012

1
(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)

10703. HOSTAGES
Problem code: BYTESH
 

Loki and his army have taken a number of human prisoners. Thankfully, however, Captain
America has located where he’s keeping them. There are m rows of prison cells with each row
having n cells. There are different number of hostages in every cell which Thor now knows
about because he’s got Iron Man helping him.
Captain America plans to help everyone escape but Iron Man, or Stark (one of the brilliant
minds of our age), noticed that Loki has wired each of the cells with explosives and it’s very
difficult to defuse these bombs. Even if they do manage to open one of the cells, every cell in the
row directly above and below it gets blown and the people in those die. The cells immediately to
the left and right also get blown. Since it’s now clear that there’s no way that they can save
everyone, Captain America has to figure out the maximum number of people he can save and
then he keeps on opening doors until there are no more prisoners he can save.
The Description bellow illustrates this, step by step. Each cell represents one prison cell and the
number of
hostages it contains. At each step, the chosen box is circled and the shaded cells represent the
cells that will get blown by explosives. After eight steps,his job is over and Captain America
managed to save 10 + 9 + 8 +
3 + 7 + 6 + 10 + 1 = 54 people.

Description

1   8   2   1   9

1   7   3  5  2

1   2   10   3   18

8  4  7  9  2

7  4   1   3   1

If we select 10 from 3rd row inthird column , entire 2nd row , 4th row become zero , and 3rd row
column 2, 3rd row 4th column also become 0;

Matrix after this selection becomes :

1
1  8  2  1  9

0  0  0  0  0

1  0 10 0 18

0  0  0  0  0

7  4  1  3  1

Input
The input contains several test cases. The first line of a test case contains two positive integers
M and N (1 <= M × N <= 105), separated by a single space, indicating the number of rows and
columns respectively. Each of the following M lines contains N integers separated by single spaces,
each representing the initial number of hostages in the cell. Each cell will
have initially at least 1 and at most 103 hostages.
The end of input is indicated by a line containing two zeroes separated by a single space.
Output
For each test case in the input, your program must print a single line, containing a single value,
the integer indicating the maximum number of hostages that can be freed.
The output must be written to standard output.
Sample input
55
18219
17352
1 2 10 3 10
84791
71316
44
10 1 1 10
1111
1111
10 1 1 10
24
9 10 2 7
5115
00
Output
54
40
17

2
Added by: Troika::Bytes
Date: 2012-02-16
Time limit: 1s
Source limit:50000B
Languages: All

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 (tutorial)

10724. Sum of Tetranacci numbers (easy)


Problem code: TETRASUM
The sequence of Tetranacci numbers is defined as follows:
a n = a n-1 + a n-2 + a n-3 + a n-4 with a 0 = a 1 = a 2 = 0 and a 3 = 1.

Input
Input starts with a positive integer t <= 4000, then t lines follow. Each of the t lines contains two space
separated integers m and n with 0 <= m <= n <= 10 9 .

Output
Calculate a m + a m+1 + ... + a n and print the result modulo 1000000007.

Example
Input:
2
1 2
1919 5393

Output:
0
66616

Note: If your solution is fast enough, you may try the classical version.

Added by: numerix


Date: 2012-02-18
Time limit: 30s
Source limit:10000B
Languages: All
Resource: own problem

1
(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 (tutorial)

10817. Easy Factorization


Problem code: FACTCG
The task in this problem is to write a number in a multiplication of prime numbers separated by " x".
You need to put the 

number 1 in this multiplication.

Input
The input consists of several lines.

Each line consists of one integer N (1 <= N <= 10^5) .

Output
For each line you need to output the factorization separated by " x" and including 1.

Sample Input
1

Sample Output
 

1
1x2
1x2x2
1x2x2x2

1
Added by: Phyllipe César [UFCG]
Date: 2012-02-26
Time limit: 7s
Source limit:50000B
Languages: All

2
(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)

10834. Travelled Distance


Problem code: SBE201A2
[IMAGE]

You will calculate the travelled distance by a moving object. The object is moving with a velocity (v)
for time (t).

Input
The first input line contains a positive integer (N) that represents the total number of input lines that
will follow. Then, each input line shall contain a pair of positive integers (v) and (t) separated by a
space, representing the object’s velocity and the travelled time, respectively.

Output
You will output one positive integer, the travelled distance, which is equal to (v) times (t).

Example
Input:
32 35 15 5 Output:
6525

Added by: Islam Samir Badreldin


Date: 2012-02-27
Time limit: 10s
Source limit:50000B
Languages: C99 strict
Resource: Newton’s Laws!

1
(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)

10942. deleted
Problem code: DOR16

Added by: Azat Taryhchiyev


Date: 2012-03-06
Time limit: 1s
Source limit:50000B
Languages: All
Resource: International Sebat Institutions

1
(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 (challenge)

10972. RIAsDILEMMA
Problem code: INS1
<html>

<body>

<p>Ria wants to attetnd a marriage party.She wnats to look different in that party.So she decided to go
for shopping to buy some new dresses.When she went to the shop ,the shopkeeper showed her sarees
of three different colours.He showed her p different green sarees, q different blue sarees and r different
red sarees.Ria loved all of them.In how many ways can she select combination of sarees taking atleast
one green and one blue saree.<p> 

Input
First line consists of number of testcases.

Each testcase consists of a single line containing three integers. p, q, and r;

0<p,q,r<100 

Output
Output the number of diffrent combinations.

Example
Input:
1

5 4 3

Output:
3720

</body>

</html>

1
Added by: ba$!c !n$t!ncT
Date: 2012-03-09
Time limit: 0s-0.001s
Source limit:50000B
Languages: C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict
Resource: Own Problem

2
(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)

10981. SimpleSort
Problem code: INS2
"THE SOLUTIONS CAN ONLY BE SUBMITTED IN C,C#,C++,C99,HASK,JAVA,PYTHON"

One day shiv asked to his friend that can you sort a array.His friend started laughning and said dont
talk rubbish ,it’s so easy.Shiv said "Ok i will give you a treat if you are able to make a program of
sorting".But unfortunately his friend becomes ill and ask you to sort the array and promises you that he
will give you a choclate.So if you want a choclate then sort it!!

Input
First line contains "T" the number of test cases.

Each test case consists of two lines.

1<=N<=10^9 (the number of elements to be sorted)

Next line contains N numners which are to be sorted ( -10^9 <=numbers<=10^9)

Output
For each test case output the sorted sequence.

Example
Input:
1

1000000005 1000000004 1000000003 1000000002 1000000001Output:


1000000001 1000000002 1000000003 1000000004 1000000005

Added by: ba$!c !n$t!ncT


Date: 2012-03-09
Time limit: 0.009s-1s
Source limit:500B
Languages: C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PYTH 2.5 PYTH 3.1.2
Resource: Own Problem

1
(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)

10990. Zoos
Problem code: ZOOS1
Batad n širkheg zoos bajgaa ba zoos b?r n’ ??rijn gesen a[i] (i - dakh’ zoosny ?ne) ?netej. Negen ?d?r
Bulgaad m?ng? khereg bolžee. Bat khamgijn baga toony zoos ??rt?? avč ?ldeed busad zoosoo Bulgaad
?g?kh ba Batyn avč ?ldsen zoosnuudyn ?nijn nijlber Bulgaad ?gs?n zoosnuudyn ?nijn nijlberees ikh
bajkh ëstoj. KHamgijn bagadaa kheden zoos avč ?ldekh šaardlagataj ve.M?n Bulgaad zaaval zoos
?g?kh albag?j ba Bulgaad ?gs?n zoosnuudyn ?nijn nijlber n’ Batad ?ldsen zoosnuudyn ?nijn nijlbertej
tentsež bolokhg?j.

KHâzgaarlaltuud:

1 <= n <= 10000


1 <= a[i] <= 100

Orolt :

Ekhnij m?r?nd n too.


KHoër dakh’ m?rt n širkheg a[i] too zajgaar tusgaarlagdan ?g?gd?n?.

Garalt:

Avč ?ldekh khamgijn baga zoosny širkheg bolokh gants too.

Žišee:

Orolt:
5
16293

Garalt:
2

Tajlbar: Ta 6 bolon 9 gesen zoosnuudyg avč ?ldekhed nijlber n’ najzdaa ?g?kh zoosnuudyn ?nijn
nijlberees ikh bajna. (6+9 > 1+2+3)

1
Added by: Dulguun Batmunkh
Date: 2012-03-10
Time limit: 1s
Source
50000B
limit:
C C# C++ 4.3.2 C++ 4.0.0-8 FORT JAVA PAS fpc PAS gpc PERL PERL 6 PHP PIKE
Languages:
PYTH 2.5 PYTH 3.1.2 RUBY

2
(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 (tutorial)

11031. Bank Robbers


Problem code: BANKROBB
You are a Police Officer from Colombia. Today, there’s a bank robbery going on. You would like to
help, of course, but first you need to know how many criminals there are. You heard through the
Police Radio System that there are n criminals inside the bank, and m criminals waiting for them
outside the bank. You need to calculate the total number of criminals. As everybody in Colombia
knows, policemen are not the brightest people on Earth, so even this is difficult for them.

Write a computer program that calculates the total number of criminals.

Input
The input consists of several test cases.

Each test case is described as two integers n and m on a single line separated by one or more spaces (1
<= n, m <= 1000).

Output
For each test case, write the total number of criminals on a single line.

Example
Input:
1 2
7 3
12 25

Output:
3
10
37

Added by: Andrés Mejía-Posada


Date: 2012-03-12
Time limit: 2s
Source limit:50000B
Languages: All
Resource: Introduction to Programming Course, EAFIT University

1
(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 (tutorial)

11032. Maximum element of an array


Problem code: MAXINARR
Given an array of n integers, find the value of its maximum element.

Input
The input consists of several test cases.

Each test case is described in two lines. The first line contains n, the size of the array (1 <= n <=
10 6 ). The second line contains n integers separated by one or more spaces. Each integer in the array
will be between -10 9  and 10 9 , inclusive.

The last line of the input contains a single 0 and should not be processed.

Output
For each test case, write the maximum element in the array on a single line.

Example
Input:
4
1 2 3 4
2
-1 0
3
-1000000000 0 1000000000
0

Output:
4
0
1000000000

Added by: Andrés Mejía-Posada


Date: 2012-03-12
Time limit: 1s-7s
Source limit:50000B
Languages: All
Resource: Introduction to Programming Course, EAFIT University

1
(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 (tutorial)

11034. Count inversions in a small array


Problem code: COUNTINV
Given a 0-indexed array A of n integers we define an inversion as a pair of integers (i, j) such that 0
<= i <j   <n
   and A[i] >A[j].

In this problem, you will be given an array and your task is to calculate the total number of inversions
in this array.

Input
The input consists of several test cases.

Each test case is described in two lines. The first line contains n, the size of the array (1 <= n <=
1000). The second line contains the array: n integers separated by one or more spaces. Each integer
in the array will be between -10 9  and 10 9 , inclusive.

Output
For each test case, write the total number of inversions of the array on a single line.

Example
Input:
2
1 2
3
3 2 1
4
0 0 0 0
5
1 2 3 5 4
6
3 1 6 5 2 4
10
5 2 10 8 1 9 4 3 6 7
0

Output:
0
3
0
1
7
22

1
Added by: Andrés Mejía-Posada
Date: 2012-03-12
Time limit: 2s
Source limit:50000B
Languages: All
Resource: Introduction to Programming Course, EAFIT University

2
(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 (tutorial)

11053. Array Minimum


Problem code: SBE201A4
Given an array of n integers, find the value of its minimum element.

Input
Each test case is described in two lines. The first line contains n, the size of the array (1 <= n <=
10 6 ). The second line contains n integers separated by one or more spaces. Each integer in the array
will be between -10 9  and 10 9 , inclusive.

The last line of the input contains a single 0 and should not be processed.

Output
For each test case, write the minimum element in the array on a single line.

Example
Input:
4
1 2 3 4
2
-1 0
3
-1000000000 0 1000000000
0

Output:
1
-1

-1000000000

(Problem is inspired by http://www.spoj.pl/problems/MAXINARR/)

Added by: Islam Samir Badreldin


Date: 2012-03-12
Time limit: 1s
Source limit:50000B
Languages: C99 strict

1
(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 (tutorial)

11062. Binary search


Problem code: BSEARCH1
You are given a sorted array of numbers, and followed by number of queries, for each query if the
queried number is present in the array print its position, else print -1.

Input
First line contains N Q, number of elements in the array and number of queries to follow,

Second line contains N numbers, elements of the array, each number will be -10^9<= ai <= 10^9, 0 <
N <= 10^5, 0 < Q <= 5*10^5

Output
For each element in the query, print the elements 0 based location of its first occurence, if present,
otherwise print -1.

Example
Input:
5 4

2 4 7 7 9

10

Output:
2

-1

1
Added by: jack(chakradarraju)
Date: 2012-03-13
Time limit: 1s-2s
Source limit:50000B
Languages: All
Resource: NITT Class

2
(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 (tutorial)

11065. GP - Complete the Series v1


Problem code: GP2
This problem has been migrated to 

http://www.spoj.pl/problems/GP1/ 

--------------------------------------------------------------------------------

Geometric progression(GP) is a set in which the ratio of 2 consecutive numbers is same. for eg,
1,2,4,8,16.... In this the ratio of the numbers is 2.

The task here is very simple indeed.

You will be given the 3rd term , 3rd last term and the sum of the series. You need print length of the
series & the series.

Input
First line will contain a number indicating the number of test cases.

Each of the following t lines will have 3 number ’3term’ ,’3Lastterm’ and ’sum’

3term  - is the 3rd term in of the series and

3Lastterm  - is the 3rd term in of the series and

sum - is the sum of the series.

Output
For each input of the test case, you need to print 2 lines.

1
fist line should have 1 value- number of terms in the series.

2nd line of the output should print the series numbers separated by single space

Example
Input:
14 64 511 Output:
91 2 4 8 16 32 64 128 256NOTE -All the values will be in the range [0, 2^64] inclusiveThe series will have at least 6 elements.number of test cases <=100.The Ratio in all the cases will be an integer. (Thanks Mitch for pointing this out)All the numbers will fit in 64 bits(long long in C)

Added by: Devil D


Date: 2012-03-13
Time limit: 0.5s
Source limit:2000B
Languages: All
Resource: Own

2
(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)

11091. PUTS
Problem code: KH00
hello world gež khevle.

Input
bajkhg?j

Output
hello world

Example
Input:

Output:
hello world

Added by: os_b


Date: 2012-03-14
Time limit: 1s
Source limit:50000B
Languages: All

1
(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 (tutorial)

11095. Symmetric or not


Problem code: SYMN
Given a list of numbers check if it is symmetric by its middle element or not i.e. {1,2,2,1} and
{1,2,3,2,1} are symmetric while {1,2,3} and {1,2,2} are not symmetric.

Input
First line contains N, size of the list (1 <= N <= 50) 

Second line contains N numbers (0 <= each number <= 50) representing the list of numbers.

Output
Prints one line containing either "Yes" if it is symmetric or "No" if it is not symmetric.

Example
Input:

1 2 3 2 1

Output:

Yes

Added by: Omar ElAzazy


Date: 2012-03-14
Time limit: 2s
Source limit:50000B
Languages: All

1
(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 (tutorial)

11096. Triple Zeros


Problem code: TRIZ
Given an N by M matrix of zeros and ones check if there are 3 vertically contiguous zeros or not

i.e. 

0 0 1 0

1 0 1 0

0010

The bold zeros represent three zeros vertically contiguous (there are 2 triplets)

Input
First line contains N and M (1<=N,M<=5) number of rows and number of columns of the matrix.

N lines follows each line contains M digits (either a 0 or a 1) separated by a space.

Output
Prints one line containing a "Yes" if there are three zeros vertically contiguous or "No" otherwise.

Example
Input:

5 5

1 0 1 1 0

1 1 0 1 1

0 0 0 1 0

0 0 1 0 0

1 1 0 0 0

Output:

1
Yes

Added by: Omar ElAzazy


Date: 2012-03-14
Time limit: 2s
Source limit:50000B
Languages: All

2
(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 (tutorial)

11097. Easy Powers


Problem code: EPO
Calculating a b   can be done using the recurrence f(a,b) such that if b > 0 f(a,b) = a*f(a,b-1) while if b
= 0 then f(a,b) = 1.

Input
Two numbers in one lines separated by a space a (1<=a<=10) and b (1<=b<=12)

Output
One number which is the value of a b

Example
Input:
3 9

Output:1968319683

Added by: Omar ElAzazy


Date: 2012-03-14
Time limit: 2s
Source limit:50000B
Languages: All

1
(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 (tutorial)

11100. Fun with Fibonacci Series


Problem code: FIBOFUN
Fibonacci series is a series in which every element is sum of previous 2 elements.

first 2elements are 0,1 and the series goes like 0,1,1,2,3,5,8,13 ........

What if you were given 2 random numbers as the starting of the series and u follow the same rule as
the fibonacci rule.

for eg. if you were given 2 and 2 .. the series would become

2 2 4 6 10 16 26 .........

Now ur task is Simple ...

You will be given 2 numbers a & b .. the first and second term of the series..

you need to calculate the sum of first n numbers of the series so formed..

Since the numbers can be big you need to print the result mod some number ’M’ provided in the input.

Input
first line will have single number ’t’ - number of test cases.

each test case will have 4 numbers a,b,n & M

a- first number of the series

b- second number of the series

n- calculate the sum till n numbers

M- print the result mod M

1
Output
single number for each case - sum of n terms mod M

Example
Input:
22 2 10 211 3 10 21 Output:

134Explanation - for first case series is 2 2 4 6 10 16 26 42 68 110 .. Sum is 286.. o/p = 286%21 = 13NOTE -Number of test cases <=100.0 <= a,b,m <= 10^8

1 <= n <= 10^8

actually n ranges from 1 to 10^8

Added by: Devil D


Date: 2012-03-15
Time limit: 0.5s
Source limit:10000B
Languages: All
Resource: Own

2
(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)

11106. Dice Problem


Problem code: MAIN12D
Everyone loves Swampy. Swampy the Alligator lives under the city and yearns for a more human like
existence. One day Swampy and his M friends decided to play a game. The game was simple.
Everyone rolls an N-sided die and whoever gets the largest faced side wins. All the alligators lined up
to throw the die. After all M friends of Swampy threw the die, it was Swampy’s turn now to throw the
die, but he being intelligent than the rest of his friends wanted to know for sure the odds of him
winning the game.

Input
First line of the input contains an integer T, the number of test cases. Then T test cases follow. Each
test case consists of two integers N and M. Next line contains M integers(space separated), d1,
d2,..,dM, the face of the die Swampy’s friends got.

Output
For each test case, print "Case #X: A/B" (quotes for clarity only), where X is the test case number
starting from 1, A is the numerator, B is the denominator and A/B is in the form of an irreducible
fraction. If the required probability equals to zero, output "0/1". If the required probability equals to 1,
output "1/1".

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

Output:
Case #1: 0/1
Case #2: 5/6

Constraints: T <= 100 1 <= N <= 1000 0 <= M <= 1000 1 <= di <= N

1
Added by: Nikunj Jain
Date: 2012-03-15
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Vaibhav Mittal

2
(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 (tutorial)

11110. Easy Longest Increasing Subsequence


Problem code: ELIS
Given a list of numbers A output the length of the longest increasing subsequence. An increasing
subsequence is defined as a set {i0 , i1 , i2 , i3 , ... , ik} such that 0 <= i0 < i1 < i2 < i3 < ... < ik < N
and A[ i0 ] < A[ i1 ] < A[ i2 ] < ... < A[ ik ]. A longest increasing subsequence is a subsequence with
the maximum k (length).

i.e. in the list {33 , 11 , 22 , 44}

the subsequence {33 , 44} and {11} are increasing subsequences while {11 , 22 , 44} is the longest
increasing subsequence.

Input
First line contain one number N (1 <= N <= 10) the length of the list A.

Second line contains N numbers (1 <= each number <= 20), the numbers in the list A separated by
spaces.

Output
One line containing the lenght of the longest increasing subsequence in A.

Example
Input:

1 4 2 4 3
Output:
3

1
Added by: Omar ElAzazy
Date: 2012-03-17
Time limit: 1s
Source limit:50000B
Languages: All

2
(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 (tutorial)

11111. Easy Longest Common Subsequence


Problem code: EELCS
A common subsequence between two strings A and B is defined as 2 sets { i0 , i1 , i2 , i3 , ... , ik } { j0
, j1 , j2 , j3 , ... , jk } such that 0 <= i0 < i1 < i2 < i3 < ... < A.length() and 0 <= j0 < j1 < j2 < j3 < ... <
B.length() and A[ i0 ] = B[ j0 ], A[ i1 ] = B[ j1 ] , ... , A[ ik ] = B[ jk ]. Given two strings A and B print
the length of the longest common subsequence between them.

i.e. "a", "d","cd" are common subsequence between the two strings "abcd" and "adcd" while "acd" is
the longest common subsequence between them.

Input
First line contains a string A (1 <= A.lenth() <= 7).

Second line contains a string B (1 <= B.length() <= 7).

Each string is composed of lower case letters only (’a’ -’z’).

Output
Prints one line containing the length of the longest common subsequence.

Example
Input:

abcd

adcd

Output:
3

Added by: Omar ElAzazy


Date: 2012-03-17
Time limit: 2s
Source limit:50000B
Languages: All

1
(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 (tutorial)

11114. Who Won the Match


Problem code: MWINNER
In IPL-5, there will be an element of mystery - scores will not be disclosed. Hence, fans will have to
wait till the presentation ceremony to know who won the match. Since you are the anchor, both teams
score are submitted to you. Now you have to announce which team has won the match and by how
many runs.
The details provided to you are team’s acronym and their scores. Output the result containing winning
team name and the difference.

Input
First line of the input contains the number T<1000(number of test cases). Test cases start from the next
line. Each test case has two lines with the details of one team. Each line has team name, less than or
equal to three characters, followed by a space and then the score of the team(<=400).

Output
For every test case, give the output in following manner.
"TEAM won by R runs".

In case of a tie, give the output

"MATCH DRAW"

(quotes are for clarity)

Example
Input:
3RCB 250MI 254DC 128KKR 84CSK 180DD 180 Output:
MI won by 4 runsDC won by 44 runsMATCH DRAW

Added by: Rajesh Kumar


Date: 2012-03-17
Time limit: 1s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8

1
(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 (tutorial)

11121. Palindromic Cricketer


Problem code: CKTPALIN
IPL-5 is going to be special. A lot of new players are going to play. Some of them have palindromic
names. A palindromic name reads same when read from either ends.

Input
N(<50), number of players. Next N lines contains names of players. Names would be a character
sequence of 50 or less characters in lowercase letters.

Output
The output should consist of N lines. For every player output "Palindromic Name", if the name is
palindromic or "Not Palindromic Name", if it is not in these lines .

Example
Input:
3nitinaadityagagasandesh Output:Palindromic NameNot Palindromic NamePalindromic NameNot Palindromic Name

Added by: Rajesh Kumar


Date: 2012-03-18
Time limit: 1s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8

1
(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 (tutorial)

11203. Auris Love


Problem code: OPC5
Little Aurilio likes a cute girl in his class. So one day he approaches her and asks her if he can sit with
her in class. Now, the cute girl is very fond of mathematics. So she gives a task. The task is as follows
-
You are given two integers n and k. compute maximum l for which (fact(n)%pow(k,l))==0 where
fact(n) is factorial n and pow(k,l) is k^l. Help Little Aurilio in impressing the cute little girl. 

INPUT
First line contains number of test cases T next T lines contains two integers n and k. 
OUTPUT
output T separate lines each containing Maximum l for which (n!%pow(k,l))==0. 
CONSTRAINTS
T<=10^3
2<=n,k<=10^9
SAMPLE INPUT
3
25
33
82
SAMPLE OUTPUT
0
1
7

Added by: bashrc is back


Date: 2012-03-23
Time limit: 1s-2s
Source limit:1000B
Languages: All
Resource: MNNIT LOCAL OPC

1
(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)

11210. Arya and the exponacci


Problem code: OPC3A

Arya is very fond of fibonacci numbers.He claimed he can solve any problem on fibonacci number.His clever friend golu gave him a challenge to prove his skills.He gave him a sequence which he called exponacci.The sequence is given by g(n)=2^f(n-1) for n>0 g(0)=1 for n==0 f(n) denotes the nth fibonacci number where f(0)=1 f(1)=1 (Obviously golu is not as good as arya in fibonacci numbers so he believes f(0)=1,anyways we have chosen not to disturb him)f(n)=f(n-1)+f(n-2) for n>1 Help arya to find the nth exponacci number.Since the numbers can be very large take mod 10^9+7

Input : The first line of the input will be the number of test cases(T<=2000). For each test case first line contains one integers n 0 <= n <= 1000000

Output :The value of g(n)%(10^9+7)

Sample Cases :

Input:
2
3
5

Output:
4
32

Added by: bashrc is back


Date: 2012-03-24
Time limit: 1s
Source limit:1000B
Languages: All
Resource: Own problem used in MNNIT LOCAL OPC

1
(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 (tutorial)

11226. Hello World!


Problem code: HELLO
The problem is to print out "Hello World!"

Output

Hello World!

Added by: Mussab ElDash


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

1
(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 (tutorial)

11239. Number Theory (Easy)


Problem code: NUMTRYE
f(n) and g(n) are two functions defined as following :

f(n) = PROD ( p i 2e i +1 +1 ), where p i is prime factor of n and e i is highest power of p i in n.

g(n) = S( n/gcd(n,i) ); 1 <= i  <= n

For a given value of n, you have to compute f(n)/g(n) % 1000000007.

Input
First line has T ( <= 10000 ), next T lines has 2 <= n <= 10^12.

Output
f(n)/g(n) % 1000000007 for each test case.

Example
Input:
224

Output:33

Added by: XeRon!X


Date: 2012-03-25
Time limit: 100s
Source limit:50000B
Languages: All

1
(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)

11247. Plus Within a diamond


Problem code: PWAD

Write a program that prints a diamond with a plus


within it, given the integer height of the diamond. The
outer-most shape is a normal
diamond shape, the middle row of the shape will be a
row filled with stars (making the horizontal dash of the
plus sign), and in
all the remaining rows the middle element of that row
will have a star (making the vertical dash of the plus
sign). Observe the
following examples.
For n=11, the output will look like:
 *
  ***    
  * * *   
  *  *  *  
 *  *   *
***********
 *  *   *
  *  *  *  
  * * *   
  ***    
 *

1
For n=7, the output will look like:
 *
  ***  
 * * *
*******
 * * *
  ***  
 *
For n=3, the output will look like:

***

For n=1, the output will look like:
*
Only consider odd sizes.
Added by: Mussab ElDash
Date: 2012-03-26
Time limit: 1s
Source limit:50000B
Languages: All
Resource: GUC CSEN202 2012 Assignment

2
(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 (tutorial)

11264. FUN WITH NUMBERS


Problem code: ACMCEG2A

Fun with numbers


 

       12 years back, Mr. Bean’s dad gifted him a board game. 10 years back, he lost the board along
with all the toys numbered "0". All that he had is these toys numbered from "1" to "9". As Mr. Bean is
a joker, no one was willing to play with him. So he sat on the floor and arranged these toys in
ascending order i.e. "123456789". Then he figured out the next smallest number that can be formed by
rearranging the toys is "123456798". Then he figured out the next greater number as "123456879".
Now he learnt C++ and he wants to write a program to find the next nth greater number that can be
formed by rearranging the digits in the given number X. You can safely assume that such a number
always exists.

Input Specification:

The first line contains a natural number t denoting the number of test cases. Then the next t lines
contains the description of t test cases, each line with two natural numbers X and n.

Output Specification:

For each test case print the answer in a separate line.

Input Constraints:

1<=t<=100

1<=X<=10^18

1<=n<=10000

Sample Input:

1
3

123 1

5132 3

1112 1

Sample Output:

132

5312

1121

Added by: cegprakash


Date: 2012-03-30
Time limit: 2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All except: BF

2
(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 (tutorial)

11265. FIGUREFUL
Problem code: ACMCEG2B

FIGUREFUL
Don and his friends had some sort of code word to describe the girls who pass towards their class.

Anitha passed - killer told.. "Dude, 5 2 is going"

Chitra passed - Jumbo told.. "Dude, 6 4 is awesome"

Divya passed - Baabi told.. "Machi 1 6 is my dream girl"

Girls couldn’t understand those code words. To crack the code word, girls decide to record all the code
words and the girls’ name whenever they call.

The silencer in the class watched all these and got angry. He mugged up all the code words, went to
teacher and complained about the naughty boys and naughty girls.

Teacher : Who is the girl with code word 1 6?

Silencer: Divya

Teacher: Who is the girl with code word  5 2?

Silencer: Anitha

Teacher: What is the code word for me??

Silencer: (puzzled)

Now you have to pretend that you are the Silencer to solve this problem. Record the code words and
answer the questions the teacher asks you.(She may ask the same question any number of times)

Note: There can be any number of code words for a same girl. If there exist more than one girl
for a same code word, then that code word belongs to the latest girl. 
 

Input Specification:

The first line contains an integer n, the number of figures. Then in each of the next n lines there will be
2 integers and a figure name.

1
After that there will be an integer t, the number of test cases. For each test case, there will be two
integers representing the code word. Print the figure’s name corresponding to the code word.

Output Specification:

For each test case output the figure name.

Input Constraints:

1<=n<=100000

1<=t<=100000

-1000000<=code1, code2<=1000000

The figure’s name will not exceed 20 characters 

Sample Input:

5 2 Anitha

6 4 Yamuna

6 4 Chitra

1 6 Divya

-2 0 Teacher

7 4 Anitha

-2 0

64

Sample Output:

Teacher

Chitra

Hint: Use map

Added by: cegprakash


Date: 2012-03-30
Time limit: 2s-5s
Source limit:50000B
Languages: All except: BF

2
(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 (tutorial)

11266. Pick the candies


Problem code: ACMCEG2C

Pick the Candies 

Many children went to a sweet shop. There were n candy varieties and each variety is kept in a
separate bowl. The sweetness of each variety is written on the bowl. All the children wanted the candy
with highest sweetness value. As there are only limited candies in each variety, the shop keeper makes
a rule. According to the rule, the shopkeeper will show selectively chosen k varieties to every children.
The children can pick any one of those varieties and move away. To make it easy for him, the shop
keeper shows the

varieties 1,2,...,k to children1,

varieties 2,3,...,k+1  to children2,

1
varieties 3,4,...,k+2 to children3 and so on..

All the children are good at math. Find what variety each child will choose.

Input Specification:
The first line contains an integer t, the number of test cases. For each test case the input consists of two
lines. The first line contains two integers n(number of candy varieties) and k. The next line contains n
number of integers, the sweetness values of all the candy varieties.
Output Specification:
For each test case, print the candy varieties chosen by the children. 
Input Constraints:
1<=t<=1000
1<=n<=10000
1<=k<=n
0<=Sweetness value<=10000
Sample Input:
3
53
12345
42
7168
95
7 14 3 0 2 2 2 2 2
Sample Output:
345
768
14 14 3 2 2

Hint: use deque 

Added by: cegprakash


Date: 2012-03-30
Time limit: 1.399s-1.799s
Source limit:50000B
Languages: All except: BF

2
(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 (tutorial)

11317. MAX AREA


Problem code: COMPSEM0
Given six sticks, two of length A metres, two of length B metres and two of length C metres. Find the
maximum area of the rectangle which can be formed using four sticks from these six sticks.
INPUT
A single line containing three integers A, B and C.
OUTPUT
The maximum area of the rectangle which can be formed using four sticks from these six sticks
CONSTRAINTS
1 <= A, B, C <= 100
SAMPLE INPUT
123
SAMPLE OUTPUT
6

Added by: amit karmakar


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

1
(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 (tutorial)

11318. NEMO
Problem code: COMPSEM1
Kaushik is fond of movies and recently saw an old one called "Finding nemo". He is also interested in
programming so thinks how he can relate both.
He comes up with a problem for which you have to find the solution.
Given an input string dertermine if nemo can be a subsequence of it.
Note: For the uninformed, A subsequence of a string is a new string which is formed from the original
string by deleting some of the characters without disturbing the relative positions of the remaining
characters. For example, "AGH" is a subsequence of "ABCDEFGH" while "AHG" is not.
INPUT
The first line contains an integer T which denotes the total number of test cases. Each test case
contains a string containing lowercase letters only (a-z) of length no more than 100 characters.
OUTPUT
For each test case print "YES" if the input string contains "nemo" as a subsequence otherwise print
"NO".
SAMPLE INPUT
3
amitmnoe
kaushikmn
nererdfsdfmdfdfo
SAMPLE OUTPUT
NO
NO
YES

Added by: amit karmakar


Date: 2012-04-04
Time limit: 2s
Source limit:50000B
Languages: All
Resource: COMPSEM 2012

1
(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 (tutorial)

11319. TARANIAMITKAUSHIK
Problem code: COMPSEM2
Tarani likes numbers which contain only the digit 1 while Amit likes numbers which contain only the
digit 5.
Kaushik likes numbers which are sum of two numbers, one containing only digit 1 and the other
containing only digit 5.
Input
First line contains an integer T(<10) denoting the total number of test cases. Each test case contains an
integer N(1<=N<=100).
Output
Print "KAUSHIK" if kaushik likes the number. If kaushik doesn’t like the number, print "AMIT" if
amit likes it or "TARANI" if tarani likes it. Else print "NONE".
Sample input
3
116
11
3
Sample Output
KAUSHIK
TARANI
NONE
Explanation
116 is sum of 111 + 5 So kaushik likes it. 11 contains only digit 1 so tarani likes it. 3 doesn’t satisfy
the liking condition of anyone.

Added by: amit karmakar


Date: 2012-04-04
Time limit: 2s
Source limit:50000B
Languages: All

1
(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 (tutorial)

11323. 2D-SORT
Problem code: SORT2D
Given n points in a two dimensional space, sort all the points in ascending order.

(x1,y1) > (x2,y2) if and only if (x1>x2)  or    (x1==x2 && y1<y2)

Input Specification:

The first line consists of an integer t, the number of test cases. Then for each test case the first line
consists of an integer n, the number of points. Then the next n lines contains two integers xi, yi  which
represents the point.

Output Specification:

For each test case print the sorted order of the points.

Input Constraints:

1<=t<=10

1<=n<=100000

- 10^9<=co-ordinates<=10^9

Sample Input:

34

-1 2

5 -3

33

-1 -2

Sample Output:

1
-1 2

-1 -2

34

33

5 -3

Hint: Use sort() in <algorithm>

Added by: cegprakash


Date: 2012-04-05
Time limit: 1s
Source limit:50000B
Languages: All

2
(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)

11331. Two Squares


Problem code: TWOSQ
Given an integer, how many distinct ways it can be written as the sum of two square integers? The
square integers are 0,1,4,9,...

Since addition is commutative, reordered sums (e.g. 0^2 + 5^2 and 5^2 + 0^2) are not distinct and
count as just one way.

For example, 50 can be written as a sum of squares in exactly two distinct ways: 1^2 + 7^2 and 5^2 +
5^2.

Input:

An integer N, from 0 to one quadrillion (10^15) inclusive.

Output:

The number of distinct ways N can be written as the sum of squares.


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

3 50

97682Example Output 1: Example Output 2: Example Output 3:

0 2

Added by: Paul Draper


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

1
(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)

11333. Vowels
Problem code: VOWELS
Count the number of vowels (a,e,i,o,u,y) in a "word". Include both uppercase and lowercase vowels in
your count.

Input:

A sequence of alphabetic characters (no spaces), with length at most 10,000.

Output:

The number of vowels.


0Example Input 1: Example Input 2:

ObjectOriented

XKCDExample Output 1: Example Output 2:

Added by: Paul Draper


Date: 2012-04-06
Time limit: 1s
Source limit:50000B
Languages: All

1
(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)

11341. TWIN PRIMES


Problem code: TWINP
Twin Primes are the pair of prime numbers that differ by two. For ex.

3,5

11,13

29,31

(each differ by two)

Input
First line of input consists of T (number of test cases).

Next T lines contains a single number N (indicating the Nth pair of twin primes).

Output
For every test case output the pair of Twin Primes in each line separated by a single space.

Example
Input:
31711Output:
3 559 61137 139(T<=25,1<=N<=10^5)(Try tutorial version (time limit easy) -> http://www.spoj.pl/problems/TWINP2/ )

Added by: Avinash


Date: 2012-04-07
Time limit: 2s
Source limit:50000B
Languages: All
Resource: Own Problem

1
(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)

11342. Here be ducks


Problem code: DUCKS
Ducky the Duck was walking by and he had a little idea, he wanted to see if making a line of dots with
his pencil and throwing the letters of his name randomly at it he would be able to pick up the letters
again and writte his name perfectly, but some times when he throws them they fall out of the path.
Ducky also throwed random characters to replace some of the dots, when he reaches a random
character before he find his name he gets mad and scream NO DUCKY!, task is simple, just find
Ducky´s name on the path he made.

Clarifications:
1-Ducky starts looking for his name from the begining of the string

2-Ducky want to find the letters of his name that means ’D’ ’u’ ’c’ ’k’ ’y’ another letter even the letter
’d’ is considered a random character

3-When he steps a dot he will keep searching for the name, if he steps a letter of his name and hasn´t
found them all he will keep searching, when he finds a random character he will stop.

Input
T=  Number of test cases, which are less than 20 omg

Then T lines will follow, each of them having a string representing the Ducky´s path

Output
Output NO DUCKY! If you cannot find his name, otherwise print DUCKY IS HERE!

Example
Input:

5Ducky....D...ucky...Duck.....D...uck!y..u.c..ky.DOutput:

1
DUCKY IS HERE!DUCKY IS HERE!NO DUCKY!NO DUCKY!DUCKY IS HERE! Extra: TLE changed to 0.35 segs cause there are only less than 20 test cases and there is people getting 0.45 seconds on their answer, wich for Ducky is unacceptable.

Added by: Rodolfo Miquilarena


Date: 2012-04-07
Time limit: 0.349s
Source limit:5000B
Languages: All
Resource: Own problem

2
(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 (tutorial)

11349. Tertiary Calculator


Problem code: SBE201A6
In this problem, you will implement a simple arithmetic expression parser.

Given lines of two arithmetic operations (one of addition, subtraction, multiplication, or division), you
will output lines that constitute the mathematical evaluation of the corresponding input lines, taking
operator precedence into account.

Intermediate calculations should be done in double precision.

Input
Each input line is in the format:

num1 [op1] num2 [op2] num3

All numbers are single-precision floating point numbers.

Operators can be one of ’+’,’-’,’*’, and ’/’

Output
For each input line, you will output the result of evaluating the input arithmetic expression,

taking operator precedence into consideration (’*’ and ’/’ have higher precedence than ’+’ and ’-’).

Example
Input:
56.1814 * -896.744 / -1.90273e+06-75.3324 - 14.335 / 17094381.6215 / 154.868 - -3.05828e+06 Output:

0.0264779-75.33253.05828e+06HINT: use atof() to convert input numbers into single-precision floating point numbers,and use printf("%g") to ouput the calculated double precision results.Continue reading input lines until no more input characters are available.

Added by: Islam Samir Badreldin


Date: 2012-04-09
Time limit: 5s
Source limit:50000B
Languages: C99 strict

1
(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 (tutorial)

11356. TWIN PRIMES


Problem code: TWINP2
Twin Primes are the pair of prime numbers that differ by two. For ex.

3,5

11,13

29,31

(each differ by two)

Input
First line of input consists of T (number of test cases).

Next T lines contains a single number N (indicating the Nth pair of twin primes).

Output
For every test case output the pair of Twin Primes in each line separated by a single space.

Example
Input:
31711Output:
3 559 61137 139(T<=25,1<=N<=10^5)(Try classical version (strict time limit)-> http://www.spoj.pl/problems/TWINP/ )

Added by: Avinash


Date: 2012-04-11
Time limit: 5s
Source limit:512B
Languages: All
Resource: Own Problem

1
(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 ()

11364. Home, sweet home 1


Problem code: HSH1
Sometimes, Romanka goes to programming competitions. After the competitions, she wants to return
home using one or more bus and/or train lines. Each of these lines connects some of N significant
stops in a given sequence. You’re given expected times of arrival to each of these stops after exiting
the first stop of the sequence. The same line departs from the first stop every whole minute, which
means Romanka doesn’t have to wait at any stop from which at least one line departs (this is the
reason why bus and train prices in Slovakia have significantly risen lately).

Note that more lines can connect the same stops, and there can be a situation when line A connects
stops X, Y and Z, and line B connects stops X and Z, but not Y; also, two lines can have different
expected arrival times even if they connect the same stops (for example, night trains are usually slower
than day trains).
Out of these N significant stops, competitions are only organized in K of them. You’re given Q
questions "how much time do you need at least to travel from stop A to stop V", where V is the village
where Romanka lives and it’s constant for all queries. Assume that all the competitions end at time
HH:MM.

Input description
In the 1st line of the input, there are positive integers: N, K, L - number of transport lines, V, and time
of a competition’s end in the format HH:MM.
In the 2nd line, there are K numbers k - the significant stops appearing in the questions.
L lines follow, i-th of them containing integer S_i - number of stops, and S_i pairs of integers - the
expected times of arrival at S_i stops, in minutes, each followed by the number of respective stop (so
the first of these numbers will be 0). Expected times of arrival form an increasing sequence.
Then, there is an integer Q, and Q numbers - for every question, stop A, from which Romanka travels.
N <= 10000K <= 10000 <= V < K0 <= k_i < K; k_i != VL <= 10002 <= S_i <= min(N,500)Q <= 1000000

Output description
Output Q lines - one line for every question, on each of them a single integer - minimum time in
minutes needed to travel from stop A (in this question) to stop V. These times fit into signed 64bit
integers in the correct solution. In case there’s no such path or the optimal path has cost 0, output the
string "trololo".

1
Example
Input:
10 10 3 2 15:42
0 1 2 3 4 5 6 7 8 910 0 0 47 1 94 2 141 3 188 4 235 5 282 6 329 7 376 8 423 9 // multiples of 474 0 5 4 7 12 2 19 07 0 1 2 9 3 5 4 4 50 5 57 6 62 1 // the driver of the bus is trolling, and took a break to have a smoke at stop 45 0 4 6 8 9(there are no comments in the testing inputs)
Output:
62519710149

Note: This is my first non-trivial problem, so feel free to tell me what you miss about the description, I
might add it. Also, the test cases are still very simple, so any correct solution will probably pass. When
more test cases are added, all the submissions will be rejudged.

Added by: Jakub Šafin


Date: 2012-04-11
Time limit: 0.5s-1s
Source limit:50000B
Languages: All

2
(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 (tutorial)

11365. TSquare TO Square


Problem code: SQ2SQ2
There are Squares whose digits can be rearranged to make another squares.Lets call them S2S
numbers.

for ex.

144->441

Input
Single line containing two integers X Y(Xth,Yth term in the list of S2S numbers).

Output
Print all the numbers from Xth to Yth Term of S2S numbers list(both inclusive).

Example
Input:
1 3

Output:
144169196(Xth,Yth term<=10^12)(Source Code Limit= 1000B) Note: 1->100->1 or other similar numbers are NOT S2S numbers(ex 9->900->9)Updated Time Limit : 30secTry the classic version -> http://www.spoj.pl/problems/SQ2SQ/

Added by: Avinash


Date: 2012-04-12
Time limit: 1s-14s
Source limit:1000B
Languages: All
Resource: Own Problem

1
(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 (tutorial)

11366. Zoom Operation


Problem code: ZOOMOP
 

Zoom Operation:

1
2
Use only 4 symbols:  + ? - #   (in circular order  beginning with + )) to zoom the number given  

Every segment of the number has one symbol more than the previous.(First Segment has a single
symbol).

First symbol of evry segment starts in the same column/row where the previous segments’ last symbol
ends.

1st segment(orange color) -> 1 symbol   + (first symbol only)

2nd segment(green color) -> 2 symbols  ? - (starts with 2nd symbol as 1st segment uses sinlge
element)

3rd segment(yellow color) -> 3 symbols  # + ? (starts with 4th symbol as 3 symbols have been used
by 1st & 2nd seg)

Colors are shown for better understanding.See Picture for more clarification.

Input:

Given a number you have to apply Zoom operation and print it.

Output:

Print the Pattern after Zoom Operation.

Example:

Input:

3
1

Output:

Input:

Output:

  +?
  -
-?+#
#
+
?
-#+?-

Input:

Output:

  +?
   -
  -?+#
 #
 +
 ?
  -#+?-#
 +
 ?
 -
 #
 +
#-?+#-?            

Input:

Output:

4
+
?-#
 +
 ?

Input:

Output:

  ?+
 -
  #+?-
 #
   +
  ?
 -?+#-          

For any clarification,refer to the picture above.

Try classical at -> http://www.spoj.pl/problems/ZOOMOP2/

Added by: Avinash


Date: 2012-04-12
Time limit: 1s
Source limit:512B
Languages: All
Resource: Own Problem

5
(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)

11368. Fibonacci brain


Problem code: TSHOW2
  Ravi is a student who loves fibonacci numbers. He used to think of fibonacci numbers all the time.
Suddenly he asked his friend Rama whether he can find Nth fibonacci number. Rama said ’No’. Ravi
started laughing. Ravi then asked Rama whether he can atleast find the last digit of Nth fibonacci
number. Thinking for a while, Rama said ’Yes’.Help Rama finding the last digit of Nth fibonacci
number. Note : The series starts from 0 (0,1,1,2,3,......)

Input
Fisrt line consists of an integer t(t<=1000) denoting the number of test cases that follow.

The follwing t lines consist of an integer N(1<=N<=10^15).

Output
Output t lines consisting of the last digit of Nth fibonacci number.

Example
Input:
3125 Output:
013

Added by: Pandian


Date: 2012-04-12
Time limit: 0.5s-1s
Source limit:50000B
Languages: All
Resource: Own problem

1
(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 (tutorial)

11382. Quadra vs PussyCat


Problem code: FAREWELL
In their teenage The Quadra and The PussyCatSinghal enters into a healthy competition of solving
more and more problem on various programming sites. As of now both of them had grown too old to
use thier fingers at keyboard, it is time to end this competition. So they ask The CoolAnu to calculate
how many of the problems had been solved by both of them, only by The Quadra and only by The
PussyCatSinghal.

So your task is to help CoolAnu determine the same. You are given two integers n and m - size of list
of problems solved by Quadra and PussyCatSinghal, respectively, along with the list.

Input
The first line of input contains a integer n, number of problems solved by Quadra. Then follows n
integers, IDs of problem solved by him. Then next line contain another integer m, number of problems
solved by PussyCatSinghal. Then follows m integers, IDs of problem solved by him.

Output
The output contains three lines. Let a be the number of problem solved by both of them, b by only
Quadra, c by only PussyCatSinghal. Then the first line contains: "Both: a", second line: "Quadra: b",
third line: "PussyCatSinghal: c" (quotes for clearity).

Constraints
<>   0 <= n, m, <= 10 5

<>   1 <= problem ID <= 10 6

<>   all problem solved by a single user has a unique ID.

Example
Input:
53 2 1 7 965 8 3 9 6 10Output:
Both: 2Quadra: 3PussyCatSinghal: 4Explanation for above test caseBoth had solved 2 problems with problem ID 3 and 9.Porblem solved by Quadra (and not by PussyCatSinghal) are 3 with ID 1, 2, 7.There are 4 problems solved only by PussyCatSinghal, namely 5, 6, 8, 10.

1
Added by: lost
Date: 2012-04-13
Time limit: 1s-5s
Source limit:50000B
Languages: All

2
(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)

11387. Perfect Cover


Problem code: COVER01
Mr. 10-pointer and Mr. Gyani had been trying to count the number of ways to perfectly cover a 1-by-n
board with monominoes and dominoes.
With pen-and-pencil they are only able calculate the count for small n.
For example:
1-by-1 = 1 (only one monomino)
1-by-2 = 2(either use two monomino or one domino)
1-by-3 = 3 (either all monomino, or 1 monomino followed by a domino, or 1 domino followed by a
monomino).
So they approached Ms. Pavani to help them calculate the same for large n. Help her to code the
solution which print the total number of ways modulo (10 8 + 7).

Input
The first line of the input contains number of test cases, T. Then follows T lines containing a number
n, size of baord.

Output
For each test case print the number of ways to cover a 1-by-n board modulo (10 8 + 7).

Constraints:
a) 0 < T <= 10 3

b) 0 < n <= 10 6

Example
Input:
4123500

Output:
12312577845

1
Note:
a) Perfect cover means the whole board should be completely covered, no two monomino/domino
overlap each other, neither any of them lie outside of the boundary of baord.

b) Monomino is of block size 1-by-1, and orientation of the monomino is not to be considered.

c) Size of a domino is 1-by-2.

Added by: lost


Date: 2012-04-16
Time limit: 2s
Source limit:50000B
Languages: All

2
(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 (tutorial)

11390. Hidden Key


Problem code: FINDWORD
One day while roaming in a mysterious island Mr. TMT (surely along with laptop on his side), he
found a square sized wooden piece. When he watched it thoroughly, he finds that the wooden piece
can be divided into NxN square blocks, each of size 1x1. In each block, there is a character engraved
on it. He already have magic book with him, which containts a list of command. Now he wonders if
these commands are engraved on the wooden piece or not.

As he is good at puzzles, he instantly code a solution for it, which takes the content of wooden piece
and the list of command and tell whether the respective commands exists in the wooden piece or not.

While searching for a command he can read the blocks horizontally (to right), vertically (to bottom), or
right-diagonally (to right-bottom). When started to search in particular direction, he cannot change it in
the midway.

Input
First line contains an integer N, size of block is NxN. Then follows N lines, each line cantains N latin
lowercase character. Then follows a integer T, number of commands in his magic book. Then follows
T lines. Each line contain a integer M followed by a string of length M. These are the commands.

Output
For each command, print "YES" if it can be found in wooden piece, otherwise "NO" (quotes for
clarity).

Constraints
a) 1 <= N <= 50

b) 1 <= T <= 50

c) 1 <= M <= N

d) All string contains only lowercase latin characters.

1
Example
Input:
5pcsinpavninneetytwokvkala43 kal4 aeoa2 cp5 nitka

Output:
YESYESNOYESExplanation for sample test case:1. kal: found at position (5, 2), while reading horizontally.2. aeoa: found at position (2, 2) while reading diagonally.3. cp: Can’t be found any where, but at position (1, 2) while reading left-diagonally, which is not allowed.4. nitka: found at position (1, 5) while reading vertically.

Added by: lost


Date: 2012-04-16
Time limit: 1s
Source limit:50000B
Languages: All

2
(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)

11398. Do You know your Algorithms


Problem code: TECHELN5
Jonny has just learned Sorting in his algorithm classes. He wants to show his mother how good he is
with algorithms, but his mother is very clever. She wants to ensure Jonny has learned the key concepts
and not just the methods. 

She places N integers in order 1, 2, 3, ..., N. and asks Jonny to reverse this sequence, i.e convert this
sequence to N, N-1, .... , 3, 2, 1. The only operation Jonny is allowed to do is to choose any 4 (not
necessarily adjacent) integers and perform the following action: exchange the leftmost integer with the
rightmost one and similarly swap the remaining two integers in the middle, both swaps must occur. He
can perform this operation as many times he want.

Jonny has a feeling that this may not always be possible for all sequences, so before starting he wants
to know whether it is possible to do this task.

Input Format

First line of the input contains T, the number of testcases. Then follow T lines, each containing an
integer N.

Output Format

For each of the given numbers print YES if the task is possible, otherwise NO.

Sample Input

2
5
6

Sample Output

YES
NO

Constrains

1 <= T <= 10
4 <= N <= 1,000,000

1
Added by: Nikunj Jain
Date: 2012-04-17
Time limit: 1s
Source limit:50000B
Languages: All
Resource: https://sequoia.interviewstreet.com/challenges/dashboard/#problem/4f889e56432a3

2
(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 (tutorial)

11403. EASY MATH 2


Problem code: EASYMAT2
You will be given 4 numbers
nmad

find count of numbers between n & m (inclusive) which dont have the digits present in (a) (a+d) and
(a+2d)

Input

first line has number t - number of test cases.each test case has 4 numbers          n m a d

Output
Single line having single number giving the count

Example
Input:

31 10 2 220 100 3 3100 1000 4 5

Output:

36

294

NOTE - 1<=n<=m<= 2^32 0<=a<= 2^32 0<=d<=2^32 2<=t<=100

Added by: Devil D


Date: 2012-04-18
Time limit: 0.5s-1s
Source limit:20000B
Languages: All
Resource: Own

1
(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)

11457. New iPad


Problem code: VUDBOL4
The new iPad is here, with retina display. It has more resolution than iPad2. Because for each pixel in
iPad2 exists 4 pixels in new iPad. That means that the new iPad has twice width and twice height.
>
> With this new resolution we need change some icons’ sizes. But we don’t have time for create new
images. We only change the black and white images. Create another image that is 4 pixels for each
pixel of the old image.
>
>

Input
The input consists in multiple test cases.
> Each test case begins a line containing an integer number "N" (1 <= N <= 50) the width and height
of the icon. In the following "N" lines are "N" characters for line. The characters ’1’ means black
pixels and ’0’ means white pixels.
> The end of input is indicated by a line with one zero. This is not a part of any test cases.
>
>

Output
For each test case print a (N+N)*(N+N) matrix representing the new icon with the new resolution for
the new iPad.
>
>

Example
Input:
4
1000
1011
1000
1111
2
10
01
0

Output:
11000000

1
(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 (tutorial)

11464. Book Shelves(tutorial)


Problem code: SHLF
When Farmer John isn’t milking cows, stacking haybales, lining up his cows, or building fences, he
enjoys sitting down with a good book. Over the years, he has collected N books (1 <= N <= 100,000),
and he wants to build a new set of bookshelves to hold them all.

Each book i has a width W(i) and height H(i). The books need to be added to a set of shelves in order;
for example, the first shelf should contain books 1...k for some k, the second shelf should start with
book k+1, and so on. Each shelf can have a total width of at most L (1 <= L <= 1,000,000,000). The
height of a shelf is equal to the height of the tallest book on that shelf, and the height of the entire set
of bookshelves is the sum of the heights of all the individual shelves, since they are all stacked
vertically.

Please help FJ compute the minimum possible height for the entire set of bookshelves.
INPUT FORMAT:

* Line 1: Two space-separated integers: N and L.

* Lines 2..1+N: Line i+1 contains two space-separated integers: H(i) and W(i). (1 <= H(i) <= 1,000,000; 1 <= W(i) <= L).

SAMPLE INPUT

5 10 

5 7 

9 2 

8 5 

13 2 

3 8

INPUT DETAILS:

There are 5 books. Each shelf can have total width at most 10.

OUTPUT FORMAT:

* Line 1: The minimum possible total height for the set of bookshelves.

SAMPLE OUTPUT :

1
21

OUTPUT DETAILS:
There are 3 shelves, the first containing just book 1 (height 5, width 7), the second containing books 2..4 (height 13, width 9), and the third containing book 5 (height 3, width 8).

Added by: ??????


Date: 2012-04-28
Time limit: 30s
Source limit:50000B
Languages: All
Resource: Usaco open 2012

2
(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)

11491. Addict to Letters


Problem code: SALVA1
Salvador is an architect and a words lover, and he wishes to put in each of his building models metal
letters referent to their names, but he does not know how to name them, because the weight of the
letters can destroy them. Besides, Salvador has every of his metal letters in order, so he doesn’t want
any combination of them that can break the established order, that’s why he needs you. He wants a
program that, given the N metal letters, the maximum weight of the model and the weight of every
letter, output how many subsequences he can form with them, in order to not pass the weight limit, the
number of letters in the largest formed word, and the weight associated with it. The subsequences must
satisfy the next conditions:

They must be formed with 2 or more letters.


They cannot pass the weight limit.
A new subsequence is counted when a subsequence is builded and "destroyed".
We mean with "destroyed" when we delete the first letter of the actual subsequence, or we reach
the end of the subsequence, resuliting in a new subsequence that not pass the weight limit.

Input
The input consists of an integer T denoting the number of test cases. Then you will receive a string of
M characters and an integer P, representing the metal letters Salvador has in the order he wanted, and
the maximum weight of the model respectively. Then M lines will follow, with a character and an
integer I separated by a space, denoting the metal letter and the weight associated to it. You must
assume the string will consist of uppercase letters and underscores ( _ )

Output
The output must contain three integers, indicating the number of possible subsequences that can be
formed (following the mentionated rules), the length of the longest word that can be formed, and the
weight associated to it. If there are two or more longest words, your program must output the weight
corresponding to the word with the minimal weight.

1<=T<=600

1<=M<=4000

1<=P<=1000000

1
1<=I<=1000000

Example
Input:

4LE_VOY_DANDO 200L 50E 100_  75V 30O 120Y 200_  75D 150A 25N 30D 150O 120HELPING 50H 50E 100L 5P 5I 20N 10G 5
EXAMPLE 100 E 20 X 4 A 16 M 24 P 44 L 60 E 50
A 1000
A 1000Output:
7 2 557 5 457 4 640 1 1000sample test case 3,valid subsequences::EXEXAEXAMXAMXAMPAMPMP

Added by: initiald159


Date: 2012-05-05
Time limit: 1s-2s
Source limit:50000B
Languages: All except: PERL PERL 6

2
(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)

11492. Fast Schedule


Problem code: RPLF
 

 Rodolfo is preparing for an important programming contest, but he have a disorganized schedule, he
haven’t organized his day and he’s going desperate on the task, he says to you "Man, I spend K
minutes on every activity I start in the morning, can you help me with the ending hour of the activity?"

It is known that Rodolfo’s day start every single day at 9’o clock, some activities started by Rodolfo
can have a duration of more than the 24 normal hours of a day! So, beware of this, by example, if
Rodolfo’s activities lasts for twenty minutes, then Rodolfo will end his activities at 09:20.

INPUT:

The first line of input will contain an integer T denoting the T test cases, then, T lines will follow.
Each of the following line will contain a number N, this number means the minutes of duration of
Rodolfo’s activities.

OUTPUT:

Output the string "Scenario #i: " where i is the test case you are analyzing followed by the ending hour
of all Rodolfo’s activities, format (hh:mm)

SAMPLE DATA:

1
INPUT OUTPUT
4 Scenario #1: 09:20

20 Scenario #2: 10:01

61 Scenario #3: 09:01

1441 Scenario #4: 13:00

240

CONSTRAINTS:

0<=N<=10^8

Added by: David Moran


Date: 2012-05-05
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own Problem used for the RPL contest

2
(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)

11505. EASY MATH 3


Problem code: EASYMAT3

You will be given 4 numbersn m a dfind count of numbers between n & m (inclusive) which can be formed by the digits present in (a) (a+d) and (a+2d)Number will not have preceeding ’0’.Inputfirst line has number t - number of test cases.each test case has 4 numbers          n m a d

Output
Single line having single number giving the count

Example
Input:

31 14 2 220 100 3 3100 200 4 5

Output:

399

NOTE - 

1<=n<=m<= 10^8 0<=a<= 10^8 0<=d<=10^8 2<=t<=100

Added by: Devil D


Date: 2012-05-09
Time limit: 0.5s-1s
Source limit:20000B
Languages: All
Resource: Own

1
(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)

11506. ANYTHING FOR ATTENDANCE


Problem code: DIE4MARK
Anything for Attendance

Most engineering students were attending classes just


because there were 5% marks for attendance. Those
students were just physically present and mentally
absent at the classes. So the Dean of the college
suddenly announced a new system that there will be no
marks for attendance. For any given student, you have
to determine whether this announcement is a profit or
loss for that student. You are given the percentage of
marks the student got in the old system and the
percentage of marks the student scored in attendance.
(See explanation for test cases)
 

Input Specification:

The first line consists of an integer t, the number of test cases. Then for the next t lines each test case
consists of two integers a and b where ‘a’ is the percentage of marks the student got in the old system
and ‘b’ is the percentage of marks the student scored in attendance. 

Output Specification:

For each test case, output "profit" if the student’s mark improves in the new system or output "loss" if
the student’s mark decreases because of the new system or output "same" if there’s no change.

1
Note: Spoj is Case Sensitive

Input Constraints:

1<=t<=100000

0<=b<=5

b<=a<=100

Sample Input:

74 0

55

60 3

93 4

68 3

59 3

50 3

Sample Output:

profit

loss

same

profit

same

same

loss

2
Explanation of testcases:

Case 1: The student has never attended classes. So the new system is clearly profit for the student.

Case 2: The 5 marks came only from attending classes. So the new system is clearly a loss for the
student.

Case 3: The new system, ignoring the attendance will not change the marks of the student.

Case 4: Converting to the new system, the mark changes to 93.68 which the professor will round it to
94. So it’s a profit for the student.

Case 5: Converting to the new system, the mark changes to 68.42 which the professor will round it to
68. So it’s neither profit nor loss for the student.

Note: The professor will round 75.49 into 75 and 75.50 into 76.

Added by: cegprakash


Date: 2012-05-10
Time limit: 1s
Source limit:50000B
Languages: All

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 (classical)

11507. SPIRAL RUN


Problem code: SPIRAL2
SPIRAL RUN

The run starts from the center point. At each step you have to move in the spiral path as shown in the
figure. At each step you can move exactly 1 unit(say 1cm). The path of the run should not overlap.
Find the direction of the next move after n moves.

Input Specification:

The first line consists of an integer t, denoting the number of test cases. For the next t lines, each line
consists of an integer n, the number of moves already made.

Output Specification:

1
For each test case find the direction of the next move after n moves.

Note: The first letter alone must be capitalized

Input Constraints:

1<=t<=100

0<=n<=50000000

Sample Input:

12

801803

12345678

85236561

801803

85236561 

Sample Output:

North

East

South

South

2
West

East

South

East

South

Added by: cegprakash


Date: 2012-05-10
Time limit: 2s
Source limit:50000B
Languages: All

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 (tutorial)

11514. N-ARY TREE


Problem code: NARYTREE
N-ARY TREE

A binary tree is a tree data structure in which each node has at most two child nodes. Similarly an
n-ary tree is a data structure in which each node has at most n child nodes.

Given the number of nodes ‘m’ in an ‘n’ary tree, find the minimum height of the tree.

Input Specification:

The first line consists of an integer t, denoting the number of test cases. Then for the next t lines, each
test case consists of two integers ‘m’ and ‘n’ as defined above.

Output Specification:

For each test case find the minimum height of the tree.

Input Constraints: 

1<=t<=100

0<=m<=1000000

1<=n<=1000000

Sample Input:

05

12

1
82

92

111 10

112 10

Sample Output:

Added by: cegprakash


Date: 2012-05-11
Time limit: 1s
Source limit:50000B
Languages: All

2
(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 (tutorial)

11522. CHOCOLATES
Problem code: CHOCLATE
CHOCOLATES

A shopkeeper sells 1 chocolate at Rs. A each. You can exchange B wrappers for 1 chocolate. If you
have N Rs. how many maximum chocolates can you get?

Input Specification:

The first line consists of an integer t, the number of test cases. Then for the next t lines, each test case
consists of 3 integers A, B and N as defined above.

Output Specification:

For each test case find the maximum number of chocolates that you can get.

Input Constraints:

1<=t<=1000

1<=A<=20

2<=B<=11

0<=N<=1000000

Sample Input:

120

125

1
7 10 7

2 11 4

1 10 4

Sample Output:

Added by: cegprakash


Date: 2012-05-14
Time limit: 2s
Source limit:50000B
Languages: All

2
(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 (tutorial)

11537. FACTSUM
Problem code: IN1
Given two numbers. Find sum of their minimum and maximum prime factors.

Input
Two numbers a and b;

1<=a,b<=10^20

Input terminates with a zero

Output
As described;

Example
21324567891 2737257367350 

Output: 10921790

Explanation:minimum prime factors of a and b are 3 and 3 respectively;

and maximum prime factors are 4932817 and 5988967.

so their sum is 10921790.

Added by: CounterinsurgectoR


Date: 2012-05-16
Time limit: 1s-6s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: Own Problem

1
(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 (tutorial)

11556. Find the minimum no of squares


Problem code: SQREASY
Little Johny is a very playful kid and often he thinks about petty problems he comes across. One day
he had a chocolate bar with him. He can eat a chocolate bar if and only if it is in the shape of a square
whose edge is a multiple of  unit length .Little Johny eats atmost one piece of chocolate everyday. He
wondered what is maximum number of days he can keep eating the given chocolate bar of  length L
and width W. We all know that the answer is L*W if he eats 1*1 chocolate bar a day but Little Johny
being a very greedy kid wants to finish the chocolate bar as soon as possible .Help him by finding the
minimum number of days within which he can finish the chocolate bar.

Input
Input wil start with an integer T (the number of test cases) followed by T lines 

each line will contain two integers L and W (L and W are between 1 and 10^7 inclusively)

note: width can also be greater than hieght

Output
For each test case output the answer in a new line

Example
Input:
31 18 59 4 Output:
156Limits :  1<=T<=1000 1<=L,W<=10000000

Added by: Ranjith Mudalaiyar


Date: 2012-05-23
Time limit: 1s
Source limit:50000B
Languages: All
Resource: own problem

1
(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 (tutorial)

11559. Are you smart enough


Problem code: DUMBPROB
Little Johny as we all know is very playful and he loves to solve geometrical problems.He is really
smart too (yes seriously he is smart enough to write programs for very complex tasks). One day he
wrote the following piece of code :

  int flag=0;
   for(int i=a;i<=b;i++){
   
     if(i==c)flag=1;
   
   }
   if(flag==1)printf("Yes, the point c is between point a and b\n");
   else printf("NO, the point c is not between a and b\n");
  
   Little Johny wrote the above piece of code to find whether the one-dimensional integral point c is
between a and b or not (and he thinks he is really smart after writing this code).
   Another day he decided to write a program for finding whether a two dimensional integral point
(x,y) is inside a rectangle (the edges of the rectangle are parellel to the x or y axis).He realized that he
cannot do it in time so he asks you for help .Your task is to write a program for finding whether a point
(x,y)  lies inside a given rectangle or not.

input description:

The rectangle will be describe by the lower left point (X,Y) followed by the base B and hieght H

(So the coordinates of the rectange are (X,Y) , (X+B,Y) , (X+B,Y+H) , (X,Y+H) in anti clockwise
order ).

You will be given many points to process for each point either print "OUTSIDE" if the point is outside
the rectangle or print "INSIDE" if the point is inside the rectangle in a new line (Quotes are only for
clarity you dont have to print it in the output)

The last point will be ( 0,0 ) you have to stop processing data after that

note : all numbers in the input will be between 1 and 10^8 inclusively and no point will be on the
rectangle itself

input

1
XYBH

X1 Y1

X2 Y2

..........

00

Example
Input:

10 15 10 2011 1715 2523 6754 762 914 300 0


Output:

INSIDEINSIDEOUTSIDEOUTSIDEOUTSIDEINSIDE 

Added by: Ranjith Mudalaiyar


Date: 2012-05-23
Time limit: 4s
Source limit:50000B
Languages: All
Resource: own problem

2
(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 (tutorial)

11567. Find the missing card


Problem code: CARDSMIS
Little Johny loves playing cards. He had a deck containing N cards(all cards are numbered from 1 to
N). He gave the deck of cards to his sister Derp. Derp being very careless lost a card and gave the deck
back to Johny thinking it was very hard for Johny to find the card lost by her. True to Derp’s
assumption Johny couldn’t find the missing card. Your task is to help Johny to find the missing card.
input :
first line will contain an integer T (number of test cases <=10)
each test case begins with an integer N (2 <= N <= 10^6 )
next line will contain N-1 space seperated distinct integers in random order(all integers are in the range
(1,N) inclusively)
output :
for each test case output the missing card in a new line

Example
Input:
574 5 2 1 7 651 2 3 488 7 6 5 4 3 161 3 5 2 432 1Output:35263

Added by: Ranjith Mudalaiyar


Date: 2012-05-24
Time limit: 10s
Source limit:50000B
Languages: All
Resource: own problem

1
(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)

11572. A Famous Music Composer


Problem code: MUSIC2
Mr.B is a famous music composer. One of his most famous work was his set of preludes. These 24
pieces span the 24 musical keys (there are musically distinct 12 scale notes, and each may use major or
minor tonality). The 12 distinct scale notes are:

A A# = Bb B C C# = Db D
D# = Eb E F F# = Gb G G# = Ab

Five of the notes have two alternate names, as is indicated above with equals sign. Thus, there are 17
possible names of scale notes, but only 12 musically distinct notes. When using one of these as the
keynote for a musical key, we can further distinguish between major and minor tonalities. This gives
34 possible keys, of which 24 are musically distinct.

In naming his preludes, Mr.B used all the keys except the following 10, which were named instead by
their alternate names:

Ab minor A# major A# minor C# major Db minor


D# major D# minor Gb major Gb minor G# major

Write a program that, given the name of a key, give an alternate name if it has one, or report the key
name is unique.

Input
Each test case is described by one line having the format note tonality, where note is one of the 17
names for the scale notes given above, and tonality is either major or minor. All notes names will be
uppercase.

Output
For each case output the required answer, following the format of the sample.

1
Example
Input:
Ab minor
D# major
G minor

Output:
Case 1: G# minor
Case 2: Eb major
Case 3: UNIQUE

Added by: [Trichromatic] XilinX


Date: 2012-05-25
Time limit: 1s
Source
50000B
limit:
Languages: All
ACM/ICPC World Finals 2012 - Dressing Rehearsal Contest, also used in FDU Local
Resource:
Contest 2012

2
(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)

11581. The Famous Clock


Problem code: CLOCK2
Mr. B, Mr. G and Mr. M are now in Warsaw, Poland, for the 2012’s ACM-ICPC World Final Contest.
They’ve decided to take a 5 hours training every day before the contest. Also, they plan to start
training at 10:00 each day since the World Final Contest will do so. The scenery in Warsaw is so
attractive that Mr. B would always like to take a walk outside for a while after breakfast. However,
Mr. B have to go back before training starts, otherwise his teammates will be annoyed. But here is a
problem: Mr. B does not have a watch. In order to know the exact time, he has bought a new watch in
Warsaw, but all the numbers on that watch are presented with Roman numerals. Mr. B cannot
understand such kind of numbers. Can you translate for him?

Input
Each test case contains a single line indicating a Roman number that to be translated. All the numbers
can be found on clocks. That is, each numbers in the input represents an integer between 1 and 12.
Roman numbers are expressed by strings consisting of uppercase I, V and X. See the sample input for
further information.

Output
For each test case, display a single line containing a decimal number corresponding to the given
Roman number.

Example
Input:
I
II
III
IV
V
VI
VII
VIII
IX
X
XI
XII

Output:
Case 1: 1
Case 2: 2
Case 3: 3
Case 4: 4

1
Case 5: 5
Case 6: 6
Case 7: 7
Case 8: 8
Case 9: 9
Case 10: 10
Case 11: 11
Case 12: 12

Added by: [Trichromatic] XilinX


Date: 2012-05-25
Time limit: 1s
Source limit:50000B
Languages: All
Resource: FDU Local Contest 2012

2
(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 (tutorial)

11600. Another Mathematical Problem


Problem code: SUMOFPOW
Little Johny suddenly found a great amusement towards numbers. Blame his crush over his maths
teacher or anything, it didnt really bother him. One day his teacher gave him a task for finding the
solution for ( (P^N) + (Q^N) ) {P power N + Q power N} given P, Q and N. Given Johny’s intense
crush he solved it very quickly. Seeing this his teacher asked him to calculate ( (P^N) + (Q^N) ) but
this time she gave P+Q and P*Q instead of P and Q. Johny set to work and then he understood the
difficulty of this problem. Guess what? . It is the same story he asks you for help.
Input :
first line will contain an integer T (<=15) denoting the number of test cases
three integers p+q, p*q and n will be given for each test case in a seperate line
for every test case output the corresponding
output (p^n)+(q^n) in a seperate line
limits : 0<= N <=15, P+Q and P*Q will be in the (-15,15) inclusively.
Note : P, Q, N would be chosen in such a way that the answer fits in a 64 bit signed integer

example:

Input :

6 9 11

6 7 10

123

-5 6 10

2 -4 9

Output:

354294
2808982
-5
60073
38912

1
Added by: Ranjith Mudalaiyar
Date: 2012-05-26
Time limit: 1s
Source limit:50000B
Languages: All

2
(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 (tutorial)

11643. Cross dangerous minefields


Problem code: MINEF1
Minefield will come back in classical with harder test cases where O( n^2 ) won’t pass!

Leo need to cross minefields, as fast as possible. You are given a map, a square, Leo start at upper left
corner and need to join the opposite corner. The only allowed moves are down or right on the map.
Sometimes it’s possible, sometimes not! You have to count the number of ways Leo can take.

Input
The input begins with the size N of the square in a single line. The next N lines are the description of
the map."#" is a mine, "." is a safe place. See the example for details.

Output
Print the number of ways, give your answer modulo 1000000007.

Example 1
Input:
4
....
.#..
##..
.#..

Output:
4

Example 2
Input:
4
...#
.##.
#...
....

Output:
0

At the start of reading third line, one can quickly answer 0.

1
Constraints:
1 <= N <= 1000

Informations:
Start and stop corner are safe. The density of mines is near 1/4, and in some test cases it is quickly
clear that there’s no way for Leo.

Added by: Francky


Date: 2012-06-02
Time limit: 4s
Source limit:50000B
Languages: All
Resource: Inspired by Prologin, DF11

2
(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 (tutorial)

11722. HELP ABHISHEK


Problem code: COMPLEX1
ABHISHEK is weak of mathematics he is not able to solve the sequences frequently. So he invited
topcoders to develop a program for solving the sequence. He managed to solve the other kind of
sequences except one kind.
The sequence description is as follows:

(x-w)(x-w^2)(x-w^3)(x-w^4).............(x-w^n-1)
here x is a number and w is nth root of unity. 

Input
first line contain number of test cases t. Then t line follow x and n. x and n seprated by a space.

Constraints:-

2<=x<=1000

2<=n<=1000

t<=410

Output
print result per case according to above sequence and also keep in mind if there is any term in decimal
then write it in form of  num/deno. see the I/O for further detail

Example
Input:

5 10
Output:
9765624/4

IF your solution is fast enough then go for harder classical problemhttp://www.spoj.pl/problems/COMPLEX2/

1
Added by: Abhishek Mishra
Date: 2012-06-16
Time limit: 5s
Source limit:50000B
Languages: All
Resource: own problem

2
(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)

11728. Forest Fires


Problem code: FFIRE
Forest fires are really dangerous, and can be started by even the smallest flame. Spreading from tree to
tree, fires can engulf an entire forest in a matter of weeks. Given a map of a forest with locations of
where a fire (or multiple fires) might have started, determine how long it would take the fire to capture
the entire forest.

Input
The input contains a 10x10 map (i.e. 10 lines each consisting of 10 characters), where each character
in the map is one of the following:

. - blank space
T - a tree
F - a tree on fire

Fires only spread from trees that are on fire to adjacent trees in one of four directions: North, South,
East or West (so not diagonally). It takes 1 unit of time for the fire to spread from one location to the
next. The fire spreads in all 4 directions at the same time (i.e. fires move outwards from the source).

Output
The output should contain the time it takes for the fire to capture the entire forest (i.e. the time it takes
for every tree to catch fire). If some piece of the forest survives, output -1.

Example
Input:

..........
..........
..........
..........
..TTTTT...
..F...F...
..........
..........
..........
..........

Output:

1
3

Added by: Amlesh Jayakumar


Date: 2012-06-18
Time limit: 1s
Source limit:50000B
Languages: C++ 4.3.2 C++ 4.0.0-8 C99 strict JAVA
Resource: DWITE Programming Contest 2010

2
(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 (tutorial)

11788. Ishika and Kashish


Problem code: ARD2
Maaz is a very flirty boy.Once he was sitting in the mess and two girls ,Ishika and Kashish came and
sat behind him.Maaz being naughty thought he has a chance to make one of them as future partner!!
 So he decided to entertain girls with his favourite subject maths.He said to girls that he will tell a
number  ’n’  and Ishika needs to answer the difference between the nth fibbonaci number modulo
123456789 ( f(n) % 123456789) and the nth prime number and Kashish needs to speak out their
sum.Both girls being fool enough started playing with maaz.

fibbonacci Series-- 0,1,1,2,3......

Prime numbers---2,3,5,7,.......

Now you task is to calculate the modulus of both the  values and print them.

Well,MAAZ loves Kashish more!! Cool

Input
First line contains t == number of test cases and next t lines contain a single number n.

1<=n<=5761460

Output
Two numbers as described seprated by a space.

Example
Input:
1

10

Output:
5 63

1
Added by: CounterinsurgectoR
Date: 2012-06-28
Time limit: 1s-20s
Source limit:33333B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: Own Problem

2
(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)

11791. Integer Factorization With A Twist


Problem code: SUMUP2
Given a positive integer (K > 2), with prime factorization:

K = p1^a1 * p2^a2 ... * pn^an (EXCLUDING 1)

Compute the following:

S = a1*p1 + a2*p2 ... + an*pn.

Input
A integer K on each line (2 <= k  <= 10^15)

Take input until EOF is occured

Output
For each integer compute the S = a1*p1 + a2*p2 ... + an*pn and output it on a single line.

Example
Input:67 180428938584693088816816927791714636917

Output:
57120285967187673607091008039
WARNING: More than 10000 integers in test file. Use I/O optimization too.EDIT: All the solutions have been rejudged

Added by: Better late than never !!!


Date: 2012-06-29
Time limit: 1s-2s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 C99 strict
Resource: RamjiLal Sir

1
(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 (tutorial)

11807. Think Different


Problem code: BEANALGO
Exponentiating by squaring is a general method for fast computation of large integer powers of a
number.The same idea allows fast computation of large exponents.
For example, the evaluation of
  x^13=((x^2 . x)^2)^2 . x 
  Algorithm needs only 5 multiplications instead of 12 (13-1)
 
  Task
  Write a program that:

  reads the parameters of the algo from the standard input, computes the number of multiplications
we need ,writes the result  to the standard output.

Input
The input begins with the integer t, the number of test cases. Then t test cases follow. For each test
case the first and only line of the input contains exactly one integer n
0<=n<=10^18

Output
For each test case the output contains exactly one integer equal to the number multiplications we have
to compute in this given algo.

Example
Input:
33510 O  utput:
234

Exponentiating by squaring is a general method for fast computation


of large integer powers of a number.The same idea allows fast
computation of large exponents modulo a number.
For example, the evaluation of
  x^13=((x^2 . x)^2)^2 . x  
  Algorithm needs only 5 multiplications instead of 12 (13-1)
  
  Task
  Write a program that:
  reads the parameters of the algo from the standard input,

1
  computes the number of multiplications we need ,
  writes the result to the standardExponentiating by squaring is a general method for fast
computation
of large integer powers of a number.The same idea allows fast
computation of large exponents.
For example, the evaluation of
  x^13=((x^2 . x)^2)^2 . x 
  Algorithm needs only 5 multiplications instead of 12 (13-1)
 
  Task
  Write a program that:
  reads the parameters of the algo from the standard input,
  computes the number of multiplications we need ,
  writes the result to the standard output. output.

Added by: MRS. BEAN


Date: 2012-07-01
Time limit: 0.100s
Source limit:50000B
Languages: All
Resource: Own Problem

2
(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 (tutorial)

11821. Combinatorial Sequence


Problem code: COMBD
Your task is to evaluate  the following series for a given n

2^n - ((n-1)C(1))*2^(n-2)  + ((n-2)C(2))*2^(n-4) - ((n-3)C(3))*2^(n-6)+ ....................

(n)C(r) denotes n choose r.

Power of 2 is always non-negative.(i.e series terminates when either power of 2 goes negative or
combinatorics becomes undefined)

Input
First Line of Input Contains the number of test cases (t<=100000) ,then follows t lines ,each containg
the value of n.(n<=100000)

Output
You should output t lines, ith line contains answer of the ith test case

Example
Input:
212Output:23

Added by: Devendra Agarwal


Date: 2012-07-04
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Own Problem

1
(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 (tutorial)

11852. Power with Combinatorics(EASY)


Problem code: POWRTU
Your task is to calculate a^(b^(exp))

a:provided in input,500=>a>=0

b:provided in input,500=>b>=0

exp=(nC0)^2 + (nC1)^2 + (nC2)^2 + ......+(nCn)^2

n:provided in input,500=>n>=0

Note: The Output for 0^0 should be 1.

nCr denotes n choose r.

As the answer can be too large , you need to output modulo 10^9+7.

Input
The first line of each input file contains number of test cases t(t<=1000).

Then follow a new line.

Then follow t lines,each conating 3 integers,(i.e a b n  in order) each of them seperated by a space.

Output
Output Contains t lines,ith line conatins the answer of the ith test case.

Example
Input:
1

1 1 1

Output:
1

Explanation: In First test case, the Value of exp is 2, value of 1^(1^2) is 1,so output is 1.

1
Added by: Devendra Agarwal
Date: 2012-07-14
Time limit: 10s
Source limit:50000B
Languages: All
Resource: Utkarsh Lath

2
(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 (tutorial)

11876. Finding Majority


Problem code: MAJORITY
Given an array A of N integers in wich the most frequent item appear most than n / 2 times,
calculate this value.

Input
The first line contain N (1 <= N <= 3000000) then N 32-bit integers per line.

Output
The output consists of one number: the most frequent item on A.

Example
Input:
523224

Output:
2

Added by: Frank Rafael Arteaga


Date: 2012-07-19
Time limit: 0.200s-1s
Source limit:50000B
Languages: All
Resource: Classic problem

1
(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 (tutorial)

11877. Upcoming Demons


Problem code: RAED0001
Archon III is an online Massively Multiplayer Online Role-Playing Game (MMORPG) where users
team up in order to beat powerful demons. The game is split into levels and each level has a demon. In
order to reach the next level your team must first kill the demon of the current level.

The strength of a demon is known as its "Qi" or "Chi", a positive integer coefficient that goes from 0
to 4,000,000,000. To be able to kill a demon you must have a Qi that is at least as large as the
demon’s. Your team increases its own Qi by going into practice mode.

VitaminAC is the best ranked team in the world because it has defeated more demons and thus the
demon with the highest Qi so far. Your team wants to be ranked first and thus must kill the demon
with the next highest Qi. However, VitaminAC also wants to remain on top so they will prepare to
defeat that next demon. You must then beat a demon with a Qi yet higher than the next best one.

You don’t know what the next best demon’s Qi is but Jorge, a team member of your team, estimates it
is Q. Given a list of Qi’s for different demons, return the next highest Qi after Q.

Input
The input has 1 + N lines. The first line contains N (2 <= N <= 1,000,000) and Q(0 <= Q
<= 3,999,999,999), two space-separated integers. N is the number of Qi’s in the list and Q is the
estimated Qi of the next best demon. Then N lines follow. Each of these lines contain a single positive
integer in the range (0 <= Qi <= 4,000,000,000). 

Output
Output the next highest Qi after Q.

Example
Input:
10 500
100300500501600700800900100010000Output:
501

1
Notes: 

It is guaranteed that a next highest Qi exists.


No two demons will have the same Qi.

Added by: kojak_


Date: 2012-07-19
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Roberto Abreu’s Repository

2
(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)

11934. PUT TRINOMO


Problem code: TRINO
Given a m * n chess board , Find out minimum no of places to be covered to make it impossible to put
a L shaped trinomo on it.

eg. In 2 * 2 chess board if you cover any 2 cells , It will be impossible to put a L shaped trinomo on it

1<=n<=10^8

1<=m<=10^8

A trinomo is a L shaped object. 

**

where * represents a cell.

Input
T : no of test cases (T <= 5000)

Next T lines :

every line contain m , n

Output
no of cells to be covered .

Example
Input:
12 2 Output:2

1
Added by: praveen123
Date: 2012-08-02
Time limit: 1s
Source limit:50000B
Languages: All
Resource: general problem

2
(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 (tutorial)

11936. FIBO BIT


Problem code: FIBBIT
Count the number of numbers between two 64 bit numbers a, b that have the sum of their bits equal to
a fibonacci number. E.g Between 15 and 17 there are two numbers that have sum of bits equal to a
fibonacci number.

15: 1111 sum=4


16: 10000 sum=1 (fibonacci)
17:10001 sum=2 (fibonacci)

Input
The 2 numbers start and end 

start < end < 10^18

Output
The number of such numbers between both start and end inclusive

Example
Input:

15 17Output:
2

Added by: priyamehtanit


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

1
(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)

11937. The Dominoes Problem


Problem code: DOM519
 In the last vacation, three ACMers went to spend a week in north coast, enjoying fresh air,
swimming in the sea and being away of traffic and noise. Their day was a little strange, they
spent all the morning sleeping except the first few hours enjoying sunrise, and studying some
Mathematics and AI, in the evening they only played dominoes, american one, they think that
the american one is better than the ordinary one as it has some calculations to play. Their story
was really happy, maybe you will know it from another problem in the contest or you can ask
them after the contest :P
In Dominoes, every piece has two halves, each half contain some points indicating its number,
for example this one indicates (4,2) or (2,4). And to play, if you want to put (3,4) on the ground,
then one of the available sides on the ground must have 3 or 4 in its end.
In the beginning of the game, the one who has the biggest symmetric piece (i.e. that contains two
equal halves) starts the game e.g. (6,6), (5,5), ..etc. After that each player must fill one of the 4
directions of that first piece, and if the player doesn’t have a suitable card he should take from
the rest of the cards on the ground. For example, if the first card on the ground was (6,6), then in
the next four turns, players must play a card that contains 6 in any of its halves. So we have 4
sides of dominoes, if you put a card that lets the summation of all 4 sides S be divisible by 5, then
you get S/5 integer points.
For example, if we have a state like that:

1
We have total score = (5+5) + 3 + 0 + (3+3) = 19, if we put a card with (0,1) in the right side then
the score will be = (5+5) + 3 + 1 + (3+3) = 20, in this case player gets 4 points.
Note that if there is a symmetric card in some side, then you should count both halves like (5,5)
one, we count 5+5.
You will be given a board and some cards and you should determine the maximum score you
can get by any of your cards.
Input
You will be given R, C, N, M. R and C indicate the number of Rows and Columns of the board
respectively. N is the number of cards in the given board, and M is the number of cards with the
player. After that you will be given an R*C board, each cell will be either ‘*’ empty place, or
A-Z character indicating the ID of a card at this place, then there will be N*4 lines, each 4 lines
will be on that form:
- 1st line has a A-Z character, ID of the card
- 3 lines showing the two halves of the card, each half has a 3*3 grid and they are separated by a
space on each line of them (more details are in the samples).
After that there will be 3*M lines each 3 lines will be two space separated 3*3 grid indicating a
card of yours, from these M cards you will choose the one that maximizes your score.
Each grid will be either ‘*’ or ‘#’, that’s how we will represent cards, so if we want to represent
(3,5), it will be
#** #*#
*#* *#*
**# #*#
and here is a list of the numbers:
(0) (1) (2) (3) (4) (5) (6)
*** *** #** #** #*# #*# #*#

2
*** *#* *#* *#* *** *#* #*#
*** *** *** **# #*# #*# #*#
Please note that in each card description, the second half represents the one at the outer side(the
side used in score computations). And each row or column is guaranteed to have at least one
card ID.
N,M,R,C are all positive integers less than ten.
Output
you should print only one integer in a line, with the wanted score, and if we can’t get one, please
print -1.
Sample Input
3463
*B**
FADE
*C**
A
#*# #*#
#*# #*#
#*# #*#
B
#*# ***
#*# ***
#*# ***
C
#*# #**
#*# *#*
#*# **#
D
#*# #**
#*# *#*
#*# ***
E
#** #*#
*#* ***
*** #*#
F
#*# ***
#*# *#*
#*# ***
*** #**
*** *#*
*** ***
#*# ***
*** *#*
#*# ***
#** ***
*#* ***
**# ***
Sample Output
2

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 (tutorial)

11960. Prime Factorization


Problem code: OPCPRIME
 

Given a number n (n<=10^12) print all its prime factors in strictly ascending order.(Note each prime
factor should be printed on a new line)
Warning: Use long long int for taking input.Integer will overflow. The format specifier for long
long int is %lld
Sample Cases :
Input:
60
Output:
2
3
5

Another Example:

Input:
100
Output:
2
5

Added by: bashrc is back


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

1
(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 (tutorial)

11961. Party trouble


Problem code: MNNNITPA
 

Chintamani is throwing a party tonight(YAY!!!:) ) But there is a slight problem. He ordered a packet
of toffees.Fussy he is,he had given strict orders to the shopkeeper that in the packet all toffees should
be of different kind.That is no more than one toffee of each variety should be there.
Each type of toffee has a unique identification number written on it. He has recieved the packet from
the shopkeeper but he wants to check the same. He starts taking out toffee from the packet one by one
saying the id number of the toffee.
Help him in this task by telling him whether a toffee with the id number he just said has occured
before or not.

Input :Â
The first line of the input will be the number of test cases(T<=10). For each test case first line contains
one integer n denoting the number of toffees in the packet 0 <= n <= 10^6, .n lines follow each
containing the id number for a toffee. 0<=id<=10^9

Output :
You have to output total n lines for each test case . For each input if the toffee with the given id has
already occurred output "DUPLICATE" else output "OK"
Sample Cases :
Input:
2
4
7
5
1
5
3
2
2
1
Output:
OK
OK
OK
DUPLICATE
OK
DUPLICATE
OK

1
Added by: bashrc is back
Date: 2012-08-10
Time limit: 1s-2s
Source limit:50000B
Languages: All

2
(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 (tutorial)

11976. Permutation
Problem code: PERMUN
You will be given a permutation of first N natural numbers.Then you will be asked to print the
smallest index of the array which contains the number between a given range(inclusive).Refer
Iput-Output for more details.

Input
First line contains two integers N and Q separated by a space.

Second line contains N integers separeted by a space.(From 1 to N in any order)

Now Q line follows :Each line contains two integers A and B separated by space.

Output
You must Output exactly Q lines each containg  the answer.

Constraint:

N<=100000,Q<=100000,A<=B<=100000.

Example
Input:

2 2
2 1
1 2
1 12 2
2 1

Output:
1
2

Added by: Devu


Date: 2012-08-14
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Surendra Baswana

1
(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 (tutorial)

11989. Factorial large


Problem code: OPC1708C
 

Given a number n print its factorial%(10^9+7)

Given a number n print its factorial%(10^9+7)

Input
 

First line contains an integer t (t<=10000). 

t lines follow.Each line contains an integer n. (0<=n<=1000000)

Output

For each test case print factorial(n)%(10^9+7)

Example
Input:
5
2
3
1
400
0

Output:
2
6
1
390998217
1

1
Added by: bashrc is back
Date: 2012-08-17
Time limit: 1s
Source limit:50000B
Languages: All

2
(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 (tutorial)

11990. Measuring Water


Problem code: OPC1708D
 

Lets solve a puzzle. :)


You are given two beakers of capacity c1 ltrs and c2 ltrs.You have to find out whether you can
measure exactly C ltrs of beer using them?

Lets solve a puzzle. :)

You are given two beakers of capacity c1 ltrs and c2 ltrs.You have to find out whether you can
measure exactly C ltrs of beer using them?

Input

The first line contains t,the number of test cases.(t<=1000)

Then t lines follow.Each test case contains three space seperated integers c1,c2 and
C.(0<c1,c2,C<=10^15)

You can use the smaller beakers any number of times and assume you have infinite amount of beer in
some measuring tank

Output

Output "YES" (quotes for clarity only) if it is possible to measure C ltrs using c1 and c2,else
output "NO"
Input:
1
2 3 5

1
Output:

YES

Warning: Use long long int for taking input

Added by: bashrc is back


Date: 2012-08-17
Time limit: 0.5s-2s
Source limit:50000B
Languages: All

2
(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 (challenge)

11993. Addicted II
Problem code: TLL238
jhon is compulsive saver, he keeps and amount "n" of piggy banks locked in his room.
He has a list which he wrote with a sequence of 1’s and 2’s that indicate the way that Jhon will
deposit his money on the piggy banks. Every time Jhon gets a penny he rushes to his room and
picks the 2 piggy banks who have the less amount of money, then he looks at the next number
on the sequence. If that number is one (1) he deposits the penny on the piggy bank with the lesser
amount of money. If that number is two (2) he deposits the penny on the next piggy bank with
the lesser amount of money.
Your task is to write a program to help Jhon to determine what is the amount in the 2 piggy
banks with less money once the sequence is overif more than two have the lowest amount of money choose those with lowest indexes.

you can assume that n <= s

Input
There is a single positive integer t on the first line of input. It stands for the number of numbers to follow. Then there are t lines each containing:
n the number of piggy banks, 2 <= n <= 10^9
s the sequence with 1’s and 2’s, 1 <= size(s) <= 10^9

Output
For every number N, output a single line containing what is the amount in the 2 piggy banks with
less money once the sequence is over.

sorted from lowest to highest.

Example
Input:
1

111112

Output:
1 2

Added by: tille


Date: 2012-08-18
Time limit: 0s-2s
Source limit:50000B
Languages: All
Resource: tille

1
(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 (tutorial)

11995. Family Problem


Problem code: DCEPC801
Shima has a very unhappy family. His family members always remain sad for one or the other
problems and they are so addicted to this nature that they cannot live a second without being sad. So to
ensure that they never become happy, every day they take all the problems they had in the last 7 days
and think about all of them and remain sad for the whole day.

For example: Let’s say they had p1 problems yesterday, p2 problems day before yesterday and so on,
then today they will think about all the problems occurred in the last 7 days and remain sad and so
problems for today are total problems (i.e. the summation) that occurred in the last 7 days.

Well sad story isn’t it!? But they were not like this always. It all started when Shima was born on the
Day no. 7 (yes it was the first problem for this strange family). They had no problems from Day no. 0
to Day no. 6 and they had only single problem on the day Shima was born.

Can you predict how many problems they will think about on the Day no. n?? Output it modulo 86399.

Input
First line contains an integer T, the no. of test cases.

Next T lines contain one integer per line, n.

Output
Output T lines, each corresponding to T test cases, containing one integer per line, the problems
Shima’s family think about on Day no. n.

Contraints
1<=n<=1000000000

1<=T<=20

Example
Input:
3

1
1

10

12

Output:
0

16

Added by: dce coders


Date: 2012-08-19
Time limit: 2s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource: Own Problem

2
(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 (tutorial)

11996. Medal Tally


Problem code: DCEPC802
You are the statistician for the 2012 London Olympics. Your job is to keep track of medals won by
different countries and broadcast the medal tally to viewers all around the world. You will be given the
data of the medals won by different countries in no particular order. Output the medal tally. The
convention to be used is sort by the number of gold medals a country has earned. In the event of a tie
in the number of gold medals, the number of silver medals is taken into consideration, and then the
number of bronze medals.

Input
First line contains 2 integers, D (no of lines = no of medals) and N (the no. of countries participating in
Olympics, 1 index based).

Next D lines are of the form "a b" (quotes for clarity). ‘a’ is the country no. (1<=a<=N) and ‘b’ takes 3
possible values (G for a gold medal, S for a silver medal and B for a bronze medal). 

Output
First line should contain the 5 space separated strings: "Country Gold Silver Bronze Total" (Total ->
total no. of medals won by a country).

Next you should output the medal tally in the form of the strings described above, one country per line.

Note however that you should output only those countries in the tally which has atleast 1 medal from
the Olympics. In case where any countries obtain same no. of gold, silver and bronze medal, place that
country above which has less country index. See sample output for more clarification.

Constraints
1<=D<=1000

1<=N<=1000

Example
Input:

1
10 52 G3 S2 B5 G4 B4 B5 B2 G2 B2 S
Output:

Country Gold Silver Bronze Total2 2 1 2 55 1 0 1 23 0 1 0 14 0 0 2 2

Added by: dce coders


Date: 2012-08-19
Time limit: 2s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource: Own Problem

2
(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 (tutorial)

11999. Catalan Powered


Problem code: DCEPC805
This one is pretty simple! Given ‘n’, evaluate n^C(n).

C(n) = (2n)!/(n!*n!*(n+1))

Since the answer can be very large, output it modulo 10^9+7.

Input
First line contains T, the no. of test cases.

Next T lines contain one integer per line, ‘n’.

Output
Output T lines, each for a single test case, containing the required output.

Constraints
0<T<=100

1<=n<=10^5

Example
Input:

224Output:
4

268435456

1
Added by: dce coders
Date: 2012-08-19
Time limit: 2s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource: Own Problem

2
(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)

12071. Point Blank


Problem code: KPB
#include <pointblank>

In a town called "Fernando Pessoa", during the year of 2050, there was a game named PointBlank that
has became very popular in the city. It was a classic online FPS game, where people of each team had
to kill the players of the other team. The winner of a game was the one that killed the most amount of
players after the end of all rounds.

The game was divided in M rounds, each one with N players in different positions. Kurohitsugi, the
best player in the town was challenged to kill all the other N players in each round. He knows that he
has only one chance: if he dies once, he loses.

According to a very experient captain, Sr. Anonymate, the best position where a player can stay in is
exactly a point x that minimizes the sum of the squares of the distances to the other players. And,
magically, we know that the probability of killing an oponent is exactly this point ’x’ divided by 100.

He wants to calculate the probability sum of killing all the soldiers in all the M rounds if he stays in
the point x, but he isn’t good in math or programming, so he asked for your help. 

Input

The first line will contain two integers, N and M (1 <= N <= 20, 1 <= M <= 10^6): the amount of
players and the amount of rounds. Each of the next M lines will contain N integers Xi (1 <= Xi <=
100): the positions of the players.

Output

You have to print the sum of the probabilities of killing all the N players in each round.

Example

1
Input:

12

50

50

Output:

1.00000

Input:

11

100

Output:

1.00000

Input:

42

5 9 98 100

16 17 25 29

Output:

0.081143

Added by: MateusDantas


Date: 2012-08-25
Time limit: 1s-2s
Source limit:50000B
Languages: All
Resource: Mateus Dantas

2
(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)

12072. Playing With Bits


Problem code: IIITA1
Maaz and Aradhya are quite brilliant students of Mathematics and Programming respectively. One
day, their Mathematics Professor Mr. K.P. Singh asked them to solve a Mathematics problem.

Given two number A and B, find the minimum number of bits required to convert binary
representation of A into binary representation of B.

Maaz promised Mr. K.P. Singh that he will be the first one to solve the problem but Aradhya decided
to do it before him. He turns to you for help. Will you be able to help him?

Input
Input consists of t (number of test cases), then t lines follows, each containing two integers a and b (1
<= a,b <= 2^31)

Output
A single line containing the minimum number of bits required to convert binary representation of  A
into binary representation of  B.

Example
Input:
214 3156 68 Output:25Time Limit is kept very strict. Any naive algorithm will never be accepted. 

Added by: Better late than never !!!


Date: 2012-08-25
Time limit: 0.029s
Source limit:500B
Languages: All
Resource: Navneet Sir

1
(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 (tutorial)

12073. Unique Numbers


Problem code: DCEPC901
Ankur Sir, getting bored in class thinks of something to pass his time. He writes all the numbers from
0 to n-1 and then does k operations on these numbers. The operations are of two type-

0 x - Replace each number i by (i+x)mod n


1 x - Replace each number i by (i*x)mod n

Now he wants to know how many unique numbers are there after each such operation and has asked
for your help.

Note- Each operation is done on the numbers that we get after the previous operation and not on
the original.

Input
First line contains n
Second line contains k, the number of operations
Each of the next k lines contain 2 integer p and x

Output
Output k lines, each containing how many unique numbers are left.

Constraints
1<=n<=10^8
1<=k<=20
0<=p<=1
0<=x<=10^8

Example
Input:
3031 80 31 12

Output:
15155

1
Added by: dce coders
Date: 2012-08-25
Time limit: 1s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource: Own Problem

2
(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 (tutorial)

12074. Magical Ladders


Problem code: DCEPC902
Harry Potter and Ronald Weasley were playing a strange Snakes and Ladders game which did not
consist of any Snakes, maybe because they don’t like Snakes (Well anything can happen in the world
of MAGIC).But unfortunately they didn’t have a dice. So, they were forced to move their pieces only
one step forward. Ron, having lost his patience on playing this slow game challenged Harry for a duel
to decide the winner.
Hermoine (the clever girl she is) broke the duel and asked Ron to tell her the total number of ways in
which he could have reached the end starting from 1(only forward jumps of 1 are allowed).If he gave
the right answer , he would be considered a Winner otherwise not . Now your task is to help Ron find
the correct answer.
NOTE : The board is not of square shape as in the actual game and the ladder can go from any lower
point to any higher point. When encountering a ladder, the player has the choice of moving the piece
up the ladder or to move one step forward.

At max 1 ladder can originate from a cell but more than 1 can end at a cell.

Input
First line of input would consist of an integer T specifying the number of test cases.
For each test case , first line would specify an integer representing N the total number of steps i.e. the
end point of the board game.
Second line would consist of an integer L specifying the number of ladders.
The next l lines would consist of 2 space separated integers x and y (x < y) giving the source and
destination points of the ladders.

Output
For each test case you have to output one line containing "Case #z: ans" (quotes for clarity) where z is
the test case number starting from 1 and ans is the the answer to the question Hermoine asked Ron ,
given the board game configuration for the corresponding test case . Since the answer can be very
large , print the answer modulo 10^9+7.

Constraints
1<=N<=10^5
0<=L<N
0<=x<y<=N

1
Example
Input:
1321 32 3

Output:
Case #1: 3

Added by: dce coders


Date: 2012-08-25
Time limit: 2s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource: Own Problem

2
(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 (tutorial)

12075. Encryption
Problem code: DCEPC903
Once Saikat sir tried to open his safe, but later on he realised that he forgot his password (which is
actually a binary string), so he calls Anuja ma’am for help. Anuja ma’am then sends an encrypted
message as they both wanted to keep the password safe.

Lets say if the password is 

01100111

She encrypted this string by adding the adjacent bits of each bit to it (Characters off the left and right
edges of the string are treated as zeroes), hence the new string will be 12211232

But on decryption Saikat sir realized that the decrypted string will not be unique and will lead to more
than 1 binary strings. Being too much tired he asks you for help. 

Input
First line contains T (1<=T<=100) number of test cases.

Each test case consists of 2 lines, first line consists of N(1<=N<=1000) length of the string and second
line contains the encrypted message.

Output
So for each test case first print "Test x:" where x is the test case number starting from 1. Then print all
possible binary strings in lexicographic order.

If there is no string possible then print "Not Possible" without quotes.

Example

Input:

3
5
11111
3
122
7
2222222

1
Output:
Test 1:
01001
10010
Test 2:
011
Test 3:
Not Possible

Added by: dce coders


Date: 2012-08-25
Time limit: 2s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource: Own Problem

2
(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 (tutorial)

12077. Secret Code


Problem code: DCEPC904
Vaibhav Sir and Saikat Sir are sending encrypted messages to each other. The message is encrypted by
changing each alphabet to its previous or next alphabet (’A’ can be changed to ’Z’ or ’B’).
Since a large number of encryptions are possible for a given string, they decide that-
1) 2 consecutive characters in the encrypted string should not be the same.
2) The characters at some positions will always be replaced by the next character(called Fixed
Positions).

Input
The input starts with T (number of test cases) followed by 2 lines for each test case.
First line consisits of the input string to be encrypted  of maximum length 5000 containing characters
’A’ to ’Z’.
Second line consists of an integer N, followed by N space separated integers A(i) in increasing order.
N = number of fixed positions.
A(i) = ith fixed position.

Output
Output contains T lines, the ith line containing the number of possible encryptions for the ith test case
modulo 1000000007.

Constraints
T<=25
1<=length of string(L)<=5000
0<=N<L
0<=A(i)<L

Example
Input:
2CODER0ABCDEF2 0 5

Output:
3216

1
Added by: dce coders
Date: 2012-08-26
Time limit: 2s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource: Own Problem

2
(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 (tutorial)

12078. Picking Weights


Problem code: DCEPC905
Ankur sir and Saikat sir are fighting again. Ankur sir thinks hold on number theory gives you an edge
in ICPC whereas Saikat sir is adament that practicing DP gives you the best chance. They both go to
Vaibhav sir and ask for his opinion. He believes, teamwork is the key to success and he lines up some
(<=10^5) weights in a line. Then he asks them to pick one weight each such that the difference
between the weights picked by Saikat sir and Ankur sir is minimum, also in case more than one
optimum solutions exist, they choose both weights such that the combined weight is also the least
amongst the solutions. Since, Saikat sir is Vaibhav sir’s team-mate he gets the first chance. By this
time Sid sir comes in , to play his pranks. As soon as Saikat sir picks a weight, Sid sir absconds with
all the weights before that weight. For example, if saikat sir picks the 5th weight. Sid sir runs away
with the first 4 weights. Ankur sir, irritated by all this foolishness picks up the closest weight to Saikat
sir, but he always picks up an equal or greater weight than him. I wonder why he does that!
Also note that Saikat sir never picks up the last weight. Saikat Sir and Ankur Sir both pick one weight
each. Output the weights picked by Saikat sir then Ankur sir respectively. If no solution exists output
-1.

Input
The first line of the input contains an integer t denoting number of test cases.
Each test case has 2 lines.
First line of each test case gives n the number of weights
The next line gives n space separated integers denoting the weights.

Output
Output "x y" (quotes for clarity) for each test case on a separate line , where x denotes the weight
picked by Saikat Sir and y denotes the weight picked by Ankur Sir. If no solution is possible, output
"-1"

Constraints
1<=t<=10
1<=n<=10^5

Each weight, 0>=x[i]<=2^31

1
Example
Input:
231 1 279 4 7 6 5 3 2

Output:
1 14 5

Added by: dce coders


Date: 2012-08-26
Time limit: 2s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource: Own Problem

2
(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 (tutorial)

12081. Picture Perfect


Problem code: DCEPC906
Developers at DCE Coders love to work on challenging new problems. During one of their fun
sessions, they were watching the movie "THE DARK KNIGHT RISES" but suddenly the picture
quality started degrading and eventually the whole picture became distort. They waited for hours and
hours for the quality to become good again but all that waiting was in vain.

The very next day during their programming session, they came up with a whole new idea of writing a
program which when run with the TV connected to a laptop could get back the original picture.

The idea they used was:-

Imagine the whole T.V screen to be made of small pixels. Now these pixels are so small that the pixels
which are nearer to each other have almost the same properties. So if they can scan the whole screen
and detect which pixels have the same property and then club them together, they can get back the
original picture. Of course this task is more complicated that it appears here.

Now they want to recruit new members and want you to write a small piece of code for them which
will form the backbone of their project.

Input:-

You are given a matrix with each cell containing a character (a..z). The characters are given in a very
random manner. Your task is to club all the same characters together and also arrange them in such a
manner that they form a proper increasing order.

The first line of input will contain an integer t representing the number of test cases. Each test case
begins with a line containing two integers r and c representing the number of rows and columns
respectively

The next r lines contain c characters each.

1 <= t <= 1000

1 <= r <= 50

1 <= c <= 50 

Output:-

1
For each test case, output the correct matrix.

SAMPLE INPUT:-

43

bcd

aef

tyu

awe

SAMPLE OUTPUT:-

aab

cde

eft

uwy

Note:- all characters are LOWER CASE only. And don’t forget the increasing order of
characters in the output matrix above.

Added by: dce coders


Date: 2012-08-26
Time limit: 2s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource: Own Problem

2
(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)

12083. Appetizer
Problem code: ACMPRAC1
Given n pairs of numbers of the form a,b find which pair has the highest a^b value. If more than one
pair have the same value, print the pair which occurs first in the input.

Note: ^ indicates exponent, not XOR. Example, 2^3 = 8, 3^3=27

Input
 

Input starts with an integer T (<= 100), denoting the number of test cases.
Each case starts with a line containing an integer n (1 <= n <= 1000) which denotes the number of
pairs.
Next n lines contain two numbers a,b each.
(1 <= a,b <= 1000000)

Input starts with an integer T (<= 100), denoting the number of test cases.

Each case starts with a line containing an integer n (1 <= n <= 1000) which denotes the number of
pairs.

Next n lines contain two numbers a,b each.

(1 <= a,b <= 1000000)

Output
 

For each test case, print two numbers, separated by a space, which indicates the answer for the
corresponding test case.

1
The answer for each test case must be in a new line.

Example
Input:
4
3
1 1
2 2
3 3
5
10 5
5 5
2 3
3 3
3 10
1
7 7
2
9 9
2 2

Output:

3 3
10 5
7 7
9 9

Added by: TouristGuide


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

2
(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)

12092. Dessert
Problem code: ACMPRAC4
 

A team of M judges  have been called to judge an episode of Masterchef India. There are N
participants and the task given to them was to make an icecream.
The icecreams are judged based on the number of nuts they contain (the participants are unaware of
this criterion). You are given the fact that participant i has put P[i] nuts 
in his icecream. To make the judgement process fast, we are asked to divide these N icecreams within
these judges so as to minimize the time taken to complete the process.
Judges can take icecreams for judging only in order. ie If judge 1 takes the first M1 icecreams then
Judge 2 can take only icecreams following M1, & so on.
ie. this icecream sharing is a linear partition. (order matters) Each judge takes a unit time to count a
nut. The time taken for completion is the time from the beginning of counting
process to the time that the last judge finishes his job. Obviously that last judge will be the guy who
was assigned maximum work (interms of total number of nuts given to him)
Thus, given the number of nuts contained in each icecream, and the number of judges available,
compute the minimum time, in which the judgement process can be completed.

A team of M judges  have been called to judge an episode of Masterchef India. There are N
participants and the task given to them was to make an icecream. The icecreams are judged based on
the number of nuts they contain (the participants are unaware of this criterion). You are given the fact
that participant i has put P[i] nuts in his icecream. To make the judgement process fast, we are asked
to divide these N icecreams within these judges so as to minimize the time taken to complete the
process. Judges can take icecreams for judging only in order. ie If judge 1 takes the first M1
icecreams then Judge 2 can take only icecreams following M1, & so on. ie. this icecream sharing is a
linear partition. (order matters) Each judge takes a unit time to count a nut. The time taken for
completion is the time from the beginning of counting process to the time that the last judge finishes
his job. Obviously that last judge will be the guy who was assigned maximum work (interms of total
number of nuts given to him)

Thus, given the number of nuts contained in each icecream, and the number of judges available,
compute the minimum time, in which the judgement process can be completed.

1
Input
 

1st line contains T, denoting the number of testcases. Each testcase is described in two lines as follows

1st line contains N & M.

2nd line contains N integers denoting P[i] 1 <= i <=N

T<=10

N <= 250

M <= N

P[i] <= 1000 for all I in [1,N]

Output
 

For each test case, output one integer containing the min of (max. amount of time taken to complete
the process.)

Example
Input:
1
5 4
1 2 3 4 5

Output:
5

Here the linear partition is : 1 2 / 3 / 4 / 5 (max work=5)

Added by: TouristGuide


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

2
(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)

12100. Main Course


Problem code: ACMPRAC3
 

X and Y are having their main course meal over a candle light dinner at a posh restaurant. Instead of
gazing into her eyes and enjoying the meal, X decides to play a game. 
X gives two numbers A and B to Y and asks her to find the number of integers n that satisfy the
following two conditions:
1. A <= n <= B
2. n is not divisible by any perfect square other than 1.
Your task is to help Y and find the answer for each of X’s queries so that Y can enjoy her meal in
peace.

X and Y are having their main course meal over a candle light dinner at a posh restaurant. Instead of
gazing into her eyes and enjoying the meal, X decides to play a game. 

X gives two numbers A and B to Y and asks her to find the number of integers n that satisfy the
following two conditions:

1. A <= n <= B

2. n is not divisible by any perfect square other than 1.

Your task is to help Y and find the answer for each of X’s queries so that Y can enjoy her meal in
peace.

1
Input
 

Input starts with an integer T (<= 100), denoting the number of test cases.

Each case starts with a line containing two integers A and B.

(1 <= A <= B <= 10 ^ 9)

Output
 

 For each test case, print one number, which indicates the answer for the corresponding test case.

The answer for each test case must be in a new line.

Example
Input:
3
10 20
30 100
1000000 10000000

Output:
7
43
5471365

For example, the squarefree numbers between 10 and 30 are 10,11,13,14,15,17,19,21,22,23,26,29,30.

Added by: TouristGuide


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

2
(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)

12101. Entrée
Problem code: ACMPRAC2
Master Bates is a ravenous eater; due to his monstrous eating habits he is having some difficulties in
performing. Dr. XXX has asked him to cut down on his intake. The doctor has prescribed the number
of meals he can have in a day. Now Bates has got ‘k’ different varieties of foods (1<=k<=26) and he
can have at most ‘m’ meals in a day (1<=m<=100) as prescribed by the doctor. Each variety of food is
specified by a letter of the alphabet in lower case. A meal is defined as a string of contiguous
characters of same type i.e all the characters in the substring should be the same. Master Bates wants
to eat as much as possible in his ‘m’ meals. Assuming each alphabet is 1 unit of food. What is the
maximum amount he can consume?

Input
 

First line of input is the number of test cases (not more than 100). Each test case consists of 2 lines,
first line of each case consists of an integer m (1<=m<=100)
Second line of each case consists of a string describing the food that he has for the day. There will be
at most 100000 (10^5) characters in the string

First line of input is the number of test cases (not more than 100). Each test case consists of 2 lines,
first line of each case consists of an integer m (1<=m<=100)

Second line of each case consists of a string describing the food that he has for the day. There will be
at most 100000 (10^5) characters in the string

Output
Output one integer indicating the maximum amount of food he can consume.

1
Example
Input:
4
2
aaaabbaaaa
3
aabbbcccaaddddaaeeeee
5
abcde
1
aaaaabcde

Output:
8
12
5
5

Added by: TouristGuide


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

2
(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 (tutorial)

12111. FirstProblem
Problem code: RIOI_T_0
You are given two arrays A and B both containing N integers. You have to rearrange numbers in A
and B such that A[0]*B[0] + A[1]*B[1] + ... + A[n-1]*B[n-1] is minimised. Output that number.

NOTE : that you have do this routine T times.

SCORING : Your score is 100 * correctly solved files / number of files. File is correctly solved if you
have solved all T tests correctly.

CONSTRAINTS:

n <= 100000

a[i] <= 10^9

NOTE : result will fit in 64 bit integer. IO is huge, use faster io methods.

Input
First number of input is T number of virtual test cases. Each test starts with number N and 2*N
integers donating A and B.

Output
Ouput minimised value

Example
INPUT : 231 1 31 1 321 21 2OUTPUT74Explanation : in first example we can rearrange number (1, 1, 3) and (1, 3, 1) which leads to sum of 7. (1, 2), (2, 1) in second exmple

Added by: Buda IM


Date: 2012-08-28
Time limit: 1s
Source limit:50000B
Languages: All
Resource: own problem

1
(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 (tutorial)

12112. SecondProblem
Problem code: RIOI_T_1
Okram Cipuc is very smart dude that works at REF ( some ugly place where he should not in fact be ).
But because he is the best in what he does, every day he gets job offers from all over the world. He
gets n offers but he likes only k. And he asked his student Arudnam on his famous Avaj course,
"which of them did I like ?", Arudnam does not know the answer now he has to guess. How many
times he will try in the worst case scenario ?

SCORING : Your score is 100 * correctly solved files / number of files. File is correctly solved if you
have solved all T tests correctly.

CONSTRAINTS

0 < N <= 20, 0 < K <= 20

Input
There will be T tests, each test consists of 1 line containing N and K.
First line of the input is T, T lines follow containing N and K in that order.

Output
Number asked in problem statement

Example
Input:15 2

Output:
10

Added by: Buda IM


Date: 2012-08-28
Time limit: 0.400s
Source limit:50000B
Languages: All
Resource: own problem

1
(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)

12113. Exotic Drinks


Problem code: ACMPRAC5
In the year 3000AD, India finally got its first chance to host the Summer Olympics. The opening
ceremony was held at the famous CEESAT ground of NIT-Trichy (which was once an educational
institution, now flourishing as one of the world’s largest flea markets). The ceremony started off with
the release of hundreds of thousands of fireworks in the air. This was touted to be a magnificent
display of color, and joy, and everything cheerful about the world. Except for one thing - all the
fireworks were either blue or red in color. This bored the audience, who became restless. A portion of
the audience consisted entirely of computer science engineers from an institute of international
importance. They started noting patterns in the fireworks that were being displayed and started playing
games among themselves, as they were drunk from all the exotic drinks that were available. One such
game is being described below:

Given a snapshot of a set of fireworks in the air, the task was to determine whether these
fireworks look like the Olympic symbol or not.
Every firework is numbered. The streak of color that can be seen between any twoadjacent
fireworks comes from any one of them (and it doesn’t matter which one belongs to what).
A snapshot is said to look like the Olympic symbol if it satisfies all of the following conditions:

1)   The streaks of colors along with the fireworks MUST form rings. The color of a ring is said to
be blue iff all the colors between fireworks in that ring are blue in color. Similarly for red colored
rings. ALL the fireworks and their colors must be part of rings.

2)   Adjacent rings must have ONLY ONE  firework in common with each other.

3)   Each ring must be monochromatic (either completely blue or completely red).

4)   Two adjacent rings must not be of the same color.

5)   All the rings must have equal number of fireworks in them. A firework that is between two
rings belongs to both rings.

6)   There may be any number of rings.

If the given snapshot satisfies all these conditions, then it is said to be similar to the Olympic symbol. 

Input

Input consists of 2 numbers N and M.

1
N = Number of firework heads, M = Number of color streaks seen.

In each of the next M lines, three numbers: x y c are given. This indicates that the firework ‘y’ is
adjacent to firework ‘x’. The color is seen as a streak from x to y and not y to x (ie, a->b<-c->a is not a
ring). If c = 0, then the color between them is blue. If c = 1, then the color streak between them is red.

Output
Print "YES" in a single line if the snapshot looks like the Olympic symbol. Print "NO" otherwise.

Constraints:

N<=10^5 +1

M<5*10^5

Example

Input:3 31 2 02 3 03 1 0

Output:YES

Input:7 91 2 02 3 03 1 02 4 14 5 15 2 15 6 06 7 07 5 0

Output:YES Input:3 31 2 02 3 1

3 1 0

Output:NO

Figures:http://imgur.com/4CLqr

In this case, it is similar to Olympic symbol. All the conditions are satisfied (sample 2).http://imgur.com/XcdjCThis is not an Olympic symbol as two blue rings are next to each other.http://imgur.com/3Di13This is not an Olympic symbol as rings intersect at more than one point.

2
Some hints:A single ring of any color is an Olympic symbol (sample 1).
Every ring should have at least 2 fireworks.
Look out for the constraints. Ensure that the space complexity of your algorithm is feasible.

Note that the ALL the fireworks and their colors must be part of the Olympic symbol.

Added by: TouristGuide


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

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 (tutorial)

12165. Encrypted String


Problem code: ENCRPASS
Miss Varsha is very concious about her belongings. She doesn’t want to share her things with anyone
and so she wants to secure all her codes with a special type of encription.
She is good at coding but she needs your help, to encript her computer.
She is replacing every character of the password with a new character, according to which you have to
determine the entire string.

Input
First line of input will contain number of test cases(n).Then 2n lines will follow ie. two line for each
test case. First line will contain the string second line will contain the original character and the
replacing character seperated by the space, respectively.You have to encript the entire string based on
the method of replacement.

Output
Output will contain only one encripted String for each test case, in the format "Case #i: "(i denotes the
i’th test case)

Example
Input:
1FRENZLIFER U

Output:
Case 1#: IUHQCOLIH

Added by: ~/-LaSt--BrEaTh-/~


Date: 2012-09-02
Time limit: 1s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA

1
(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 (tutorial)

12166. Reverse And Add


Problem code: REVNUMBE
Bacchi is always into books. She was bored with her monotonous life. One day she thought how
would it look if everything was upside down and as she was a book worm,she thought how numbers
will look if they were reversed.
For this task she wants your help.
You will be given two numbers a and b(0<=a,b<=10^15), you have to perform the following
operations on them:
1: reverse both the numbers and add them.
2: reverse the result that you get after operation 1
3: print the result.

Input
First line contains the number of test cases ’T’(T<=100), then ’T’ lines follow. Each line consists of
two numbers seprated by a space.

Output
Output will be in the format"Case i#: result" where i is the ith test case and result is the final output.

Example
Input:
21234 56781002 123
Output:
Case 1#: 68031Case 2#: 2232

Added by: ~/-LaSt--BrEaTh-/~


Date: 2012-09-02
Time limit: 1s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA

1
(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 (tutorial)

12167. Fibonacci starters


Problem code: FIBTUTO
Fibo was a Famous Farmer. Who lived in the city of Fibonacia. One day while Farming For Fibonuts
he saw a golden Fiboegg. He thought that now he will become a rich man with this golden Fiboegg.
That night while he was sleeping a Fairy came in his dream and asked him did the Fiboegg came first
or the golden Fibohen.So now come to the point:
Fibonacci series is a series in which every term is the sum of the previous two terms.
eg. 0 1 1 2 3 5 8 13 ....
Your task is to print the SUM of First N Fibonacci terms.

Input
First line of input will contain number of testcases T(<=1000), followed by T lines.
Every line will contain a positive integer N(<=90).

Output
For every input print the sum of first N fibonacci numbers.

Example
Input:
258

Output:
733

Added by: ~/-LaSt--BrEaTh-/~


Date: 2012-09-02
Time limit: 1s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA

1
(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 (tutorial)

12168. APGP Tutorial


Problem code: APGPTUT
Arithematic Progression is the series in which every next term is at common difference from the
previous term, eg:1 2 3 4, where the common difference is 1.
Geometric Progression is one in which every next term of the series is obtained by multiplying the
previous term with a constant, eg 1 2 4 8, where the common ratio is 2.
Your task is to find the series and print its next term..

Input
The input will contain three numbers(0<=a,b,c<=10^15) denoting the three consecutive terms of the
series.
Input is terminated when all the three numbers are 0.

Output
Output for each testcase will contain the name of the series ie. AP or GP and the value of the next term
of the series.

Example
Input:
10 15 205 10 200 0 0

Output:
AP 25GP 40

Added by: ~/-LaSt--BrEaTh-/~


Date: 2012-09-02
Time limit: 1s-2s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA

1
(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 (tutorial)

12169. General Number Series


Problem code: LISTTUT
Abhishek is very fond of series and he loves solving them. He thinks that no one can match his skills
at series and so he throws a challenge at you.
The challenge is to determine the sum of the first N terms of the series.
The series is as:
0 1 2 6 20 56 144 352....
Be carefull while finding the Nth term, it is not always determined by the starting terms ;)

Input
The first Line of input contains number of Test Cases T(<=100), then T lines follow.
For each test case there will be a number N(<=30).

Output
Output the sum of series till N terms

Example
Input:
225

Output:
129

Added by: ~/-LaSt--BrEaTh-/~


Date: 2012-09-02
Time limit: 1s
Source limit:50000B
Languages: C C++ 4.3.2 C++ 4.0.0-8 JAVA

1
(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 (tutorial)

12184. Help the statistics department


Problem code: KFSTD

Help the statistics department


In the statistics department of the Kingdom of Byteland the programmers have to maintain all the
dynamic information efficiently. The Census data for the current decade was recently collected in
Byteland, and now the data is to be used to compute some interesting statistics. The programmers at
the statistics department are not very smart, hence they are seeking the help of a bright student i,e you
:). The problem is as follows:

We need to maintain a dynamic list of integers which is initially empty under the following 4
operations:

Add(x) :- Add x to the dynamic list


Delete(x) :- Delete one occurence of x from the dynamic list
ReportKth(k) :- Print the 1-based Kth smallest element in the list
ReportRank(x):- Report the 1-based rank of x (1 + No. of elements less than x)

Input
First line of the input contains T, number of test cases.
First line of each test case contains Q, number of operations.
Each of the next Q lines is of the following form:
KX

If K = 1 then perform Add(x)


If K = 2 then perform Delete(x)
If K = 3 then perform ReportKth(x)
If K = 4 then perform ReportRank(x)

Output
For each operation of the type 3 OR 4 print one line containing the required result. It is guaranteed that
the number x given at the time of delete operation is always present in the set. It is also guaranteed that
x in the operation ReportRank is no more than number of elements in the list at that moment.

1
Sample Input
1
7
12
13
14
31
44
22
43

Sample Output
2
3
1

Constraints
1 <= T <= 10
1 <= Q <= 10^5
1 <= X <= 10^5
1 <= K <= 4

Added by: rizwan hudda


Date: 2012-09-04
Time limit: 3s
Source limit:50000B
Languages: All
Resource: Kodefest 2012 IITK - Own problem

2
(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)

12186. Tropical Garden


Problem code: IOI11GAR
Problem text...

Input
Input description...

Output
Output description...

Example
Input:
etc.

Output:
etc.

Added by: Ahmed Kamel [ahm.kam_92]


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

1
(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)

12208. The Chain Reaction


Problem code: AGRADE
Aayush enters the Algorithms’ class late. His teacher is angry with him, so in order to punish him he
asks him to solve a problem. In case Aayush is not able to solve the problem his current A grade will
be converted into B. The problem statement is - "Given the below recursive function he needs to figure
out how many times the given function will call itself".Help him save his grade.

f(n)

{ if n <= 2

  return 1

  else

  return f(n-1)*f(n-2)*f(n-3)

Input
First line contains the number of test cases T. T test lines follow each containing a integer N.

Output
One result for each test case equal to the number of recursive function calls. Each output in new line.
As the result could be very large print it modulo 10^9 + 7.

Example
Input:
3
234Output:
036 Range:1<=T<=10001<=N<=10^15 

Added by: Apurv Singhal


Date: 2012-09-11
Time limit: 1s
Source limit:50000B
Languages: All
Resource: QUIZ’01 2012,BITS Pilani

1
(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 (tutorial)

12246. Day sô 1
Problem code: KSEQ1
Cho môt day sô A1 .... An Yeu câu: tim sô K lo+’n nhât sao cho tôn ta.i day chi? sô i1 < i2 < ... < i2k
tho?a man A i1 < A i( k + 1 ) ; A i2 < A i( k + 2 ) ...... A ik < A i2k  

Du+~ lie^.u

Dong đâu ghi sô nguyen du+o+ng N.

Dong sau ghi N sô A i ( 1 <= i <= N ).

Ke^’t qua?

Ghi tren môt dong sô K lo+’n nhât tim đu+o+.c.

Gio+’i ha.n

N <= 300 ; 1 <= A i <= 10000.

Example

Du+~ lie^.u:

1234567

Ke^’t qu?a

Added by: Minh^^


Date: 2012-09-19
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Thây Đông

1
(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 (tutorial)

12271. Speed test - Pyramid version


Problem code: SPEEDPYR
This problem was created to compare speed of the Pyramid and Cube Clusters. After you get AC result
for this problem you can submit solution to problem called Speed test - Cube version - both problems
have identical statement and test cases.

Input
There is a single positive integer t (2 <= t <= 10000) on the first line of input which corresponds to the
number of tests. Then t lines follow, each containing five numbers: a, b, c, d, h (2 <= a, b, c, d, h <=
10000). For each line you should do the following thing:

 Step 0
a) Assign a to r1.
 Step 1
b) Take r1, add b to it and you get r2.
c) Take r2, multiply it by c and you get r3.
d) Now compute r1 = r3 modulo d.
 Steps 2, 3, ... , h
e) Do b), c) and d) (h-1) times.

Output
t lines containing one number: r1

Example
Input:
3
2 3 4 5 2
5 8 9 4 9
23 15 923 489 23

Output:
6
5
284

1
Added by: Filip Wielewski
Date: 2012-09-22
Time limit: 15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All

2
(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 (tutorial)

12272. Speed test - Cube version


Problem code: SPEEDCUB
This problem was created to compare speed of the Pyramid and Cube Clusters. After you get AC result
for this problem you can submit solution to problem called Speed test - Pyramid version - both
problems have identical statement and test cases.

Input
There is a single positive integer t (2 <= t <= 10000) on the first line of input which corresponds to the
number of tests. Then t lines follow, each containing five numbers: a, b, c, d, h (2 <= a, b, c, d, h <=
10000). For each line you should do the following thing:

 Step 0
a) Assign a to r1.
 Step 1
b) Take r1, add b to it and you get r2.
c) Take r2, multiply it by c and you get r3.
d) Now compute r1 = r3 modulo d.
 Steps 2, 3, ... , h
e) Do b), c) and d) (h-1) times.

Output
t lines containing one number: r1

Example
Input:
3
2 3 4 5 2
5 8 9 4 9
23 15 923 489 23

Output:
6
5
284

1
Added by: Filip Wielewski
Date: 2012-09-22
Time limit: 5s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All

2
(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)

12275. Meeting and Dating


Problem code: NITT3
Once in a random college it was a well known fact that the number of cows were more than the
number of students in that college. If we consider the entire college as a x-y plane then there is a cow
at every integer point. Once a frustrated guy wanted to have fun of looking at the girls. He found a
beautiful girl at some integer point P2(x2,y2). He prayed to the god to take him to some integer point
so that his view is more clear. The god responded and moved him to a random point P1(x1,y1). But
poor guy, there were cows which disturbed his fun. Find the number of distinct cows between the boy
and the girl including the cow (on the line joining between them) which is on the place they are
standing. 

Input
 

first line T denoting the number of test cases


next T lines containing four integers x1 y1 x2 y2

First line contains T(<=50) denoting the number of test cases 

Next T lines has four integers x1 y1 x2 y2 which describes the coordinates of the two point P1(x1,y1)
and P2(x2,y2)

Absolute value of all the coordinates will be less or equal to 10000

Output
For each test case output the required number of cows on each line

Example
Input:
2

1 1 5 5

1
2 3 3 4

Output:
5

Added by: jack(chakradarraju)


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

2
(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)

12276. Subset and upset


Problem code: NITT5
 

The whole world is crazy about subset sum. We define subset sum as sum of all subparts. A subpart is
a number which is obtained by erasing certain digits and arranging the remaining numbers in the same
order. You have to calculate the subset sum of the given number. Since the number can be very large
return the subset sum modulo 9.
For example if the number is 1357, then the various subparts are 1, 3, 5, 7, 13, 15, 17, 35, 37, 57. 

The whole world is crazy about subset sum. We define subset sum as sum of all subparts. A subpart is
a number which is obtained by erasing certain digits and arranging the remaining numbers in the same
order. You have to calculate the subset sum of the given number. Since the number can be very large
return the subset sum modulo 9.

For example if the number is 1357, then the various subparts are 1, 3, 5, 7, 13, 15, 17, 35, 37, 57, 137,
135, 157, 357, 1357 . 

Input
 

First line contains T denoting the number of test cases (T<=50)

Next T lines containing the number (maximum number digits of the number can be 51).

Output
Print the subset sum modulo 9

1
Example
Input:
2

456

111

Output:
6

Added by: jack(chakradarraju)


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

2
(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)

12281. Word or number (Easiest)


Problem code: WORDNUMS
We use alphabetic characters from the Romans for words, and numerals from the Arabs for numbers.
Can you write a program to tell the difference?

Input
Input will be a sequence of either alphabetic characters, or a sequence of numeric characters (no
decimals).

Output
Output "word" (no quotes) if the characters are alphabetic. Output "number" (no quotes) if the
characters are numeric. All character will be one or the other.

Example
Input:
ACM

Output:
word

Input:
012

Output:
number

Added by: Paul Draper


Date: 2012-09-26
Time limit: 2s
Source limit:50000B
Languages: C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict JAVA JS RUBY

1
(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)

12282. Word or number (easiest 2)


Problem code: WORDNUM2
We use alphabetic characters from the Romans for words, and numerals from the Arabs for numbers.
Can you write a program to tell the difference?

Input
Input will be a sequence of either alphabetic characters, or a sequence of numeric characters (no
decimals).

Output
Output "word" (no quotes) if the characters are alphabetic. Output "number" (no quotes) if the
characters are numeric. All character will be one or the other.

Example
Input:
ACM

Output:
word

Input:
012

Output:
number

Added by: Paul Draper


Date: 2012-09-26
Time limit: 2s
Source limit:50000B
Languages: All

1
(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)

12283. Phu? sóng


Problem code: WAVE
Du+. kie^’n xây du+.ng ma.ng lu+o+’i phát thanh, truye^‘n hinh o+? môt đi.a phu+o+ng no. có môt
đai phát va tra.m tie^’p sóng đánh sô tu+‘ 1 to+’i n. Tra.m thu+’ i đa đu+o+.c xây du+.ng o+? toa. đô (
x i , y i ). Đe^? đa?m ba?o tính trung thu+.c cu?a các nguôn tin, các tra.m tie^’p sóng chi? có the^?
nhân tín hie^.u tru+.c tie^’p tu+‘ đai phát. Va nhu+ vây có nghia la đe^? phát sóng đe^’n tât ca? các
tra.m thu, bán kính phu? sóng cu?a đai phát pha?i đu? lo+’n đe^? phu? he^’t các tra.m tie^’p sóng.
(Gia? su+? vung phu? sóng la hinh tron có tâm la đai phát).

Yeu câu: Hay tim vi. trí đăt đai phát sao cho khoa?ng cách tu+‘ tra.m thu xa nhât to+’i đai phát la ngăn
nhât. Cho bie^’t bán kính phu? sóng trong phu+o+ng án tim đu+o+.c tôi thie^?u pha?i la bao nhieu.

Du+~ lie^.u:
-  Dong đâu: Chu+’a sô nguyen du+o+ng n( 0 < n <= 200 );
-  Dong tie^’p theo, dong thu+’ i chu+’a hai sô nguyen du+o+ng ( x i , y i ) có giá tri. tuye^.t đôi không
quá 10000 cách nhau ít nhât môt dâu cách.

Ke^’t qua?:
Ghi ra bán kính nho? nhât tim đu+o+.c, lam tron to+’i 6 chu+~ sô sau dâu châm thâp phân

Ví du.

Input  
8  
00
200 300
200 0
200 200
0 200
100 300
300 100
100 0

Output
182.107840

1
Added by: Christian Eriksen
Date: 2012-09-26
Time limit: 1s-2s
Source limit:50000B
Languages: All except: AWK CLOJ ERL F# GO PERL 6 PYTH 3.2.3 SCALA SED TCL
Resource: Thây Le Minh Hoang

2
(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)

12289. Grid Travel


Problem code: NITT7
A square of side length a is in the first quadrant sharing the x and y axis. Given two points P1(x1,y1)
and P2(x2,y2) on the boundary of the square, find the minimum distance between those two points by
travelling only on the boundary of the square

Input
 

First line containing T denoting the number of test case


Then T lines is of the format <a x1 y1 x2 y2> 

First line containing T(<=50) denoting the number of test case

Then T lines is of the format <a x1 y1 x2 y2> 

3<= a <= 10000

Both P1 and P2 will lie on the boundary of the square

Output
For each test case print the minimum distance to reach P2 from P1 by travelling on the boundary of the
square

Example
Input:
2

4469

2770 0 4469 1117 

2562

2083 0 0 652

Output:

1
2816

2735

Added by: jack(chakradarraju)


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

2
(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 (tutorial)

12298. Tirate un paso


Problem code: PASO
El inicio del sistema se ha danado, ya no muestra un mensaje de bienvenida a los usuarios. Elabore un
programa que, dado el nombre de un usuario, muestre un mensaje de bienvenida.

Entrada
La entrada consiste de una cadena de caracteres compuesta únicamente por letras y sin espacios. El
tamano de la cadena no será mayor a 50 caracteres.

Output
Debe imprimir el mensaje: "Oye <NOMBRE DEL USUARIO>, tirate un paso." sin comillas.

Ejemplo
Entrada
Jhonatan

Salida
Oye Jhonatan, tirate un paso.

Added by: Simón Santiago Soriano Pérez


Date: 2012-09-29
Time limit: 1s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: C++ 4.0.0-8

1
(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)

12348. Sum of Subsets


Problem code: POWERSUM
The sum of a set is defined as the sum of all elements in the set. You are given a set of integers, each
between 0 and 10**9. Find the total sum of the sums of each subset of the set.

Input
There are several testcases. The first line will contain T, the number of testcases. 

Each of the next T testcases begin with a single integer , n, on the first line, the number of elements in
the set.

The second line of each test case will contain n space separated integers, the elements of the given set.

Output

For each testcase, you are required to print the total sum of the sums of each subset of the set. As the
answer can be quite large, print it %(10**9+7).

Constraints
1<=T<=100.

1<=n<=10**4

Example
Input:
2

1 4 8

3 6

Output:
52

1
18

Added by: Apoorv Gupta


Date: 2012-10-02
Time limit: 0.400s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: Self

2
(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)

12372. In Debt
Problem code: TAP2012I
[The original version of this problem (in Spanish) can be found
at http://www.dc.uba.ar/events/icpc/download/problems/taip2012-problems.pdf]

Ignacio and Ines really like science. Luckily they live in Nlogonia, where as everyone 
knows there are N science museums. Both Ignacio and Ines have the next N Saturdays free, 
so they have agreed on a schedule to visit a different science museum each of these 
days.
Ignacio is quite stingy, so that every Saturday he will tell Ines that he has forgotten 
to bring the money to pay the museum’s entrance fee, and ask her to pay for him. Ines 
always does so, and because she knows him well she also knows that if she does ask for 
her money back, he will never pay up. In fact, Ines is certain that even if she asks 
Ignacio for her money back, he will only accept to pay if the cumulative debt is a 
multiple of 100, because otherwise he will argue that he has no change to pay exactly, 
and thus pays nothing at all.
This being the situation, every Sunday if the cumulative debt is a multiple of 100 Ines 
will go to Ignacio’s house to claim her money, and because he’ll have no excuse left, he 
will pay without any type of protest. Of course he doesn’t like this, but he is comforted 
by the idea that if the cumulative debt after visiting the N museums is not a multiple of 
100, Ines shall not claim the last part of her money.
Ines would like to know how many times she will go to Ignacio’s house to ask for her 
money. In order to calculate this, she can provide a list of the prices of the entrance 
fees to the N science museums in Nlogonia, in the order that she and Ignacio are going to 
visit them.

Ignacio and Ines really like science. Luckily they live in Nlogonia, where as everyone knows there are
N science museums. Both Ignacio and Ines have the next N Saturdays free, so they have agreed on a
schedule to visit a different science museum each of these days.

Ignacio is quite stingy, so every Saturday he will tell Ines that he has forgotten to bring the money to
pay the museum’s entrance fee, and will therefore ask her to pay for him. Ines always does so, and
because she knows him well she also knows that unless she asks for her money back, he will never
pay up. In fact, Ines is certain that even if she asks Ignacio for her money back, he will only accept to
pay if the cumulative debt is a multiple of 100, because otherwise he will argue that he has no change
to pay exactly, and will thus pay nothing at all.

This being the situation, every Sunday if the cumulative debt is a multiple of 100 Ines will go to
Ignacio’s house to claim her money, and because he’ll have no excuse left, he will pay without any
type of protest. Of course he doesn’t like this, but he is comforted by the idea that if the cumulative
debt after visiting the N museums is not a multiple of 100, Ines shall not claim the last part of her

1
money.

Ines would like to know how many times she will have to go to Ignacio’s house to ask for her money.
In order to calculate this, she can provide a list of the prices of the entrance fees to the N science
museums in Nlogonia, in the order that she and Ignacio are going to visit them.

Input
Each test case is described using two lines. The first line contains a single integer number N,
indicating the number of science museums in Nlogonia (1 <= N <= 100). The second line contains
N integers P i representing the prices of the entrance fees to the different museums, in the order in
which they are going to be visited (1 <= P i  <= 100 for i = 1, ..., N). The end of the input is
signalled by a line containing the number -1.

Output
For each test case, you should print a single line containing an integer number, representing the
number of times Ines is going to have to go by Ignacio’s house to ask for her money.

Example
Input:
3
50 50 50
5
50 100 100 100 100
9
25 50 75 100 25 50 75 100 25
5
35 45 20 22 33
3
100 100 100
-1

Output:
1
0
2
1
3

2
Added by: Fidel Schaposnik
Date: 2012-10-04
Time limit: 1s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: Argentinian Programming Tournament 2012

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 (classical)

12395. Maximizing the equation


Problem code: MAXEQUA
Given 3 sequences of positive numbers A,B and C. Your mission is to maximize this equation:

Z = A[i] / (B[j] * C[k]).

In other words, you have to choose any numbers from the given sequences in order to maximize Z.

Input:

First line contains a positive integer T which is the number of test cases. Each test case has the
following format:

A[0] A[1] A[2] .... A[N-1]

B[0] B[1] B[2] ..... B[M-1]

C[0] C[1] C[2] ...... C[P-1]

Constraints:

1<= T <=100

1<= N,M,P <=10000

1<= A[i],B[i],C[i] <= 1000

Output:

Print T lines, one for each test case that contains the maximum Z rounded to 2 decimal places.

Sample Input:

1
3

123

5678

10 2 6

12

Sample Output:

0.30

1.25

Added by: Pfifing


Date: 2012-10-05
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: AUC Local contest

2
(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)

12396. Johnny divides by 2


Problem code: LCPC12A

Description
Johnny is studying division and he started by division by 2. To practice division, his colleague gave him a set of problems as follows: Given a string S of length L all containing digits from 0 to 9 (with no leading zeros), how many substring of S can be divided by 2 with no remainder, and how many cannot be divided by 2 with no remainder. For example string "123" has six substrings "1", "2", "3", "12", "23", and "123". Four of which cannot be...

Input Format
Input will start with T number of test cases. Followed by T lines each line contains string S with length 0<L<10 of digits 0-9.

Output Format
For each test case, output the result using the following format:

k. D N

Where k is the test case number (starting at 1), a single period, a single space, then D (how many substrings of S can be divided by 2 with no remainder), N (how many cannot be divided by 2 with no remainder).

Sample InputSample Output


1 1. 2 4

123  

Added by: Pfifing


Date: 2012-10-05
Time limit: 1s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: LCPC 2012

1
(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)

12410. No more Johnny


Problem code: LCPC12I

Description
Sure you are bored from Johnny and his stories, so we decided that we will not mention Johnny in this problem. As you are one of the cleverest students in programming course, it is required to develop...n > 1 can be represented in exactly one way as a product of prime (A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself) powers:

Where p 1 2 k  < p  < ... < p  are primes and the a i  are positive integers; 1 is represented by the empty product. In this problem you will work with prime factors of numbers that is & means you will take minimum power for each prime between the 2 numb... 1 * 3 1 3 | 3 so result will be 2 1 * 3 3 that will be 18. Also 6 & 9 will be 2 1 * 3 1 3
& 3 so result will be 2 1 * 3 1 that will be 6. Given a set of numbers and operations between them, print the final result as primes with powers (show prime factors of the result).

Input Format  
The first line of input contains an integer T, the number of test cases. T test cases follows, the first line of each test case contains N where 1 <= N <= 100 represent number of integers to do calculations. Followed by N numbers between each 2 number one of the operations & or | (The precedence of & and | are equal and both are left associative). All numbers x will be 0 <= x < 100.

Output Format
There should be T lines, containing the following format.

k. p1^a1 p2^a2 ..pi^ai...pn^an

Where k is the test case number (starting at 1), a single period, a single space and sequence of primes with their powers represent a final result where p1 <p2 < pi < pn (don’t print primes with power zero).

Sample InputSample Output


2 1. 2^2 3^1 5^1

3 2. 2^1 3^1 5^1

12 | 6 & 15

12 & 6 | 15

Sample Clarification:

12 | 6 & 15 means 2 211111 2111 211


*3 |2 *3 &3 *5 that will be 2 *3 &3 *5 that will be 2 *3 *5

1
Added by: AUC LOCAL
Date: 2012-10-06
Time limit: 1s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All except: NODEJS
Resource: LCPC 2012

2
(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)

12411. Johnny And Modulo


Problem code: LCPCP1

Description
Johnny was very happy after knowing the modulo operation because he was always worried from
overflow specially that 32 bit integers can store numbers in the range -2147483648 to 2147483647
only. In computing, the modulo operation finds the remainder of division of one number by another.

Given two positive numbers, a (the dividend) and n (the divisor), a modulo n (abbreviated as a mod n)
is the remainder of the Euclidean division of a by n. For instance, the expression "5 mod 2" would
evaluate to 1 because 5 divided by 2 leaves a quotient of 2 and a remainder of 1, while "9 mod 3"
would evaluate to 0 because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0;
there is nothing to subtract from 9 after multiplying 3 times 3. (Notice that doing the division with a
calculator won’t show you the result referred to here by this operation, the quotient will be expressed
as a decimal fraction.) When either a or n is negative, this naive definition breaks down and
programming languages differ in how these values are defined. Although typically performed with a
and n both being integers, many computing systems allow other types of numeric operands. The range
of numbers for an integer modulo of n is 0 to n - 1. (n mod 1 is always 0; n mod 0 is undefined,
possibly resulting in a "Division by zero" error in computer programming languages) See modular
arithmetic for an older and related convention applied in number theory.

Input Format
Input will start with T number of test cases. Followed by T lines each line contains integers
0<M<=10 9 and 0<N<=100 followed by N integers 0<=X[i]<M and 0<=i<N.

Output Format
For each test case, output the result using the following format:

k. S

Where k is the test case number (starting at 1), a single period, a single space, then S the sum
(X[0]+X[1]+...+X[N-1]) mod M

1
Sample InputSample Output
1 1. 0

7243  

Added by: AUC LOCAL


Date: 2012-10-06
Time limit: 1s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All except: NODEJS
Resource: LCPC 2012

2
(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)

12412. Johnny Learns Modular exponentiation


Problem code: LCPCP2

Description
After Johnny solved problem A in LCPC2012 practice contest he decided to read more about modulo operation so he read the following article.

Modular exponentiation is a type of exponentiation performed over a modulus. It is particularly useful in computer science, especially in the field of cryptography.

A "modular exponentiation" calculates the remainder when a positive integer b (the base) raised to the e-th power (the exponent), and the total quantity is divided by a positive integer m, called the ...b, exponent e, and modulus m, the modular exponentiation c is: c = (b^e) mod M

For example, given b = 5, e = 3, and m = 13, the solution c is the remainder of dividing 5^3 by 13, which is the remainder of 125 / 13, or 8.

If b, e, and m are non-negative, and b <m


  , then a unique solution c exists with the property 0 <= c <m
  .

Input Format
Input will start with T number of test cases. Followed by T test cases each test has three integers 0<b<10 9 and 0<e<10 18 and 0<m<10 9

Output Format
For each test case, output the result using the following format:

Where k is the test case number (starting at 1), a single period, a single space, then  .

Sample InputSample Output


1 1. 1 

328

1
Added by: AUC LOCAL
Date: 2012-10-06
Time limit: 1s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All except: NODEJS
Resource: LCPC 2012

2
(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 (tutorial)

12447. LOVER BOY


Problem code: JUNMC
Sunny L Deol loves prime numbers. He gets excited if the sum of all elements in an array is a prime
number. Tell he is excited or not by calculating the sum of number in the array.

If he is excited then print ’I LOVE MILD’

else print ’GIVE ME MOMENTS’. Quotes rae just for clarity.Cool

Input
First line contains t = number of test case.

Each Test case consists of two lines.

First line of each test case contains n. 1<=n<100

second line contains n numbers. 

Output
As described.

Example
Input:
2

10

1 2 3 4 5 6 7 8 9 10

1 4 6

Output:
GIVE ME MOMENTS

I LOVE MILD

1
Added by: .
Date: 2012-10-12
Time limit: 1s-20s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: ARADHYA,AVIRAL,YASH,MUDDA

2
(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 (tutorial)

12454. Permutation
Problem code: PERMU
A permutation is a sequence of integers p 1 , p 2 , ..., p n , consisting of n distinct positive integers, each
of them doesn’t exceed n. Let’s denote the i-th element of permutation p as p i . We’ll call number n the
size of permutation p 1 , p 2 , ..., p n .

Nickolas adores permutations. He likes some permutations more than the others. He calls such
permutations perfect. A perfect permutation is such permutation p that for any i (1 <= i <= n) (n is the
permutation size) the following equations hold p p i = i and p i != i. Nickolas asks you to print any
perfect permutation of size n for the given n.

Input
First line will contain number of testcase T, followed by T lines .

Each line contains a single integer n (1 <= n <= 100) -- the permutation size.

Output
If a perfect permutation of size n doesn’t exist, print a single integer -1. Otherwise print n distinct
integers from 1 to n, p 1 , p 2 , ..., p n -- permutation p, that is perfect. Separate printed numbers by
whitespaces.

Example
Input:
3124Output:
-1 2 1 2 1 4 3

Added by: CounterinsurgectoR


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

1
(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 (tutorial)

12455. Order
Problem code: RIOI_0_1
You are given permutation of N integers, that is, every number fomr 1 to N appears exactly once in
the array. What is minimal number of swaps needed to sort the array ?

Constraints :

N <= 100

Input
First number in the input is number t (t <= 100), donating number of test cases. Every testcase looks as
follows. First line is number N describing size of the array. N number follow, donating the array.

Output
Output one number, minimal number of swaps.

Example
Input:232 1 355 3 4 2 1Output:13Explanation : In the first case, we swap (1, 2). In second example, we swap (5,1), (3,2), (4,3).

Added by: Buda IM


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

1
(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 (tutorial)

12456. NUMBER SERIES


Problem code: NUMSERIE
Problem Statement:
A number series 1,2,3,4,6,9,13,... is generated using the formula t[n]=t[n-1]+t[n-3]

Print the first 100 terms in the series.

Output:

Just print the first 100 terms in the series one per line

Example:

Sample Output:

(100 terms)

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

2
(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 (tutorial)

12457. HELP NERUBAN


Problem code: DOTAA2
Problem Statement:

Neruban, the DotA gamer knows to play with some heroes. You are given the list of heroes that
Neruban knows to play with. You are also given how accurate he can play, how fast he can play and
how stupidly he can play with every hero. i.e. for each hero you are given 3 values Accuracy(a),
Speed(v) and Stupidity(s). Neruban wants to rank the heroes according to the order with which he can
play perfectly. So sort the heroes based on higher accuracy, higher speed and lower stupidity

For example a hero with a=10, v=1, s=100 is higher ranked than a hero with a=1,v=100,s=0, because
first preference is given for the accuracy of the hero.

Similarly a hero with a=10, v=5, s=20 is higher ranked than a hero with a=10, v=4, s=40, because
second preference is given for the speed of the hero.

A hero with a=10, v=3, s=10 is higher ranked than a hero with a=10, v=3, s=15, because stupidity of a
player should be lower

If any two heroes have same accuracy, speed and stupidity, sort them based on their name
alphabetically.

Input:

The first line consists of an integer n, the number of heroes. The next n lines describe each hero with 4
values - the name of the hero, accuracy, speed and stupidity.

Output:
Sort the heroes based on the above criteria and print the rank list.
Input Constraints:
1<=n<=100000
Name of a hero <= 15 characters (all lower case)
0<=a,v,s<=100
Example:

Sample Input:

goblinshredder 45 66 98

1
pudge 45 86 76

shadowfiend 99 98 2

invoker 45 86 75

Sample Output:

shadowfiend

invoker

pudge

goblinshredder

Added by: cegprakash


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

2
(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 (tutorial)

12458. Unique strings


Problem code: RIOI_0_2
You are given N strings, you have to determin how many of them are unique. Unique means that it
apperars in the input only once.

Constraints :

N <= 100000

sum of all lengths of strings <= 2*10^6

Input
First line of input is number t, donating number of test cases. Next line consists of interger N. N lines
follow each contaning one string.

Output
Output asked number.

Example
Input:110abaasdfabbe abaabbeaaaaaaaaabbeaaaabbbbOutput:2 Explanation, "bbbb" and "asdf" are only two strings that are unique in the input.

Added by: Buda IM


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

1
(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)

12460. Eat a Good Meal


Problem code: GOODMEAL
You’re hungry, and you’re about to be executed. You’re planning your last meal, and you want to be
sure you maximize your enjoyment. Pizza, for example, provides a 7/10 enjoyment level per slice, but
takes up 20% of your available stomach space per slice. Fudge, on the other hand, provides a 9/10
enjoyment level per square and uses only 2% of your available stomach space, but you can only eat 3
squares before you get sick of it.
Given a potential menu by your captors, including the enjoyment level it provides per unit, the
stomach space required per unit, and the maximum number of units you can enjoy, plan the perfect
final meal.
Input:
First line is an integer, representing the number of different items on the menu.
Each subsequent line is one menu item, formatted as "name spacePerUnit enjoymentPerUnit
maxUnits".
Output:
The maximum amount of enjoyment you can get from the available menu within 100 stomach space,
as an integer.

Input Output
3
Pizza 20 7 5
61
Fudge 2 9 3
Soda 5 3 3
4
Burrito 10 4 10
Apple 5 5 2 70
Pie 5 8 2
Cookies 2 4 4
4
Steak 20 8 1
Potato 10 4 2 31
Vegetables 10 1 10
Sundae 15 6 2

1
Added by: Ben Dilts
Date: 2012-10-12
Time limit: 10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All

2
(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)

12465. Shared Letters


Problem code: SHARELET
Determine how many unique letters are shared by two sentences. For example, "this is fun" and
"this is not fun" share the letters "thisfun", for a total of 7 different letters. Note that the space
character is not counted.
Input:
Two lines, each of which contains a sentence
Output:
An integer representing how many different letters are shared by the two input sentences

Input Output
this is fun
7
this is not fun
i love my dog
6
lorem ipsum dolor sit amet
strange things are afoot at the circle k
11
what we need is great strength of feet

Added by: Ben Dilts


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

1
(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)

12466. Closest Points


Problem code: CLOSPT
Determine the square of the distance between the closest two points in a set of points. For
example, among the points (1,1), (5, 1), and (1,3), the closest distance between two points is 2, the
distance between (1,1) and (1,3). So the correct output is 22 = 4.
Input:
The first line is the number of points
Each subsequent line is the X and Y coordinates (positive integers) of one point, separated by a
space
Output:
The square of the minimum distance between two of the input points, as an integer.

Input Output
3
11
4
51
13
8
53
49
13 9
16 11 5
22 9
12 1
83
91
4
32
94 8
72
1 14

1
Added by: Ben Dilts
Date: 2012-10-13
Time limit: 10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All

2
(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 (tutorial)

12470. Friend numbers


Problem code: KHALED
 

Ahmed and Mohamed love friends numbers - they say number x is friend to number y if and only if
X contains number of digits equals to number of digits in Y. ex : 123 is friend to 457 , 1000 is friend to
9999 But 789 is NOT friend with 10 .
Ahmed and Mohamed Decide to play a game, they choose randomly 2 friend numbers and count their
different in digits.
Ex: 1) 123 and 457 is different in 3 digits (because (1) is not the same to its corresponding digit (4) ,
(2) is not same to its corresponding digit (5) ... and so on . Ex: 2) 123, 145 different in 2 digits. Given
2 friend numbers Count the different between their digits

Ahmed and Mohamed love friends numbers - they say number x is friend to number y if and only if X
contains number of digits equal to number of digits in Y. ex : 123 is friend to 457 , 1000 is friend to
9999 But 789 is NOT friend with 10 .

Ahmed and Mohamed decide to play a game, they choose randomly 2 friend numbers and count the
number of different digits.

Ex: 1) 123 and 457 are different in 3 digits (because (1) is not the same to its corresponding digit (4) ,
(2) is not same to its corresponding digit (5) ... and so on .

Ex: 2) 123, 145 are different in 2 digits. Given 2 friend numbers count the number of differences
between their digits.

Input
Two space-separated friend numbers X and Y, (0<=X, Y<=1000000000)

Output
The number of different corresponding digits.

1
Example
Input:
10000 15678

Output:
4

Added by: Hossam El-Deen Goodname


Date: 2012-10-13
Time limit: 1s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: Khaled Samy

2
(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 (tutorial)

12473. INVITATION FOR TECHOFES


Problem code: TECHOFES
Problem Statement:

You are going to invite chief guests for Techofes. There are n guests. You are given the cost required
and the popularity of each chief guest. Among the n guests, you can invite any number of guests. But
for inviting a guest, you have to pay his required cost. The expected number of audience is the sum of
popularity of all the chosen guests. You only have M amount of money in hand. Find the maximum
expected number of audience.

Input:

The first line consists of an integer t, the number of test cases. For each test case { The first line
consists of 2 integers n and M - the number of guests and the money in hand respectively. Then n lines
follows, each line contains two integers - the cost and popularity of each guest. }

Output:
For each test case find the maximum expected number of audience.
Input Constraints:
1<=t<=10
1<=n<=20
0<=cost,popularity<=1000
0<=M<=20000
Note that some chief guests may have no cost
Example:

Sample Input: (blank lines just for clarity)

28

19

57

22

1
2 14

2 12

59

91

64

7 15

3 12

95

Sample Output:

16

14

16

Added by: cegprakash


Date: 2012-10-14
Time limit: 2s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All

2
(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 (tutorial)

12509. STRING PROBLEM


Problem code: STRINGPR
Problem Statement:

Given a run length coding, convert it into a string, in-place

Input Format:

The first line consists of an integer t, the number of test cases. Each test case consists of a string
representing the run length code.

Input Constraints:

1<=t<=100

The run length code can be upto a maximum of 30 characters(all in lower case)

Each number in the run length code will not exceed 99

Sample Input:
3
a1b4c2d3
ab2c3d

a11b

Sample Output:

aabbbbbcccdddd

abbbccccd

aaaaaaaaaaaab

1
Added by: cegprakash
Date: 2012-10-17
Time limit: 2s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All

2
(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)

12510. JUMPING DORA


Problem code: JUMPDORA
Problem Statement:

Jumping Dora wants to reach her destination from the source as soon as possible.
Dora’s initial position is (0,0) and the destination is (m-1,n-1)
If Dora is currently at (i,j), she can either move to (i,j+1) or (i,j+1+C[i][j]) or (i+1,j) or (i+1+C[i][j],j)
Dora cannot move to the blocked positions.
Note that you can jump when there are blocks in between.

Find the shortest time required to reach the destination.

Input:
The first line consists of an integer t, the number of test cases. For each test case, the first line consists
of two integers m and n representing the number of rows and columns. Then follows the description of
the matrix C.
Output:

1
For each test case find the shortest time required to reach the destination. If it is impossible, print -1.
Input Constraints:

1<=t<=100
2<=m,n<=100
C[i][j]={ [0-9] , # }

Note: There may be no path to the destination from the Source. In such cases print -1.

C[0][0] and C[m-1][n-1] are always 0.

Sample Input:

44

0#03

1120

#0#0

0100

Sample Output:

Added by: cegprakash


Date: 2012-10-17
Time limit: 1s-10s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All

2
(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 (tutorial)

12511. CUBE ROOT


Problem code: CUBEROO2
Problem Statement:

Find the cube root of the given numbers. Print exactly the first four decimal places. (Do not round
off.)

Input:

The first line consists of an integer t, the number of test cases. For each test case, you are given an
integer n.

Output:

For each test case, print the cube root of the number in the specified format.

Input Constraints:

1<=t<=1000

1<=n<=10^9

Sample Input:

1000000

Sample Output:

1
2.0000

100.0000

Added by: cegprakash


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

2
(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)

12515. INVITATION FOR TECHOFES (v2)


Problem code: TECHOFEZ
Problem Statement:

You are going to invite chief guests for Techofes. There are n guests. You are given the cost required
and the popularity of each chief guest. Among the n guests, you can invite any number of guests. But
for inviting a guest, you have to pay his required cost. The expected number of audience is the sum of
popularity of all the chosen guests. You only have M amount of money in hand. Find the maximum
expected number of audience.

Input:

The first line consists of an integer t, the number of test cases. For each test case { The first line
consists of 2 integers n and M - the number of guests and the money in hand respectively. Then n lines
follows, each line contains two integers - the cost and popularity of each guest. }

Output:
For each test case find the maximum expected number of audience.
Input Constraints:
1<=t<=10
1<=n<=50
0<=cost,popularity<=1000
0<=M<=50000
Note that some chief guests may have no cost
Example:

Sample Input: (blank lines just for clarity)

28

19

57

22

1
2 14

2 12

59

91

64

7 15

3 12

95

Sample Output:

16

14

16

Added by: cegprakash


Date: 2012-10-18
Time limit: 2s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All

2
(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)

12523. Nuts Frenzy


Problem code: TIGA
Ivan, Filbert, and Tracy really like nuts. They can eat nuts without stopping all day long if they want
to. Today they decided to buy some nuts so each one of them get exactly K nuts
(1<=K<=1,000,000,000) and they want to eat it all. To make it interesting, they are only allowed to eat
a certain number of nuts every second.

Ivan can eat at max I nuts per second. (1<=I<=1,000,000)


Filbert can eat at max K/F nuts per second. (1<=F<=100)
Tracy can eat at max the sum of all the factors of K excluding 1 and K nuts per second.

They are not allowed to eat only a fraction of a nut every second, and they must eat a minimum of 1
nut every second regardless of the previous rule. They can stop eating after they run out of nuts. Your
task is to determine the time needed (in seconds) for each of them to finish their nuts!

Input
The first line of input is T, the number of test case. (T<20)
The next T lines each consists of three numbers K, I, and F separated by a space.

Output
For each test case, output the minimum time needed for Ivan, Filbert, and Tracy to finish their nuts.

Example
Input:

310 2 5100 10 4121 100 1Output:

5 5 210 4 12 1 11

Added by: Andy William


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

1
(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)

12540. It is Super Effective


Problem code: EFFECTIV
As you may know, this world is inhabited by creatures called Dokémon! For some people, Dokémon
are pets. Other use them for fights.

During a Dokémon battle, two Dokémon attack each other, alternately, until one of them faints. The
survivor is declared the winner.

In this problem, every Dokémon has one (and only one) type, which indicates the creature’s strength.
Also, all attacks made by a Dokémon are physical and cause damage to its opponent.

An attack can be regular, super effective (it causes twice as much damage of a regular attack) or not
very effective (it causes half the damage of a regular attack). This classification depends on the types of
the Dokémon that are fighting.
The table below indicates how the attacks are classified. The character + in the i-th row and j-th
column indicates that an attack made by an i-typed Dokémon against a j-typed Dokémon is super
effective. The characters - and . indicate not very effective and regular attacks, respectively.

The names above the columns are abbreviated, but represent the same names in the rows, in the same
order.

1
Bash Catchem is a young boy from Lappet Town who wishes to be a Dokémon Master one day.
However, he is still studying tactics for his Dokémon battles. Your task is to help Bash to determine,
given descriptions of Dokémon Battles, the effectiveness of the attacks during the battles.

Input
Each test case starts with a line containing an integer P, 1 <= P <= 151, the number of different
Dokémon that exists in our world. Each of the next P lines contains the description of a Dokémon
given as two strings N T, where N is the name of the creature and T is its type. Its name contains up to
15 lowercase or uppercase letters, and its type is one of the types given in the table above, not
abbreviated.
The next line contain an integer Q, 1 <= Q <= P^2, the number of queries. Each of the next Q lines
contains names of two Dokémon, N1 N2, describing a battle. It’s guaranteed that both names were
described in the same test case.
The last test case is followed by a line containing the number 0.

Output
For each query, print "It’s super effective!" if an attack of N1 is super effective against N2. Print "It’s
not very effective..." if the attacks are not very effective, or "Regular Attack." otherwise. The character
’ has the decimal code 39 in the ASCII table.
Print a blank line after each test case.

Example
Input:
4Pikaxu ElectricSquartle WaterDullbasaur GrassCharminder Fire2Pikaxu SquartleDullbasaur Charminder3Miauth NormalWizang PoisonKabrada Psychic2Kabrada WizangWizang Miauth0

Output:
It’s super effective!It’s not very effective...It’s super effective!Regular Attack.

Added by: Ricardo Oliveira [UFPR]


Date: 2012-10-24
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: UFPR Training session

2
(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)

12564. Innovative Combination


Problem code: CDC12_I
 

Suddenly Ronny opened his eyes, the entire battle was only a dream! Then he looked up his
watch and realize that it was really late, and decided to go back home.
Inmediatly after his arrival he received a call from CEIDEC (Center of Extraordinary Inves-
tigations Defining Excluded Creatures), they needed a password to open the exit door of the
congress, and Ronny was the only one that knew the combination, but he forgot it! Fortunately,
he had a "clue" of the password that says: Given a sequence of numbers, and a special list of
numbers, the password would be the number of appearence of each special number on the first
sequence, keeping the order of the list of special numbers.
Input
The first line contains an integer T , which specifies the number of test cases. Then, will follow
the descriptions of T test cases.
Each test case description will contain an integer N and an integer M . N is the size of the first
sequence of numbers, and M is the size of the list of special numbers. Note: A special number
will not always appear at least once on the entire sequence.
After that, a line with N numbers that represents the sequence, and then a line with M num-
bers that represents the list of special numbers.
The input must be read from standard input.
Output
For each input case you must print a single line with the string "Scenario #i: " where i is the
number of the test case (Starting by 1), followed by the password of the exit door of the congress.
The output must be written to standard output.

Suddenly Ronny opened his eyes, the entire battle was only a dream! Then he looked up his

watch and realize that it was really late, and decided to go back home.

Inmediatly after his arrival he received a call from CEIDEC (Center of Extraordinary Inves-

tigations Defining Excluded Creatures), they needed a password to open the exit door of the

congress, and Ronny was the only one that knew the combination, but he forgot it! Fortunately,

he had a "clue" of the password that says: Given a sequence of numbers, and a special list of

1
numbers, the password would be the number of appearence of each special number on the first

sequence, keeping the order of the list of special numbers.

Input

The first line contains an integer T , which specifies the number of test cases. Then, will follow

the descriptions of T test cases.

Each test case description will contain an integer N and an integer M . N is the size of the first

sequence of numbers, and M is the size of the list of special numbers. Note: A special number

will not always appear at least once on the entire sequence.

After that, a line with N numbers that represents the sequence, and then a line with M num-

bers that represents the list of special numbers.

The input must be read from standard input.

Output

For each input case you must print a single line with the string "Scenario #i: " where i is the

number of the test case (Starting by 1), followed by the password of the exit door of the congress.

The output must be written to standard output.

INPUT OUTPUT
3 Scenario #1: 12
52 Scenario #2: 2223
33544 Scenario #3: 224422
54
74
4855548
4485
10 6
3376557666
576635

Constraints

* 1 <= T <= 100

2
* 1 <= N <= 100,000

* 1 <= M <= 100,000

* 1 <= Ni , Mi <= 100,000

Added by: Venezuelan Programming League


Date: 2012-10-27
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: Own problem used for UCV-CEIDEC 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 (classical)

12579. Search Insert Delete


Problem code: SID
You are given a bunch of data (all are positive 32 bit numbers) to operate on. The only operations on
the data are search, insert, and delete. When storing the data you have to remember its rank, that is the
original position when the data is being inserted. All successful operations must return the ranks of the
data. Failed operations should return NONE as the answer.

Your objective is to execute all of the operations as fast as possible.

Input
The first line of input is N and M, separated by a space, N is the number of initial data. ( 0 <= N <
1000000 ) and M is the number of operations against the data. ( 0 <= M < 1000000).

The second line contains N data, seperated by blanks. All data are positive 32 bits numbers

The next M lines contains operations against the data. Each line contains a symbol and a number,
separated by a space. 

There are 3 symbols (S, I, D), each representing search, insert, and delete operation.

’S number’ tries to find the number in the stored data, and outputs its first rank in the stored data (as
originally inserted), or NONE if no such number exists.

’I number’ inserts the number into the stored data, and outputs its rank in the stored data. (Data can be
duplicated).

’D number’ deletes the least ranked number found in the stored data, and outpus its rank, or NONE if
no such number originally exists.

Output
There is an output for each executed operation. See the above input description about each operation
for the detail of the output.

Example
Input:10 620 12 10 28 20 50 49 8 51 1S 20I 3S 11D 20I 2S 20Output:111NONE1125

1
Added by: Jimmy Tirtawangsa
Date: 2012-10-28
Time limit: 1s-3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: C C# C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource: Own problem

2
(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 (tutorial)

12596. Palindrom 1
Problem code: MO1002
?g?gds?n khoër orontoj toog palindrom esekhijg togtoo.

Input
KHoër orontoj neg b?khel too ?g?gd?n?.

Output
Palindrom bol YES biš bol NO gesen ?r d?n gargana.

Example
Input:
87

Output:
NO

ExampleInput:
44

Output:
YES

Added by: mbt


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

1
(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 (tutorial)

12599. K-DIGITS
Problem code: DIGIT
Tim tât ca? các sô trong he^. K phân có N chu+~ sô, trong đó không có 2 chu+~ sô 0 nao đu+’ng ca.nh
nhau

VD: N = 7 va K = 10

-   Sô 1030650 tho?a man đie^‘u kie^.n

-   Sô 1000179 không tho?a man đie^‘u kie^.n

-   Sô 0555555 không tho?a man đie^‘u kie^.n

INPUT

2 sô N va K( K > 1; N > 0 );

OUTPUT

Ke^’t qua? bai toán

EXAMPLE

Input: 2 10

Output: 90

Chú ý:

20% test có k = 2; n <= 100

20% test có k <= 5; n <= 1000

1
20% test có k <= 10; n <= 2000

20% test có k <= 10; n <= 10000

20% test có k <= 1000; n <= 1000

Added by: Christian Eriksen


Date: 2012-10-31
Time limit: 1s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: C C# C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc
Resource: ..................

2
(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 (tutorial)

12602. Urvuu too


Problem code: MO1003
Gurvan orontoj too ?gs?n bol t??nij urvuu toog ol.

Input
Gurvan orontoj neg too ?g?gd?n?.

Output
Urvuu toog khevlene.

Example
Input:
876

Output:
678

Added by: mbt


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

1
(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 (tutorial)

12607. Missing one


Problem code: RIOI_2_1
You are given string S. Find lexicographicaly smallest string, that is not subsequence of given string.
Subsequence of string is created by deleting zero or more characters from starting string.

Subsequences of string "abc" are { "a", "b", "c", "ab", "ac", "bc", "abc" }

Constraints :

|S| <= 10000

Input
First line of the input is number t (t <= 10000) donating number of testcases. t lines follows, each
containing string S, length of each string is at max 10000 (10^4). 

Output
Output t strings, solution to each test.

Example
Input:
2

bcd

abcdefghijklmnnjoprstuvjklmqyz

Output:

aa

Added by: Buda IM


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

1
(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 (tutorial)

12608. Switch
Problem code: RIOI_2_2
You are given array A of length N, initially all values in A are set to 0. We will make M passes
through array. On ith pass we will visit cells B[i], 2*B[i], 3*B[i], and so on. In other words we visit
cells that are multiples of B[i]. When we visit xth cell we change its value from 1 to 0 or from 0 to 1.
That is if A[x] was 1 before visit, it changes to 0, or if it was 0 before visit it changes to 1. 

After we make all M passes, we wonder what is the sum of the array.

Constraints :

1 <= N, M <= 100000

B[i] <= N

Input
First line contains t, donating number of tests. Each test looks as follows. First line consists of 2
integers, N and M, size of array and number of passes respectively. Second line consists of M integers
donating integer array B, which means that in ith pass we will visit cells that are multiples of B[i] . 

Output
Ouput t lines, solution to each test case.

Example
Input:
2

5 3

1 2 3

5 5

1 2 3 4 5

Output:

1
2

Added by: Buda IM


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

2
(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)

12650. Even and Odd


Problem code: EVENODD
Given undirected graph, we are interested to state 2 points
1- Is the count of nodes with odd degree, even or odd?
2- Is the count of nodes with even degree, even or odd?

Use following pseudocode to construct the graph:

FOR i = 1 to N

  FOR J = 1 to min(N-i, K)

  add_graph_edge(i, i+j);

where node degree is defined as: the number of edges incident to the vertex. This graph will be
generated through following pseudocode, for a given N (number of nodes) and K (connectivity factor).

For example, given N = 5, K = 3 we have a graph consisting of 2 nodes with odd degree and 3 nodes
with even degree.

Input
The first line of input contains an integer T that represents the number of test cases, then follow T lines
each contains only two integer numbers N, K where 1 <= N <= 100,000 and 0 <= K <= N.

Output
For each test case, output on a single line "Case #K:" where K is the number of the test case, followed
by either "even" or "odd" for the count of nodes with odd degree, then single space, then either "even"
or "odd" for the count of nodes with even degree. Check Sample below to see the format.

Example
Input:
1
53
Output:
Case #1:
even odd

1
 

Added by: Mostafa Saad


Date: 2012-11-05
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: 11th Egyptian Collegiate Programming Contest

2
(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)

12793. The power of two


Problem code: ATWO
World is a funny place, one moment you are walking around the street eating some chicken and the
other you are wondering: what numbers are a power of 2? not only that, you also want to know , 
given a number that ain’t power of 2, the closest increasing power of 2, that means for example that if
you get: 5, you will show 5 8, because 8 is the closest increasing power of 2 from 5.

Input
first line will have a T (1<=T<=10000) the next T lines will contain an integer (which we do not
ensure that fits on 32-bits, but maybe it does)

Output
If the number is a power of 2, just print it. If it is not a power of two, you will print the number and
after that print the closest increasing power of 2

Example
Input:40123
Output:
0 1123 4

Added by: Rodolfo Miquilarena


Date: 2012-11-19
Time limit: 0.600s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: own problem

1
(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)

12801. Browsing History


Problem code: HISTORY2
One day when you are going to clear all your browsing history, you come up with an idea: You want
to figure out what your most valued site is. Every site is given a value which equals to sum of ASCII
values of all characters in the URL. for example aa.cc has value of 438 because 438 =
97+97+46+99+99. You just need to print the largest value amongst all values of sites.

Things are simplified because you found that all entries in your browsing history are of the following
format:[domain] (quotes for clarify) where [domain] consists of lower-case latin letters and ‘.’ only.
You can see the sample for more details.

Input
There are several test cases, please process till EOF. Each test case starts with a line of a integer n (1
<= n <=100), the number of entries in your browsing history. Then follows n lines, each consisting of
one url whose length will not exceed 100.

Output
For each case please print one line containing the answer to corresponding test case. Please see the
sample output for detailed format.

Example
Input:
1
aa.cc
2
www.google.com
www.wikipedia.org

Output:
Case 1: 438
Case 2: 1728

1
Added by: [Trichromatic] XilinX
Date: 2012-11-21
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: ACM/ICPC Regional Contest, Chengdu 2012

2
(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 (tutorial)

12823. Print Big Binary Numbers


Problem code: PBBN1
Some answers for some problems could be huge binary numbers. In order to check the computation,
one could ask you the sum of its digits. With a little base, the answer is a small number too, but not
with a bigger base.

XerK would like to avoid precomputed results and wish check you’ve computed his huge numbers.
Here’s a tutorial problem that check computation of a big number N. A classical edition exists with
language restrictions.

Let define the function CHK(N, B): Input : N a big number in binary representation, B a power of two.
Consider N as a base B number. Output : the sum of its digits in this base.

Example :with B=2^8, 12345678 = 78 + 97*B + 188*B*B, so CHK(12345678, B) = 78 + 97 + 188

This should be easily computed with few bitwise-AND, bitshifts and additions.

Input
The input begins with the number T of test cases in a single line. In each of the next T lines there are
four integer numbers A, B, C, D, given in base 10.

Output
For each test case : * compute N = (A^B) XOR (C^D). * print CHK(N, 2^16384) as a base 10 number.
(^ denote the power, and XOR the bitwise operator)

Example
Input:
2
7 3 5 4
1234 5678 9012 4444

Output:
806
1194204158794232147799<...snip...>9938532444216215551948305

1
Explanations
For test case 1: 7^3 = 343, 5^4 = 625, 343 XOR 625 = 806, CHK(806, 2^16384) = 806.

For test case 2: You have to output all 4933 digits of the result.

Constraints
1 < T <= 321
1 < A, B, C, D <= 10^4

Added by: Francky


Date: 2012-11-23
Time limit: 10s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All
Resource: Own problem

2
(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 (tutorial)

12851. Bâc thây pha che^’ ru+o+.u


Problem code: QTANCOL
Ancol la môt tay pha che^’ ru+o+.u có tie^’ng o+? VOJ. Cách pha che^’ ru+o+.u cu?a anh ta rât đăc bie^.t đó la:

- Chi? dung N chai đe^? pha che^’ ru+o+.u.

- Không có 2 chai nao có đô ru+o+.u băng nhau.

- Chi? dung 2 loa.i ru+o+.u đe^? pha che^’ cho môi ly ru+o+.u ma khách go.i.

- Chi? lây 2 loa.i ru+o+.u năm o+? gân nhau.

- Sau khi pha che^’ xong anh ta se~ đôi vi. trí 2 chai ru+o+.u đó.

Tuy nhien do su+’c kho?e anh ta chi? pha cho đúng K vi. khách rôi nghi?.

Vao môt buôi sáng đe.p tro+‘i, anh ta nhân ra 1 đie^‘u la có rât nhie^‘u lân sau khi nghi? các chai ru+o+.u đu+o+.c săp xe^’p vo+’i đô ru+o+.u tăng dân măc du ban đâu chúng đu+o+.c đe^‘ o+? vi. trí bâ...

Input:

Gôm 2 sô N,K.

Output:

Sô tru+o+‘ng ho+.p các chai ban đâu ma sau khi nghi? các chai ru+o+.u đu+o+.c xe^’p tăng dân ve^‘ đô ru+o+.u sau khi modul 10 9 +9.

Examples:

3 0  

1  

Gia?i thích: (1,2,3)

3 1 

2  

Gia?i thích: (2,1,3) => (1,2,3)

               (1,3,2) => (1,2,3)

3 2  

Gia?i thích: (3,1,2) => (1,3,2) => (1,2,3)

               (2,3,1) => (2,1,3) => (1,2,3)

               (1,2,3) => (1,3,2) => (1,2,3)

3 3  

3  

Gia?i thích: (2,1,3) => (1,2,3) => (2,1,3) => (1,2,3)

               (1,3,2) => (1,2,3) => (1,3,2) => (1,2,3)

               (3,2,1) => (3,1,2) => (1,3,2) => (1,2,3)

1
Lu+u ý: thu+’ tu+. đôi va cách đôi khác nhau vo+’i cung 1 thu+’ tu+. chai ban đâu chi? tính la 1.

(1,3,2) => (1,2,3) => (1,3,2) => (1,2,3)

(1,3,2) => (1,2,3) => (2,1,3) => (1,2,3)

2 cách cách đôi tren đu+o+.c xem la 1 vi đe^‘u xuât phát tu+‘ (1,3,2).

Gio+’i ha.n: 1<=N<=2000. 0<=K<=2000.

Added by: Pig Yellow


Date: 2012-11-27
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: add bo+?i blackstart

2
(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 (tutorial)

12856. Hoa hu+o+’ng du+o+ng


Problem code: QTLOVE
 

Ngay ki? nie^.m 1 năm quen nhau cu?a MN va MH đa to+’i. Chang trai MN cu?a chúng ta quye^’t
đi.nh chuân bi. 1 món qua thât đăc bie^.t đe^? tăng cho ngu+o+‘i yeu cu?a minh. MN đa tu+. lam cho
  MH môt bông hoa hu+o+’ng du+o+ng thât to băng giây. Vo+’i tai năng thien bâm cung vo+’i su+.
ti? mi?, MN đa lam xong 1 bông hoa thât to, nhi. hoa la 1 hinh tron vo+’i N cánh hoa cách đe^‘u
nhau

 Công vie^.c cuôi cung la tô mau các cánh hoa, công vie^.c nay không he^‘ đo+n gia?n. Bie^’t
ngu+o+‘i yeu minh rât thích mau săc săc so+~ va không thích nhu+~ng bông hoa nao có 2 cánh hoa
gân nhau có mau giông nhau. MN đa chuân bi. M mau đe^? trang trí. MN muôn lam thât nhie^‘u bông
hoa khác nhau tu+‘ M mau đó đe^? góp thanh môt bó hoa thât lo+’n đem tăng MH. Nhu+ng khô nôi
MN không bie^’t đu+o+.c bó hoa cu?a minh se~ có bao nhieu bông hoa đe^? chuân bi.. Hay giúp anh
ba.n si tinh khôn khô cu?a chúng ta nao, đu+‘ng đe^? ngu+o+‘i yeu cu?a minh nôi giân, con gái nôi
giân thi pha?i mât ca? tuân đe^? xin lôi đó.......

Lu+u ý: Hai bông hoa đu+o+.c go.i la khác nhau ne^’u chúng có 1 cánh hoa có mau khác nhau

1
 

2 căp hoa vo+’i n=5 va n=6 tren la 2 căp hoa khác nhau

Input: Hai sô N,M.

Output: Sô bông hoa sau khi modul 10 9 +7.

Example:

34

24

43

18

Gio+’i ha.n: N<=10 6 . M<=10 9 .

 Sau khi lam xong bai nay ba.n có the^? lam QTLOVE2.

Added by: Pig Yellow


Date: 2012-11-29
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All
Resource: add bo+?i blackstart

2
(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)

12857. Hoa hu+o+’ng du+o+ng


Problem code: QTLOVE2
Ngay ki? nie^.m 1 năm quen nhau cu?a MN va MH đa to+’i. Chang trai MN cu?a chúng ta quye^’t đi.nh chuân bi. 1 món qua thât đăc bie^.t đe^? tăng cho ngu+o+‘i yeu cu?a minh. MN đa tu+. lam cho MH môt bô... 

 Công vie^.c cuôi cung la tô mau các cánh hoa, công vie^.c nay không he^‘ đo+n gia?n. Bie^’t ngu+o+‘i yeu minh rât thích mau săc săc so+~ va không thích nhu+~ng bông hoa nao có 2 cánh hoa gân nhau có ...

Lu+u ý: Hai bông hoa đu+o+.c go.i la khác nhau ne^’u chúng có 1 cánh hoa có mau khác nhau
 

2 căp hoa vo+’i n=5 va n=6 tren la 2 căp hoa khác nhau

Input: Hai sô N,M.

Output: Sô bông hoa sau khi modul 10 9 +7.

Example:

1
3 4

24

4 3

18

Gio+’i ha.n: N<=10 18 . M<=10 9 .

Added by: Pig Yellow


Date: 2012-11-29
Time limit: 1s
Source
50000B
limit:
Cluster: 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: add bo+?i n_cqt

2
(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 (tutorial)

12861. LATARNIE JASIA


Problem code: LATARNIE
 

Jaś jest na szkolnej wycieczce "Szlakiem pomorskich latarni". W trakcie zwiedzania zastanawiał się
na następującym problemem: "W którym miejscu będzie równoodległy od trzech latarni morskich".
Ale Jaś jest ma problemy z matematyką. Poprosił więc Ciebie, ucznia klasy matematyczo-fizycznej
o pomoc.

Jaś jest na szkolnej wycieczce "Szlakiem pomorskich latarni". W trakcie zwiedzania zastanawiał się

na następującym problemem: "W którym miejscu będzie równoodległy od trzech latarni morskich".

Ale Jaś jest ma problemy z matematyką. Poprosił więc Ciebie, ucznia klasy matematyczo-fizycznej

o pomoc.

Wejście
 

W pierwszym wierszu wejścia znajduje się liczba całkowita n (n>0) oznaczająca liczbę miejsc do

sprawdzenia. Kolejne n-wierszy zawiera trzy pary liczb rzeczywistych oznaczających odpowiednio:

x A , y A , x B , y B , x C , y C , gdzie x i , y i oznaczają odpowiednio współrzędne x i y punktów A, B i C.

Wyjście
 

Każdy z n-wierszy wyjścia zawiera oddzielone spacjami współrzędne x i y szukanego miejsca z

1
dokładnością do jednego miejsca po przecinku.

Przykład
Wejście:
1
3.7 3.7 12.2 3.6 4.6 13.2

Wyjście:
8.00 8.09

Added by: Marek Dudzicz


Date: 2012-11-30
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: C++ 4.3.2

2
(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)

12910. Addicted Numbers


Problem code: TA1
Anshuman was playing a game. The game consists of following steps

1. He summed all the digits of a number.

2. Untill the sum became less than 10, he repeats the above step for the new number ie. sum of all the
digits of the num

As the numbers are very large you have to help him figure out the final output of the game.

Input
First line of the input contains an integer t, 1<=t<=10 denoting the number of testcases, followed by t
lines each containing a number n, 1<=n<=10^300000

Output
For each number n given at input, display a line with the final number.

Example
Input:212345213413512 Output:
64 For first testcase 1+2+3+4+5=151+5=6

Added by: Sandeep Singh Jakhar


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

1
(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 (tutorial)

1004151. Zoos
Problem code: HICHEEL
Batad n širkheg zoos bajgaa ba zoos b?r n’ ??rijn gesen a[i] (i - dakh’ zoosny ?ne) ?netej. Negen ?d?r
Bulgaad m?ng? khereg bolžee. Bat khamgijn baga toony zoos ??rt?? avč ?ldeed busad zoosoo Bulgaad
?g?kh ba Batyn avč ?ldsen zoosnuudyn ?nijn nijlber Bulgaad ?gs?n zoosnuudyn ?nijn nijlberees ikh
bajkh ëstoj. KHamgijn bagadaa kheden zoos avč ?ldekh šaardlagataj ve.M?n Bulgaad zaaval zoos
?g?kh albag?j ba Bulgaad ?gs?n zoosnuudyn ?nijn nijlber n’ Batad ?ldsen zoosnuudyn ?nijn nijlbertej
tentsež bolokhg?j.</br>

KHâzgaarlaltuud:</br>

1 <= n <= 10000 </br>

1 <= a[i] <= 100 </br>

Orolt :</br>

Ekhnij m?r?nd n too.</br>

KHoër dakh’ m?rt n širkheg a[i] too zajgaar tusgaarlagdan ?g?gd?n?.</p>

Garalt:</br>

Avč ?ldekh khamgijn baga zoosny širkheg bolokh gants too.</p>

Žišee:</br>

Orolt:</br>

5</br>

1 6 2 9 3</br>

Garalt:</br>

2</br>

Tajlbar: Ta 6 bolon 9 gesen zoosnuudyg avč ?ldekhed nijlber n’ najzdaa ?g?kh zoosnuudyn ?nijn
nijlberees ikh bajna. (6+9 > 1+2+3)

1
Added by: Dulguun Batmunkh
Date: 2012-03-06
Time limit: 1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All except: NODEJS PYTH 3.2.3 n

You might also like