# Spotify Programming Challenge 2011 · Spotify Programming Challenge 2011 Problem A: All Just A...

### Transcript of Spotify Programming Challenge 2011 · Spotify Programming Challenge 2011 Problem A: All Just A...

Spotify Programming Challenge 2011

May 21, 2011

Problems

A All Just A DreamB Imperial MeasurementC Wheel GameD Primary RegistersE PlaylistF Pie SquaresG Peer StreamingH Cat Coat Colors

(the problems are not sorted by difficulty)

Submission Instructions

• To submit a solution to one of the problems, send an e-mail to [email protected] with your sourcecode files as attachments and the problem id or problem name as subject. For instance, to submit to problemA “All Just A Dream”, the e-mail should have subject “dream” or “All Just A Dream”. Within minutes youwill get a reply indicating whether your source code solved the problem, and if not, an indication of whatwas wrong with it.

• Your programs can be written in either C, C++, Java, or Python.

• Your programs should read data from standard input (stdin) and write to standard ouput (stdout).

Happy coding!

This work by Scrool is licensed under a CC Attribution-Share Alike 2.5 Sweden License.

This page is intentionally left (almost) blank.

Spotify Programming Challenge 2011 Problem A: All Just A Dream 1

Problem AAll Just A DreamProblem ID: dream

Time limit: 2 seconds

Picture in Public Domain via Wikimedia Commons

A common plot device in story-telling is the “All Just A Dream” trope. Typ-ical symptoms of this trope being used are talking lions, main characters dy-ing, yodeling aliens on monocycles, and a general plethora of weird events.Then, of course, someone wakes up and it is revealed that everything thathappened during the entire season did in fact not happen at all. It was AllJust A Dream (or some kind of hallucination), and the days of our lives spentwatching all those episodes are lost forever. In order to cause further confu-sion and uncertainty, this can also be done in layers, with characters havingdreams within dreams within dreams, and so on.

When the All Just A Dream trick is taken too far and gets used too often,it can get difficult to keep track of what has actually happened. This is whereyou enter the picture. You will be given a list of events, dreams, and scenarios.Each scenario specifies some events that have happened and some others thathave not happened. Your job is to determine for each scenario whether thatscenario is possible (possibly using the All Just A Dream trick).

Input

The first line of input consists of an integer 1 ≤ n ≤ 50 000, the number ofevents, dreams and scenarios. Then follow n lines, giving the events, dreams,and scenarios in chronological order. Each line is in one of the followingforms:

• An event line is of the form “E e”, indicating that event e happens (see below for format of e).

• A dream line is of the form “D r”, indicating that the last r events that happened were All Just A Dream.Note that these events are now considered to not have happened, so they should not be counted whenprocessing subsequent D lines.

• A scenario line is of the form “S k e1 . . . ek”, where 1 ≤ k ≤ 30 is an integer giving the number ofevents and e1, . . . , ek is the list of events of the scenario. In a scenario, each event may be prefixed with a‘!’, indicating that the event did not happen in this scenario.

Events are strings containing at most 20 characters and using only the characters ‘a’-‘z’ and underscores (‘ ’).For ‘D’ lines, you can assume that r is an integer between 1 and R, where R is the total number of events that havehappened so far (and that have not turned out to be a dream). For ‘E’ lines, you can assume that e is not an eventthat has already happened, except if the previous occurence of the event turned out to be a dream, in which case itcan happen again.

Warning

This problem has somewhat large amounts of input and output. We recommend you to make sure that yourinput and output are properly buffered in order to make the most of the few seconds of execution time that wegive you. For some advice on I/O performance in Java, see https://spc11.contest.scrool.se/doc/javaio. For some advice on I/O performance in C++, see https://spc11.contest.scrool.se/doc/iostreamio (where the two last items are most relevant for this problem).

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

Spotify Programming Challenge 2011 Problem A: All Just A Dream 2

Output

For each scenario in the input, output a line as follows:

• “Yes” if the given scenario is consistent with what has happened so far.

• “r Just A Dream” if the given scenario would be consistent with what has happened so far, provided a“D r” line had occurred just before the scenario. If there are many possible values of r, choose the smallestvalue. Note that you should not consider this hypothetical “D r” line to have occurred (as illustrated bysample input 2 below).

• “Plot Error” otherwise.

Sample input 1 Sample output 110E business_as_usualE bobby_diesS 1 bobby_diedE stuff_happensE jr_does_bad_thingsS 2 !bobby_dies business_as_usualE it_goes_on_and_onD 4S 1 !bobby_diesS 2 !bobby_dies it_goes_on_and_on

Plot Error3 Just A DreamYesPlot Error

Sample input 2 Sample output 211S 1 !somethingE oneE twoE threeE fourE fiveS 3 three !four oneD 1S 3 three !four oneD 1S 3 three !four one

Yes2 Just A Dream1 Just A DreamYes

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

Spotify Programming Challenge 2011 Problem B: Imperial Measurement 3

Problem BImperial MeasurementProblem ID: measurement

Time limit: 1 secondsThe traditional imperial system has eight units of dis-tance (excluding maritime units and some units used insurveying), related as follows:

thou (th)inch (in) 1000 thousfoot (ft) 12 inchesyard (yd) 3 feetchain (ch) 22 yardsfurlong (fur) 10 chainsmile (mi) 8 furlongsleague (lea) 3 miles

Given a distance measured in one of these units, can youfigure out what it will be in another unit?

Photo by William Warby (wwarby) on flickr

Input

The input consists of a single line of the form “d u in v”, where 1 ≤ d ≤ 100 is an integer amount and u, vare any of the units listed above, indicating that we are converting d u’s into v’s. Units are given either by theirfull name or by their acronym, but will always be given in singular using only lower case letters.

Output

Output the distance converted into v. You do not need to worry about the precise formatting of the answer (e.g.,number of decimals), but either the absolute error or the relative error of your output must be smaller than 10−9.

Sample input 1 Sample output 142 ft in inch 504

Sample input 2 Sample output 210 furlong in lea 0.4166666666667

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

This page is intentionally left (almost) blank.

Spotify Programming Challenge 2011 Problem C: Wheel Game 5

Problem CWheel Game

Problem ID: wheelgameTime limit: 1 seconds

It’s yet another rainy day in 1959, there are no video games, and you are stuck indoors playing a game with afriend. The game is played using an even number 2n of sticks, laid out on a table to form a wheel with n spokesas shown in the figure below.

You and your friend take turns removing sticks (you always start, since you are you). The rules are simple:each turn, the current player selects one of the remaining sticks. She then removes this stick and all sticks touchingthe selected stick. This goes on until there are no sticks left, and the player who removed the last stick is declaredthe winner.

(a) A wheel with 5 spokes (b) What remains after the grey stick is selected

After a while, this gets boring, and you start fantasizing about what the world will be like in the 21st century:no doubt there will be robots to play stick games with instead of plain old friends. Oh what jolly fun it would be!But what if the robots are super smart? Then you would never be able to win. That wouldn’t be very fun.

Write a program which, given the value of n, determines whether you would have any possibility of winningwhen playing against a robot, or whether you would lose no matter what you do. Assume that the robot is cleverenough to always play optimally, and unemotional enough that it would never intentionally lose just to make youfeel better.

Input

The input consists of a single integer n between 3 and 500 000, inclusive. (You may complain that it is impossibleto lay out that many sticks to form something resembling a wheel, but recall that this took place in 1959 – thetimes were different back then.)

Output

Output a single line, containing “The robot is your friend” if it is possible for you to win, or “Destroythe robot before it is too late” if the robot would win no matter how you play.

Sample input 1 Sample output 15 Destroy the robot before it is too late

Sample input 2 Sample output 26 The robot is your friend

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

This page is intentionally left (almost) blank.

Spotify Programming Challenge 2011 Problem D: Primary Registers 7

Problem DPrimary RegistersProblem ID: register

Time limit: 1 seconds

Picture in public domain via Wikimedia Commons

We’re working on a new super-computer, built to un-leash the hidden computing powers of all eight dimen-sions of reality. The secret to utilizing more dimen-sions turns out to be to use counting registers of differ-ent sizes. In particular, we have eight registers, count-ing cyclically modulo the different primes 2, 3, 5, 7,11, 13, 17, 19. A size p register stores a value between0 and p− 1 (inclusive).

The only operation available is an “increment” op-eration. When it is performed, the size 2 register is in-creased by 1. If this increment causes overflow (i.e., ifthe old value was 1) the value is reset to 0, and the size3 is incremented. If this causes overflow the size 3 reg-ister is reset to 0 and the size 5 register is incremented,and so on. If this goes all the way to the last registerand the size 19 register overflows, the computer blowsup.

In order not to destroy the computer in testing, we need to build a program to check the safety of doingincrement operations before we perform them. Given the current state of the registers, you need to compute howmany more operations can safely be performed before the computer blows up.

Input

The input consists of a single line containing eight integers v2, v3, v5, v7, v11, v13, v17, v19 indicating the currentvalues of the registers. The value of the size p register is always between 0 and p− 1 (inclusive).

Output

Ouput a single line containing an integer N , the number of additional operations that can be performed withoutthe computer blowing up.

Sample input 1 Sample output 10 0 4 6 10 12 16 18 5

Sample input 2 Sample output 21 2 4 6 10 12 16 18 0

Sample input 3 Sample output 30 0 0 0 0 0 0 0 9699689

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

This page is intentionally left (almost) blank.

Spotify Programming Challenge 2011 Problem E: Playlist 9

Problem EPlaylist

Problem ID: playlistTime limit: 20 seconds

Photo by Anonymous Account on flickr

You have been invited to host a famous radio showto tell your fascinating life story and play some ofyour favorite songs. However, choosing which songsto play is turning out to be very tricky; there are justway too many good songs and you only have enoughtime to play a measly nine songs!

In order to give the show a sense of continuity,you have decided that consecutive songs you playshould have some detail in common. For instance,if you start by playing Bjork’s song “Pagan Poetry”,you could continue with next playing matmos’ track“Enigma Machine for Alan Turing” since matmos con-tributed to Bjork’s Vespertine album (on which PaganPoetry appears). Continuing, you might play a part ofProkofiev’s “Pet� i volk”, as it was written in 1936,the same year as Alan Turing’s seminal paper on un-decidability of the Halting Problem, and so on. Theordering of the songs is important, so just because youcould play song X after song Y it will not necessarilybe the case that you can play song Y after song X. At the same time as achieving this sense of continuity, you alsowant the playlist to have a bit of variation, so all nine songs must be by different artists.

You have narrowed things down to a bunch of your favorite songs, but finding a list of nine songs with acommon thread seems tricky. Maybe you could use your programming skills to find a good playlist?

Input

The first line of input consists of an integer n (9 ≤ n ≤ 100), the number of songs. Then follow n lines. Each linedescribes a song, starting with the name of the artist (as a string of ‘a’-‘z’ of at most 15 characters), followed byan integer t (0 ≤ t ≤ 40), the number of songs that can be played directly after this song. Then follows (on thesame line) t distinct integers s1, . . . , st, each between 1 and n, giving the numbers of the songs that can be playedafter the current song. The songs are numbered from 1 to n, with song number 1 being described on the first line,and so on.

Output

If there is a playlist of nine songs satisfying the requirements, output a list of nine integers giving the numbersof the songs (according to the same numbering as in the input), in the order they should be played. Otherwise,output a single line containing the word “fail”. If there is more than one valid playlist, any one of them will beaccepted.

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

Spotify Programming Challenge 2011 Problem E: Playlist 10

Sample input 1 Sample output 110a 2 10 3b 1 6c 2 1 5d 1 9e 1 4f 1 2g 2 6 8h 0i 1 3j 1 7

5 4 9 3 1 10 7 6 2

Sample input 2 Sample output 210a 2 10 3a 1 6c 2 1 5d 1 9e 1 4f 1 2g 2 6 8h 0i 1 3j 1 7

fail

Sample input 3 Sample output 310a 2 10 3b 1 6c 2 1 5d 1 9e 1 9f 1 2g 2 6 8h 0i 1 3j 1 7

fail

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

Spotify Programming Challenge 2011 Problem F: Pie Squares 11

Problem FPie SquaresProblem ID: pie

Time limit: 5 seconds

You are working on an OCR (Optical Character Recognition) application to convert scanned images into textformat. In addition to just being able to parse text, you plan to have your software recognize graphs and transcribethem in a meaningful way. Having already handled histograms, bar graphs, scatter plots and regular pie charts,you have now worked your way to square pie charts.

A square pie chart consists of a rectangle subdivided into regions by horizontal or vertical lines. Just like aregular pie chart, the different regions represents how large fractions of something (e.g., baked desserts) are takenup by various subcategories (e.g., pies, cookies, etc). See the figure below for an example.

Lies: 33.3%

Cookies: 25.0%Pies: 16.7%

Pastries: 16.7%

Cake:8.3%

Figure F.1: A square pie chart. This is a drawing of the second example case.

The module you are working on will be given a set of horizontal and vertical line segments forming a squarepie chart, and should compute the sizes of the different regions of the chart.

The set of line segments is guaranteed to have been constructed as described above. In other words, four ofthem form a rectangle constituting the boundary of the square pie chart, and then each remaining line segmentdivides one rectangle into two smaller ones. Note that this means that the line segments do not intersect, exceptthat the endpoints of each line segment touches some other line segment. However, the order of the line segmentsin the input is completely arbitrary and you can not assume that they are given in the order they were drawn.

Input

The first line of input consists of a single integer n (4 ≤ n ≤ 100 000), the number of lines of the pie chart. Eachof the following n lines consists of four integers x1, y1, x2, y2, indicating a line segment from (x1, y1) to (x2, y2).The line segment is either horizontal (i.e., x1 6= x2 and y1 = y2) or vertical (i.e., x1 = x2 and y1 6= y2). Eachcoordinate is at most 109 in absolute value.

Warning

This problem has somewhat large amounts of input and output. We recommend you to make sure that yourinput and output are properly buffered in order to make the most of the few seconds of execution time that wegive you. For some advice on I/O performance in Java, see https://spc11.contest.scrool.se/doc/javaio. For some advice on I/O performance in C++, see https://spc11.contest.scrool.se/doc/iostreamio (where the third item is the most relevant for this problem).

Output

If there are m regions in the pie chart, the output should consist of m lines, giving the sizes of the different regions(as fractions of the entire chart), in non-increasing order. You do not need to worry about the precise formattingof the sizes (e.g., number of decimals), but the absolute error of each size must be smaller than 10−9.

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

Spotify Programming Challenge 2011 Problem F: Pie Squares 12

Sample input 1 Sample output 140 0 6 06 0 6 66 6 0 60 6 0 0

1

Sample input 2 Sample output 286 2 0 20 0 6 00 2 0 02 2 2 13 1 3 00 1 6 16 0 6 22 1 2 0

0.3333333333330.25000.16666666670.166666666670.0833333333

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

Spotify Programming Challenge 2011 Problem G: Peer Streaming 13

Problem GPeer Streaming

Problem ID: streamingTime limit: 3 seconds

Photo by Tanbir Ahmed via Wikimedia Commons

You are developing software to stream music to users overthe Interwebs. In order to reduce network traffic for yourservers, you plan to do this in a peer-to-peer way: a userwho has listened to a given song for a while longer thansome other user will have parts of the song that the seconduser needs and can send them to her directly.

It is now time to develop the logic to decide which usersshould send which data to which other users. At a high level,the logic works as follows. Each second, the data availableat the different users listening to a song is examined. Basedon this, the system decides what data users should transmit,and to whom.

To be specific, suppose there are n users currently lis-tening to the song. The i’th user’s playback is currently atthe pi’th byte of the song, and has already received the firstbi ≥ pi bytes of the song, and no other parts of the song. Furthermore, each user has a bandwidth ui boundinghow many bytes she can upload in total to other users during the one second interval. After one second, each user’splayback will be C bytes further, i.e., the i’th user will be at byte pi + C. Each user now has the first b′i bytes ofthe song, where b′i depends exactly on what data was received from other users during the second. Thus, after theone second interval, the buffer that the i’th user has is b′i − (pi +C) bytes. During the one second interval, a usercan only upload data that she had before the interval started (i.e., from the first bi bytes of the song). A user cansend data to any number of other users, but in order to send a piece of data to several users it needs to be sent toeach user individually.

In order to minimize the risk for jitter, the system should make sure that each user’s buffer is as large aspossible. Specifically, the goal is to make sure that after the second has passed, the minimum buffer size b′i− (pi+C) is as large as possible. Note that it may be the case that this value is negative, indicating that it is impossible toavoid that some user runs out of buffer during the one second interval.

For simplicity, we’ll assume that this takes place on the Interwebs of an alternate reality where upload speedsare completely captured by the ui parameters (e.g., they do not depend on where the data is being uploaded to),and there are no such things as packet losses, slow ping times, or anything else that might make the idealizedsituation described here unrealistic.

Input

The first line of input contains two integers n (1 ≤ n ≤ 50 000) and C (1 ≤ C ≤ 109). Then follow n lines. Thei’th of these lines contains the three integers pi, bi, ui with meanings as described above. You may assume that0 ≤ pi ≤ bi ≤ 109, and 0 ≤ ui ≤ 109.

Warning

This problem has somewhat large amounts of input. We recommend you to make sure that your input is properlybuffered in order to make the most of the few seconds of execution time that we give you. For some adviceon I/O performance in Java, see https://spc11.contest.scrool.se/doc/javaio. For some adviceon I/O performance in C++, see https://spc11.contest.scrool.se/doc/iostreamio (where thethird item is the most relevant for this problem).

Output

Output a single line containing an integer B, the maximum possible smallest buffer size after one second.

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

Spotify Programming Challenge 2011 Problem G: Peer Streaming 14

Sample input 1 Sample output 13 2050 70 10100 110 4150 190 16

5

Sample input 2 Sample output 24 1000 50 1000 50 1000 50 1001000 1500 100

-17

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

Spotify Programming Challenge 2011 Problem H: Cat Coat Colors 15

Problem HCat Coat ColorsProblem ID: catcoat

Time limit: 1 seconds

Photo by Pedro Ribeiro Simoes (pedrosimoes7) on flickr

The color of a cat is primarily decided by three genes,coding for Black (Eumelanin), Red (Phaeomelanin)and Dilution (Melanophilin). The cat genetics expertsamong the readers will note that we are ignoring awide range of genes, e.g., Tyrosinase and the whitemasking gene – we apologize in advance for the over-simplifications that are to ensue.

Black is usually written as B, Red as O, Dilutionas D. In general, a cat has two copies of each gene,one from each parent (except for the red gene whichis sex-bound, we’ll return to that later). Each copycan be either dominant, which we’ll denote using anupper case letter, or recessive, which we’ll denote using a lower case letter. Thus for each gene there are threepossibilities: either both copies of the gene are dominant, both are recessive, or one is dominant and the other isrecessive. When describing a cat we’ll write this as a pair of letters, with the second one possibly being a “-” toindicate a wildcard. For example, “bb” indicates that the cat has two recessive black genes, and “B-” indicatesthat the cat has a dominant black gene and that we don’t care about whether the other one is dominant or recessive.

When a cat has no dominant red (O) gene, its coat will be a variation of black, according to the following fourcombinations:

B-D-: Black B-dd: BluebbD-: Chocolate bbdd: Lilac

Now, red (O or o) is sex bound on the X chromosone. This means a male cat, or tom, only has a single redgene, while a female has two. Red dominates black, meaning that a cat having an O gene will always have redcoloring. Like black, red is also affected by the dilution gene. For male cats, we have the following two possiblered colors (here, the black genes have no effect on the coat color):

D-O: Red ddO: Cream

For female cats the situation gets a bit more complicated. If the female has two O genes she will be be red,with variations depending on the dilution gene in exactly the same way as for male red cats:

D-OO: Red ddOO: Cream

However, a female cat with the Oo combination will have a partially black, partially red, coat. These catsare known as Torties (Tortoiseshells), and named after both their coat colours, starting with the black. The fourpossible Tortie colorings are thus as follows:

B-D-Oo: Black-Red Tortie B-ddOo: Blue-Cream TortiebbD-Oo: Chocolate-Red Tortie bbddOo: Lilac-Cream Tortie

When a pair of cats have kittens, the offspring will get a random set of genes from their parents according tothe following simple process: for each gene, independendtly, one of the copies is selected uniformly at randomfrom the father’s two copies, and the other copy is selected uniformly at random from the mother’s two copies.For the red gene, there is a 50% chance that the offspring will be female in which case it will get the father’s redgene (and one of the mother’s red genes at random), and a 50% chance that the offspring will be male in whichcase it will only get one of the mother’s red genes (at random).

Write a program which, given the colors of two cats, computes the most likely color for their offspring. Forcats having a color where some genes do not affect the color, assume that the corresponding genes are uniformlyrandom (over the two choices dominant/recessive). For example, if a cat is red, you should assume that thepossibilities “DD” and “Dd” for the dilution gene are equally likely, and that the four possibilities “BB”, “Bb”,“bB” and “bb” are equally likely for the black gene (but note that “Bb” and “bB” are equivalent).

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.

Spotify Programming Challenge 2011 Problem H: Cat Coat Colors 16

Input

The input consists of two lines. The first line gives the color of the female cat, and the second line gives the colorof the male cat. Each color is spelled and capitalized exactly as when it is listed above, and the color is valid (i.e.,the male cat won’t be a Tortie).

Output

Output a list of the possible color outcomes for the offspring of the two cats. Each line should contain a colorfollowed by a number 0 < p ≤ 1 indicating the probability of this particular outcome.

The list should be sorted first in decreasing order by probability, then in alphabetic order by name (see sampleinput 3 below). You do not need to worry about the precise formatting of the probabilities (e.g., number ofdecimals), but the absolute error of each probability must be smaller than 10−9.

Sample input 1 Sample output 1RedRed

Red 0.937500000Cream 0.062500000

Sample input 2 Sample output 2Lilac-Cream TortieBlue

Blue 0.375000000Cream 0.250000000Blue-Cream Tortie 0.187500000Lilac 0.125000000Lilac-Cream Tortie 0.062500000

Sample input 3 Sample output 3BlueRed

Black 0.328125000Black-Red Tortie 0.328125000Blue 0.109375000Blue-Cream Tortie 0.109375000Chocolate 0.046875000Chocolate-Red Tortie 0.046875000Lilac 0.015625000Lilac-Cream Tortie 0.015625000

This work by Scrool is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.